/* ===========================================================
   Halvorsen — Locations + FAQ + Contact + Booking modal + Footer
   =========================================================== */

const LOCATIONS = [
  {
    city: "London",
    addr: "33 Grosvenor Place\nLondon SW1X 7HY",
    days: "Mon · Tue · Thu",
    consult: "Cleveland Clinic London",
    surgery: "Cleveland Clinic London",
    tel: "+44 (0)20 7946 0214",
    motif: "knee",
  },
  {
    city: "Oslo",
    addr: "Hansteens gate 5\n0253 Oslo, Norway",
    days: "Wed · Fri",
    consult: "Volvat Oslo",
    surgery: "Volvat Oslo",
    tel: "+47 22 95 75 00",
    motif: "shoulder",
  },
  {
    city: "Telemedicine",
    addr: "Worldwide\nSecond opinions only",
    days: "Friday afternoons",
    consult: "Encrypted video",
    surgery: "—",
    tel: "—",
    motif: "hip",
  },
];

const Locations = () => {
  const [active, setActive] = React.useState(0);
  const cur = LOCATIONS[active];
  const Motif = { knee: KneeMotif, shoulder: ShoulderMotif, hip: HipMotif }[cur.motif];
  return (
    <section id="locations" style={{ padding: "120px 32px", maxWidth: 1400, margin: "0 auto" }}>
      <div className="reveal" style={{ marginBottom: 56 }}>
        <Chapter num={8} label="Locations" />
        <h2 className="serif" style={{ margin: "20px 0 0", fontSize: "clamp(36px, 4.8vw, 64px)", lineHeight: 1, letterSpacing: "-0.015em", fontWeight: 400 }}>
          Two clinics, one <span style={{ fontStyle: "italic", color: "var(--sage-deep)" }}>standard</span>.
        </h2>
      </div>
      <div className="reveal" style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 64 }}>
        <div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
            {LOCATIONS.map((l, i) => (
              <li
                key={l.city}
                onClick={() => setActive(i)}
                tabIndex={0}
                onKeyDown={(e) => { if (e.key === "Enter") setActive(i); }}
                style={{
                  padding: "32px 24px",
                  borderTop: "1px solid var(--line)",
                  borderBottom: i === LOCATIONS.length - 1 ? "1px solid var(--line)" : "none",
                  background: active === i ? "var(--bone)" : "transparent",
                  cursor: "pointer",
                  display: "grid",
                  gridTemplateColumns: "60px 1fr auto",
                  alignItems: "baseline",
                  transition: "background 280ms var(--ease)",
                }}
              >
                <span className="mono" style={{ fontSize: 11, color: "var(--sand-deep)" }}>{String(i + 1).padStart(2, "0")}</span>
                <div>
                  <div className="serif" style={{ fontSize: 32, lineHeight: 1.1 }}>{l.city}</div>
                  <div className="mono" style={{ fontSize: 11, color: "var(--ink-muted)", marginTop: 6, letterSpacing: "0.08em", textTransform: "uppercase" }}>{l.consult}</div>
                </div>
                <div className="mono" style={{ fontSize: 11, color: "var(--ink-soft)", letterSpacing: "0.18em", textTransform: "uppercase" }}>{l.days}</div>
              </li>
            ))}
          </ul>
        </div>

        <div style={{ position: "sticky", top: 120, alignSelf: "start" }}>
          <div style={{ aspectRatio: "1/1", border: "1px solid var(--line)", padding: 32, background: "var(--bone)", color: "var(--ink-2)", position: "relative", display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
            <div style={{ display: "flex", justifyContent: "space-between" }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: "0.2em", color: "var(--ink-soft)", textTransform: "uppercase" }}>
                Clinic · {cur.city}
              </div>
              <Crosshair size={18} style={{ color: "var(--sand-deep)" }} />
            </div>
            <div style={{ display: "grid", placeItems: "center", flex: 1 }}>
              <Motif size={220} />
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
              <div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: "0.18em", color: "var(--ink-muted)", textTransform: "uppercase" }}>Address</div>
                <div style={{ fontSize: 13, marginTop: 4, whiteSpace: "pre-line" }}>{cur.addr}</div>
              </div>
              <div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: "0.18em", color: "var(--ink-muted)", textTransform: "uppercase" }}>Telephone</div>
                <div style={{ fontSize: 13, marginTop: 4 }}>{cur.tel}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

/* ---------- FAQ ---------- */
const FAQS = [
  { q: "How quickly can I be seen?", a: "Initial consultations are typically available within 7–10 days in London and 3–5 days in Oslo. Urgent sports injuries are triaged within 48 hours." },
  { q: "Do you take insurance?", a: "Yes — Bupa, AXA Health, Aviva, Vitality, WPA, Cigna, Allianz Care, and most international policies. We provide pre-authorisation paperwork on your behalf." },
  { q: "Will my surgeon perform my surgery?", a: "Always. Dr. Halvorsen performs every operation she books. Trainees may assist; nobody else is the lead." },
  { q: "What about second opinions?", a: "Strongly encouraged. Friday telemedicine slots are reserved exclusively for second opinions on existing recommendations." },
  { q: "Do you publish your data?", a: "Yes. The full registry — including complications, revisions, and PROMs — is updated quarterly and available on request." },
  { q: "What is the cost?", a: "Initial consultation is £280 / NOK 3,400. Surgery is quoted in writing after consultation, with itemised theatre, implant and rehabilitation fees." },
];

const FAQ = () => {
  const [open, setOpen] = React.useState(0);
  return (
    <section id="faq" style={{ padding: "120px 32px", borderTop: "1px solid var(--line)", background: "var(--bone)" }}>
      <div style={{ maxWidth: 1100, margin: "0 auto" }}>
        <div className="reveal" style={{ marginBottom: 56 }}>
          <Chapter num={9} label="Plain Answers" />
          <h2 className="serif" style={{ margin: "20px 0 0", fontSize: "clamp(36px, 4.8vw, 64px)", lineHeight: 1, letterSpacing: "-0.015em", fontWeight: 400 }}>
            What patients <span style={{ fontStyle: "italic", color: "var(--sage-deep)" }}>actually</span> ask.
          </h2>
        </div>
        <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
          {FAQS.map((f, i) => (
            <li key={i} style={{ borderTop: "1px solid var(--line)", borderBottom: i === FAQS.length - 1 ? "1px solid var(--line)" : "none" }}>
              <button
                onClick={() => setOpen(open === i ? -1 : i)}
                aria-expanded={open === i}
                style={{ width: "100%", textAlign: "left", padding: "28px 0", background: "transparent", border: "none", cursor: "pointer", color: "var(--ink)", display: "grid", gridTemplateColumns: "40px 1fr 30px", gap: 16, alignItems: "baseline" }}
              >
                <span className="mono" style={{ fontSize: 11, color: "var(--sand-deep)" }}>{String(i + 1).padStart(2, "0")}</span>
                <span className="serif" style={{ fontSize: 28, lineHeight: 1.2 }}>{f.q}</span>
                <span style={{ fontSize: 22, color: "var(--ink-soft)", transform: open === i ? "rotate(45deg)" : "none", transition: "transform 280ms var(--ease)" }}>+</span>
              </button>
              <div style={{ overflow: "hidden", maxHeight: open === i ? 200 : 0, transition: "max-height 480ms var(--ease)" }}>
                <div style={{ paddingLeft: 56, paddingBottom: 28, paddingRight: 56, fontSize: 16, lineHeight: 1.6, color: "var(--ink-soft)", maxWidth: 720 }}>
                  {f.a}
                </div>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
};

/* ---------- CONTACT / REFERRAL FORM ---------- */
const Contact = ({ onBook }) => (
  <section id="contact" style={{ padding: "140px 32px 100px", maxWidth: 1400, margin: "0 auto" }}>
    <div className="reveal" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80, alignItems: "start" }}>
      <div>
        <Chapter num={10} label="Begin" />
        <h2 className="serif" style={{ margin: "20px 0 0", fontSize: "clamp(48px, 6vw, 96px)", lineHeight: 0.95, letterSpacing: "-0.02em", fontWeight: 400 }}>
          A 45-minute conversation is the place to <span style={{ fontStyle: "italic", color: "var(--oxblood)" }}>start</span>.
        </h2>
        <div style={{ marginTop: 36, fontSize: 16.5, lineHeight: 1.6, color: "var(--ink-soft)", maxWidth: 480 }}>
          Tell us a little about what brought you here. A member of the team will reply within one working day with available consultation slots.
        </div>
        <div style={{ marginTop: 48, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, paddingTop: 32, borderTop: "1px solid var(--line)" }}>
          <Detail k="General enquiries" v="hello@halvorsen.clinic" />
          <Detail k="Referrals (GP / Dr.)" v="referrals@halvorsen.clinic" />
          <Detail k="Press" v="press@halvorsen.clinic" />
          <Detail k="Emergency" v="999 or A&E. We do not run emergency lines." />
        </div>
      </div>
      <form onSubmit={(e) => { e.preventDefault(); onBook(); }} style={{ display: "flex", flexDirection: "column", gap: 4 }}>
        <Field label="Your name" placeholder="" id="f-name" />
        <Field label="Email" placeholder="" id="f-email" type="email" />
        <Field label="Phone (optional)" placeholder="" id="f-phone" />
        <Field label="Reason for getting in touch" textarea placeholder="" id="f-reason" />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 8 }}>
          <RadioGroup label="Region" name="region" options={["Knee", "Shoulder", "Hip", "Foot/Ankle", "Spine", "Unsure"]} />
          <RadioGroup label="Preferred clinic" name="clinic" options={["London", "Oslo", "Telemedicine"]} />
        </div>
        <button type="submit" className="btn btn-primary" style={{ marginTop: 32, alignSelf: "flex-start", padding: "18px 28px", fontSize: 15 }}>
          Send enquiry <Arrow />
        </button>
      </form>
    </div>
  </section>
);

const Detail = ({ k, v }) => (
  <div>
    <div className="mono" style={{ fontSize: 10, letterSpacing: "0.18em", color: "var(--ink-muted)", textTransform: "uppercase" }}>{k}</div>
    <div style={{ fontSize: 14, marginTop: 6 }}>{v}</div>
  </div>
);

const Field = ({ label, id, textarea, type = "text", placeholder }) => (
  <div style={{ borderBottom: "1px solid var(--line-strong)", padding: "18px 0" }}>
    <label htmlFor={id} className="mono" style={{ display: "block", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 8 }}>
      {label}
    </label>
    {textarea ? (
      <textarea id={id} placeholder={placeholder} rows={3} style={{ width: "100%", border: "none", background: "transparent", color: "var(--ink)", fontFamily: "var(--sans)", fontSize: 16, resize: "vertical", outline: "none" }} />
    ) : (
      <input id={id} type={type} placeholder={placeholder} style={{ width: "100%", border: "none", background: "transparent", color: "var(--ink)", fontFamily: "var(--sans)", fontSize: 16, outline: "none" }} />
    )}
  </div>
);

const RadioGroup = ({ label, name, options }) => {
  const [val, setVal] = React.useState(null);
  return (
    <fieldset style={{ border: "none", padding: 0, margin: "16px 0 0" }}>
      <legend className="mono" style={{ fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 12 }}>{label}</legend>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
        {options.map((o) => (
          <label key={o} style={{ cursor: "pointer" }}>
            <input type="radio" name={name} value={o} onChange={() => setVal(o)} style={{ position: "absolute", opacity: 0, pointerEvents: "none" }} />
            <span style={{ display: "inline-block", padding: "8px 14px", borderRadius: 999, border: "1px solid var(--line-strong)", fontSize: 12.5, background: val === o ? "var(--ink)" : "transparent", color: val === o ? "var(--paper)" : "var(--ink)", transition: "all 200ms var(--ease)" }}>
              {o}
            </span>
          </label>
        ))}
      </div>
    </fieldset>
  );
};

/* ---------- BOOKING MODAL ---------- */
const BookingModal = ({ open, onClose }) => {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({ region: null, clinic: null, when: null, name: "", email: "" });
  const dialogRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    setStep(0);
    setData({ region: null, clinic: null, when: null, name: "", email: "" });
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open) return null;

  const total = 4;
  const next = () => setStep((s) => Math.min(total, s + 1));
  const prev = () => setStep((s) => Math.max(0, s - 1));

  return (
    <div role="dialog" aria-modal="true" aria-label="Request a consultation" ref={dialogRef}
      style={{ position: "fixed", inset: 0, zIndex: 100, display: "grid", placeItems: "center", padding: 24, background: "rgba(15,18,23,0.6)", backdropFilter: "blur(8px)", animation: "fadeIn 240ms var(--ease)" }}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div style={{ width: "min(720px, 100%)", maxHeight: "90vh", overflow: "auto", background: "var(--paper)", border: "1px solid var(--line)", animation: "slideUp 420ms var(--ease)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "20px 28px", borderBottom: "1px solid var(--line)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <span className="mono" style={{ fontSize: 11, letterSpacing: "0.2em", color: "var(--ink-soft)" }}>STEP {step + 1} / {total + 1}</span>
            <div style={{ width: 80, height: 2, background: "var(--line)", borderRadius: 2, overflow: "hidden" }}>
              <div style={{ width: `${((step + 1) / (total + 1)) * 100}%`, height: "100%", background: "var(--ink)", transition: "width 380ms var(--ease)" }} />
            </div>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ background: "transparent", border: "none", color: "var(--ink)", cursor: "pointer", fontSize: 20, padding: 6, lineHeight: 1 }}>×</button>
        </div>

        <div style={{ padding: "40px 48px 48px" }}>
          {step === 0 && (
            <BookStep title="Where does it hurt?" subtitle="We focus on five regions. Choose the closest one — we'll refine in consultation.">
              <ChipRow value={data.region} onChange={(v) => setData({ ...data, region: v })} options={["Knee", "Shoulder", "Hip", "Foot / Ankle", "Spine", "Unsure"]} />
            </BookStep>
          )}
          {step === 1 && (
            <BookStep title="Which clinic suits you?" subtitle="Dr. Halvorsen consults in London (Mon · Tue · Thu) and Oslo (Wed · Fri).">
              <ChipRow value={data.clinic} onChange={(v) => setData({ ...data, clinic: v })} options={["London", "Oslo", "Telemedicine (second opinion only)"]} />
            </BookStep>
          )}
          {step === 2 && (
            <BookStep title="When works best?" subtitle="Indicative — we'll confirm exact slots over email.">
              <ChipRow value={data.when} onChange={(v) => setData({ ...data, when: v })} options={["This week", "Next 2 weeks", "This month", "I'm flexible"]} />
            </BookStep>
          )}
          {step === 3 && (
            <BookStep title="How can we reach you?" subtitle="A real person replies within one working day.">
              <div style={{ display: "grid", gap: 0 }}>
                <Field label="Full name" id="m-name" />
                <Field label="Email address" id="m-email" type="email" />
              </div>
            </BookStep>
          )}
          {step === 4 && (
            <BookStep title="Thank you." subtitle="Your enquiry is in. The team is reading it.">
              <div style={{ marginTop: 24, padding: 28, background: "var(--bone)", border: "1px solid var(--line)" }}>
                <div className="mono" style={{ fontSize: 10, letterSpacing: "0.2em", color: "var(--ink-soft)", textTransform: "uppercase" }}>Reference</div>
                <div className="serif" style={{ fontSize: 32, marginTop: 8 }}>HC-{Math.floor(Math.random() * 9000 + 1000)}</div>
                <div style={{ marginTop: 24, fontSize: 14, lineHeight: 1.6, color: "var(--ink-soft)" }}>
                  We'll be in touch shortly with available consultation slots. If you've not heard from us by tomorrow afternoon, please call the clinic directly.
                </div>
              </div>
            </BookStep>
          )}
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "20px 28px", borderTop: "1px solid var(--line)", background: "var(--bone)" }}>
          <button onClick={step === total ? onClose : prev} disabled={step === 0} style={{ background: "transparent", border: "none", color: "var(--ink)", cursor: "pointer", fontSize: 13, opacity: step === 0 ? 0.3 : 1 }}>
            ← Back
          </button>
          <button
            onClick={step === total ? onClose : next}
            className="btn btn-primary"
            style={{ padding: "12px 22px", fontSize: 13 }}
          >
            {step === total ? "Done" : step === total - 1 ? "Submit" : "Continue"} <Arrow />
          </button>
        </div>
      </div>
      <style>{`
        @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(24px) } to { opacity: 1; transform: translateY(0) } }
      `}</style>
    </div>
  );
};

const BookStep = ({ title, subtitle, children }) => (
  <div>
    <h3 className="serif" style={{ margin: 0, fontSize: 38, lineHeight: 1.1, letterSpacing: "-0.01em", fontWeight: 400 }}>{title}</h3>
    <div style={{ marginTop: 12, fontSize: 15, color: "var(--ink-soft)", lineHeight: 1.5 }}>{subtitle}</div>
    <div style={{ marginTop: 32 }}>{children}</div>
  </div>
);

const ChipRow = ({ options, value, onChange }) => (
  <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
    {options.map((o) => (
      <button
        key={o}
        onClick={() => onChange(o)}
        style={{
          padding: "12px 20px",
          borderRadius: 999,
          border: "1px solid var(--line-strong)",
          background: value === o ? "var(--ink)" : "transparent",
          color: value === o ? "var(--paper)" : "var(--ink)",
          fontSize: 14,
          fontFamily: "var(--sans)",
          cursor: "pointer",
          transition: "all 220ms var(--ease)",
        }}
      >
        {o}
      </button>
    ))}
  </div>
);

/* ---------- FOOTER ---------- */
const Footer = () => (
  <footer style={{ borderTop: "1px solid var(--line)", padding: "80px 32px 40px", background: "var(--bone)" }}>
    <div style={{ maxWidth: 1400, margin: "0 auto" }}>
      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr 1fr", gap: 48, paddingBottom: 56, borderBottom: "1px solid var(--line)" }}>
        <div>
          <Logo />
          <div style={{ marginTop: 24, fontSize: 14, color: "var(--ink-soft)", maxWidth: 320, lineHeight: 1.6 }}>
            Consultant orthopaedic surgery — joint preservation, sports injury and complex revision. Practising in London and Oslo.
          </div>
        </div>
        <FooterCol title="Practice" links={["About", "Procedures", "Outcomes", "Press"]} />
        <FooterCol title="Patients" links={["Patient journey", "Referrals", "Insurance", "FAQ"]} />
        <FooterCol title="Contact" links={["London clinic", "Oslo clinic", "Telemedicine", "Emergency"]} />
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 32, flexWrap: "wrap", gap: 16 }}>
        <div className="mono" style={{ fontSize: 11, color: "var(--ink-muted)", letterSpacing: "0.1em" }}>
          © 2009–2026 HALVORSEN ORTHOPAEDIC LTD · GMC 6041273 · CQC REGISTERED
        </div>
        <div className="mono" style={{ fontSize: 11, color: "var(--ink-muted)", letterSpacing: "0.1em" }}>
          PRIVACY · COOKIES · TERMS · ACCESSIBILITY
        </div>
      </div>
      <div style={{ marginTop: 24, paddingTop: 24, borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: "0.18em", color: "var(--ink-muted)", textTransform: "uppercase" }}>
          A pure concept by <a href="https://beornstudios.com" target="_blank" rel="noopener noreferrer" style={{ color: "var(--oxblood)", textDecoration: "none", borderBottom: "1px solid var(--oxblood)" }}>Beorn Studios</a>
        </div>
        <div className="mono" style={{ fontSize: 11, letterSpacing: "0.18em", color: "var(--ink-muted)", textTransform: "uppercase" }}>
          beornstudios.com ↗
        </div>
      </div>
    </div>
  </footer>
);

const FooterCol = ({ title, links }) => (
  <div>
    <div className="mono" style={{ fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ink-soft)" }}>{title}</div>
    <ul style={{ listStyle: "none", margin: "20px 0 0", padding: 0, display: "flex", flexDirection: "column", gap: 10 }}>
      {links.map((l) => (
        <li key={l}><a href="#" style={{ color: "var(--ink)", textDecoration: "none", fontSize: 14 }}>{l}</a></li>
      ))}
    </ul>
  </div>
);

Object.assign(window, { Locations, FAQ, Contact, BookingModal, Footer });
