/* global React */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ─── Logo ──────────────────────────────────────────────────────────────
function BsaLogo({ height = 36, color = "currentColor" }) {
  // The SVG wordmark already contains "BSA LAW" — render it alone, no duplicated text.
  return (
    <span aria-label="BSA LAW home" style={{ display: "inline-flex", alignItems: "center", lineHeight: 1, color }}>
      <img src="media/logo-bsa-law.svg" alt="BSA LAW" aria-hidden="false"
        style={{ height, width: "auto", display: "block" }} />
    </span>
  );
}

// ─── Section header ───────────────────────────────────────────────────
function SectionHead({ eyebrow, head, sub, align = "left", maxw = 740, onDark }) {
  return (
    <div style={{ textAlign: align, marginBottom: 48, maxWidth: maxw, marginLeft: align === "center" ? "auto" : 0, marginRight: align === "center" ? "auto" : 0 }}>
      {eyebrow && <div className={"eyebrow" + (onDark ? " on-dark" : "")} style={{ marginBottom: 18 }}>{eyebrow}</div>}
      <h2 style={{ fontSize: "clamp(36px, 4.5vw, 60px)", color: onDark ? "var(--on-ink)" : "var(--ink)", letterSpacing: "-0.01em", textWrap: "balance" }}>
        {head}
      </h2>
      {sub && (
        <p style={{ marginTop: 20, fontSize: 17, color: onDark ? "var(--on-ink-mut)" : "var(--muted)", maxWidth: 620, textWrap: "pretty", lineHeight: 1.55, marginInline: align === "center" ? "auto" : 0 }}>
          {sub}
        </p>
      )}
    </div>
  );
}

// ─── Icons (minimal hairline) ─────────────────────────────────────────
const I = {
  arrow: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><path d="M1 7h12M8 2l5 5-5 5" stroke="currentColor" strokeWidth="1.2" /></svg>,
  arrowSm: (p) => <svg width="11" height="11" viewBox="0 0 14 14" fill="none" {...p}><path d="M1 7h12M8 2l5 5-5 5" stroke="currentColor" strokeWidth="1.4" /></svg>,
  close: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.4" /></svg>,
  plus: (p) => <svg width="11" height="11" viewBox="0 0 11 11" fill="none" {...p}><path d="M5.5 1v9M1 5.5h9" stroke="currentColor" strokeWidth="1.2" /></svg>,
  chev: (p) => <svg width="10" height="10" viewBox="0 0 10 10" fill="none" {...p}><path d="M2 3l3 3 3-3" stroke="currentColor" strokeWidth="1.4" fill="none" /></svg>,
  globe: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><circle cx="7" cy="7" r="5.5" stroke="currentColor" strokeWidth="1" /><path d="M1.5 7h11M7 1.5c1.8 2 2.5 4.1 2.5 5.5S8.8 10.5 7 12.5C5.2 10.5 4.5 8.4 4.5 7S5.2 3.5 7 1.5z" stroke="currentColor" strokeWidth="1" fill="none" /></svg>,
  search: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><circle cx="6" cy="6" r="4.5" stroke="currentColor" strokeWidth="1.2" /><path d="M9.5 9.5L13 13" stroke="currentColor" strokeWidth="1.2" /></svg>,
  email: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><rect x="1" y="3" width="12" height="8" stroke="currentColor" strokeWidth="1" /><path d="M1 4l6 4 6-4" stroke="currentColor" strokeWidth="1" /></svg>,
  phone: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><path d="M2 3c0-1 1-2 2-2l1.5 2.5L4 5c0 2 3 5 5 5l1.5-1.5L13 10c0 1-1 2-2 2-5 0-9-4-9-9z" stroke="currentColor" strokeWidth="1" fill="none" /></svg>,
  pin: (p) => <svg width="12" height="14" viewBox="0 0 12 14" fill="none" {...p}><path d="M6 13s5-4.5 5-8a5 5 0 10-10 0c0 3.5 5 8 5 8z" stroke="currentColor" strokeWidth="1" fill="none" /><circle cx="6" cy="5" r="1.5" stroke="currentColor" strokeWidth="1" fill="none" /></svg>,
  scroll: (p) => <svg width="12" height="20" viewBox="0 0 12 20" fill="none" {...p}><rect x="1" y="1" width="10" height="18" rx="5" stroke="currentColor" strokeWidth="1" /><line x1="6" y1="5" x2="6" y2="9" stroke="currentColor" strokeWidth="1.5"><animate attributeName="y1" values="5;9;5" dur="2s" repeatCount="indefinite" /><animate attributeName="y2" values="9;11;9" dur="2s" repeatCount="indefinite" /></line></svg>,
  linkedin: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor" {...p}><path d="M2 12V5h2v7H2zm1-8a1 1 0 110-2 1 1 0 010 2zm10 8h-2V8.5c0-1 0-1.5-1-1.5s-1 .5-1 1.5V12H7V5h2v1c.3-.5 1-1 2-1 2 0 2 1.5 2 3V12z" /></svg>,
};

// ─── Modal ────────────────────────────────────────────────────────────
function Modal({ open, onClose, children, side = "right" }) {
  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const esc = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", esc);
    return () => { document.body.style.overflow = prev; window.removeEventListener("keydown", esc); };
  }, [open, onClose]);

  if (!open) return null;
  return (
    <React.Fragment>
      <div className="modal-backdrop" onClick={onClose} />
      <div className="modal-panel" role="dialog" aria-modal="true">
        <button onClick={onClose} aria-label="Close"
          style={{ position: "absolute", top: 24, right: 24, background: "transparent", border: 0, color: "var(--ink)", padding: 8, display: "inline-flex" }}>
          <I.close />
        </button>
        {children}
      </div>
    </React.Fragment>
  );
}

// ─── Enquiry Form ─────────────────────────────────────────────────────
function EnquiryForm({ presetLawyer, presetPractice, presetOffice, t }) {
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({
    name: "",
    org: "",
    email: "",
    phone: "",
    practice: presetPractice || "",
    lawyer: presetLawyer || "",
    office: presetOffice || "",
    message: "",
    consent: false,
  });
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.type === "checkbox" ? e.target.checked : e.target.value }));
  const submit = (e) => { e.preventDefault(); setSubmitted(true); };

  if (submitted) {
    return (
      <div style={{ padding: "60px 48px" }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>Received</div>
        <h3 style={{ fontSize: 30, marginBottom: 16 }}>Thank you.</h3>
        <p style={{ color: "var(--muted)", fontSize: 16, marginBottom: 24, maxWidth: 360 }}>
          Your enquiry has been routed to the appropriate partner. We typically respond within one business day.
        </p>
        <button className="btn btn-ghost" onClick={() => { setSubmitted(false); setForm({ name: "", org: "", email: "", phone: "", practice: "", lawyer: "", office: "", message: "", consent: false }); }}>
          New enquiry
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={submit} style={{ padding: "60px 48px 48px" }}>
      <div className="eyebrow" style={{ marginBottom: 14 }}>{t.consult}</div>
      <h3 style={{ fontSize: 32, marginBottom: 8 }}>{t.enquireHead}</h3>
      <p style={{ color: "var(--muted)", fontSize: 14, marginBottom: 32, maxWidth: 380 }}>
        {t.enquireSub}
      </p>

      <div className="field"><label>Full name</label><input required value={form.name} onChange={set("name")} /></div>
      <div className="field"><label>Organisation</label><input value={form.org} onChange={set("org")} /></div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <div className="field"><label>Email</label><input type="email" required value={form.email} onChange={set("email")} /></div>
        <div className="field"><label>Phone</label><input value={form.phone} onChange={set("phone")} /></div>
      </div>
      <div className="field"><label>Practice area</label>
        <select value={form.practice} onChange={set("practice")}>
          <option value="">— Any practice —</option>
          {window.SERVICES.map((s) => <option key={s.slug} value={s.name}>{s.name}</option>)}
        </select>
      </div>
      <div className="field"><label>Office</label>
        <select value={form.office} onChange={set("office")}>
          <option value="">— No preference —</option>
          {window.OFFICES.map((o) => <option key={o.slug} value={o.city}>{o.city}</option>)}
        </select>
      </div>
      {presetLawyer && (
        <div className="field"><label>Lawyer</label><input value={form.lawyer} readOnly /></div>
      )}
      <div className="field"><label>Message</label><textarea value={form.message} onChange={set("message")} placeholder="Brief outline of your matter (no privileged details required at this stage)" /></div>

      <label style={{ display: "flex", gap: 12, alignItems: "flex-start", margin: "8px 0 28px", fontSize: 13, color: "var(--muted)", lineHeight: 1.5 }}>
        <input type="checkbox" required checked={form.consent} onChange={set("consent")} style={{ marginTop: 3 }} />
        <span>I consent to BSA LAW processing this enquiry in line with the firm's privacy notice.</span>
      </label>

      <button type="submit" className="btn" style={{ width: "100%" }}>
        Submit enquiry <I.arrow />
      </button>
      <p style={{ fontSize: 12, color: "var(--muted-2)", marginTop: 18, lineHeight: 1.5 }}>
        For urgent matters call the relevant office direct. Engagements are by consultation — no fees apply to the enquiry itself.
      </p>
    </form>
  );
}

// ─── Lawyer card ──────────────────────────────────────────────────────
function LawyerCard({ p, onOpen, t }) {
  return (
    <article style={{ display: "flex", flexDirection: "column", cursor: "pointer", background: "transparent" }} onClick={() => onOpen(p)}>
      <div style={{ position: "relative", aspectRatio: "4/5", overflow: "hidden", background: "var(--stone)" }}>
        <img src={p.img} alt={p.name} loading="lazy"
          style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center top", filter: "grayscale(0.15) contrast(0.95)", transition: "transform .6s ease" }}
          onMouseEnter={(e) => e.currentTarget.style.transform = "scale(1.03)"}
          onMouseLeave={(e) => e.currentTarget.style.transform = "scale(1)"}
        />
        {p.credentials.find((c) => c.toLowerCase().includes("chambers") || c.toLowerCase().includes("legal 500")) && (
          <div style={{ position: "absolute", top: 14, left: 14, padding: "5px 10px", background: "var(--paper)", color: "var(--ink)", fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase" }}>
            Ranked
          </div>
        )}
      </div>
      <div style={{ paddingTop: 18 }}>
        <h3 style={{ fontFamily: "var(--serif)", fontSize: 24, fontWeight: 400, color: "var(--ink)", marginBottom: 4 }}>{p.name}</h3>
        <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)" }}>
          {p.role} · {p.office}
        </div>
        <div style={{ marginTop: 10, fontSize: 14, color: "var(--ink-2)", lineHeight: 1.45 }}>
          {p.practices.slice(0, 2).join(" · ")}
        </div>
      </div>
    </article>
  );
}

// ─── Lawyer detail panel (inside modal) ───────────────────────────────
function LawyerDetail({ p, onClose, onEnquire, t }) {
  return (
    <div>
      <div style={{ height: 360, background: "var(--stone)", overflow: "hidden" }}>
        <img src={p.img} alt={p.name} style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 20%" }} />
      </div>
      <div style={{ padding: "40px 48px 48px" }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>{p.role} · {p.office}</div>
        <h2 style={{ fontSize: 40, fontFamily: "var(--serif)", marginBottom: 12 }}>{p.name}</h2>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 24 }}>
          {p.practices.map((pr) => <span key={pr} className="tag">{pr}</span>)}
        </div>

        <p style={{ fontSize: 16, color: "var(--ink-2)", lineHeight: 1.6, marginBottom: 28 }}>{p.bio}</p>

        {p.credentials.length > 0 && (
          <div style={{ marginBottom: 32 }}>
            <div className="eyebrow" style={{ marginBottom: 14 }}>Credentials</div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, borderTop: "1px solid var(--line)" }}>
              {p.credentials.map((c, i) => (
                <li key={i} style={{ padding: "12px 0", borderBottom: "1px solid var(--line)", fontSize: 14, color: "var(--ink-2)", display: "flex", gap: 12, alignItems: "flex-start" }}>
                  <span style={{ color: "var(--accent)", fontFamily: "var(--mono)", fontSize: 11, minWidth: 24 }}>{String(i + 1).padStart(2, "0")}</span>
                  <span>{c}</span>
                </li>
              ))}
            </ul>
          </div>
        )}

        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <button className="btn" onClick={() => onEnquire(p)}>
            {t.contactLawyer} <I.arrow />
          </button>
          <a href={`mailto:${p.email}`} className="link-arrow" style={{ alignSelf: "flex-start" }}>
            <I.email /> {p.email}
          </a>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { BsaLogo, SectionHead, I, Modal, EnquiryForm, LawyerCard, LawyerDetail });
