/* DISC Dubai — UI primitives + chrome */
const { useState, useEffect, useRef, useMemo, Fragment } = React;
const { SERVICES, CONCERNS, LOCATIONS, TEAM } = window.DISC_DATA;

/* ---------------- icons (minimal, monoline) ---------------- */
const Icon = {
  arrow: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 6l6 6-6 6"/></svg>
  ),
  arrowDown: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 5v14M6 13l6 6 6-6"/></svg>
  ),
  phone: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72a2 2 0 0 1 1.72 2z"/></svg>
  ),
  whatsapp: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" {...p}><path d="M12 2a10 10 0 0 0-8.5 15.2L2 22l4.9-1.5A10 10 0 1 0 12 2zm5.2 14.2c-.2.6-1.2 1.1-1.7 1.2-.4.1-1 .1-1.6-.1-.4-.1-.9-.3-1.5-.6-2.6-1.1-4.3-3.8-4.5-4-.1-.2-1-1.4-1-2.6 0-1.2.7-1.8.9-2 .2-.2.5-.3.7-.3h.5c.2 0 .4 0 .6.5l.8 2c.1.2.1.4 0 .6-.1.2-.2.3-.3.5l-.4.5c-.1.1-.2.3-.1.5.1.3.6 1.1 1.4 1.7 1 .9 1.8 1.2 2.1 1.3.2.1.4.1.5-.1l.6-.8c.2-.2.4-.2.6-.1l1.9.9c.2.1.4.2.4.3.1.2.1.6-.1 1.2z"/></svg>
  ),
  pin: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 10c0 7-8 12-8 12s-8-5-8-12a8 8 0 0 1 16 0z"/><circle cx="12" cy="10" r="3"/></svg>
  ),
  clock: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
  ),
  check: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 6 9 17l-5-5"/></svg>
  ),
  close: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M18 6 6 18M6 6l12 12"/></svg>
  ),
  shield: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
  ),
  spark: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/></svg>
  ),
  layers: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 2 2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></svg>
  ),
  plus: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 5v14M5 12h14"/></svg>
  ),
  globe: (p = {}) => (
    <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15 15 0 0 1 0 20M12 2a15 15 0 0 0 0 20"/></svg>
  )
};

/* ---------------- DISC logo (vector — generic green-mark + wordmark, original) ---------------- */
function Logo({ variant = "dark" }) {
  const fg = variant === "light" ? "#FFFFFF" : "var(--ink)";
  return (
    <a href="#/" className="logo" aria-label="DISC Dubai — home">
      <svg viewBox="0 0 64 40" width="56" height="36" aria-hidden="true">
        {/* orbital mark — original interpretation: two arcs forming an open ring */}
        <g transform="translate(20 20)">
          <path d="M -14 0 a 14 14 0 0 1 28 0" fill="none" stroke="var(--green)" strokeWidth="3.2" strokeLinecap="round"/>
          <path d="M 14 0 a 14 14 0 0 1 -28 0" fill="none" stroke="var(--ink)" strokeWidth="3.2" strokeLinecap="round" opacity={variant === "light" ? 0 : 1}/>
          <path d="M 14 0 a 14 14 0 0 1 -28 0" fill="none" stroke="#FFFFFF" strokeWidth="3.2" strokeLinecap="round" opacity={variant === "light" ? 1 : 0}/>
          <circle cx="0" cy="0" r="3.2" fill="var(--green)"/>
        </g>
      </svg>
      <span className="logo-word" style={{color: fg}}>
        <span className="logo-disc">DISC</span>
        <span className="logo-sub">Dubai</span>
      </span>
    </a>
  );
}

/* ---------------- routing helpers ---------------- */
function useHashRoute() {
  const [hash, setHash] = useState(window.location.hash || "#/");
  useEffect(() => {
    const onHash = () => setHash(window.location.hash || "#/");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const path = hash.replace(/^#/, "") || "/";
  const parts = path.split("/").filter(Boolean);
  return { path, parts, hash };
}

function navigate(to) {
  window.location.hash = to;
  window.scrollTo({ top: 0, behavior: "instant" });
}

/* ---------------- Header / Nav ---------------- */
function Header({ onBook }) {
  const { path } = useHashRoute();
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [megaOpen, setMegaOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => { setOpen(false); setMegaOpen(false); }, [path]);

  const navItems = [
    { label: "Services", to: "#/services", mega: true },
    { label: "Our team", to: "#/team" },
    { label: "Locations", to: "#/locations" },
    { label: "About", to: "#/about" },
    { label: "Contact", to: "#/contact" }
  ];

  return (
    <header className={"site-header " + (scrolled ? "is-scrolled" : "")}>
      <div className="topbar">
        <div className="wrap topbar-inner">
          <span><Icon.pin /> 3 Dubai locations — DHCC · JLT · Al Quoz</span>
          <div className="topbar-right">
            <a href="tel:+97143662334"><Icon.phone /> +971 4 366 2334</a>
            <span className="dot" />
            <a className="lang"><Icon.globe /> EN <Icon.arrowDown style={{fontSize:"0.7em"}}/></a>
          </div>
        </div>
      </div>
      <div className="wrap header-inner">
        <Logo />
        <nav className="primary-nav" onMouseLeave={() => setMegaOpen(false)}>
          {navItems.map(n => (
            <div key={n.to} className="nav-item"
              onMouseEnter={() => n.mega && setMegaOpen(true)}>
              <a href={n.to} className={path.startsWith(n.to.replace("#","")) ? "is-active" : ""}>
                {n.label}{n.mega && <Icon.arrowDown style={{fontSize:"0.65em", marginLeft:6}}/>}
              </a>
            </div>
          ))}
          {megaOpen && <Mega onClose={() => setMegaOpen(false)} />}
        </nav>
        <div className="header-cta">
          <a className="ghost-btn" href="https://wa.me/971521214295?text=Hi%20DISC%2C%20I%27d%20like%20to%20book%20a%20consultation" target="_blank" rel="noopener"><Icon.whatsapp /> WhatsApp</a>
          <button className="primary-btn" onClick={onBook}>Book an appointment <Icon.arrow /></button>
        </div>
        <button className="burger" aria-label="Menu" onClick={() => setOpen(!open)}>
          <span></span><span></span><span></span>
        </button>
      </div>
      {open && (
        <div className="mobile-nav">
          {navItems.map(n => <a key={n.to} href={n.to}>{n.label}</a>)}
          <button className="primary-btn" onClick={onBook}>Book an appointment</button>
        </div>
      )}
    </header>
  );
}

function Mega({ onClose }) {
  return (
    <div className="mega" onMouseLeave={onClose}>
      <div className="wrap mega-inner">
        <div className="mega-col">
          <h6>By service</h6>
          <div className="mega-services">
            {SERVICES.map(s => (
              <a key={s.slug} href={`#/services/${s.slug}`} className="mega-service">
                <span className="mega-service-title">{s.title}</span>
                <span className="mega-service-sub">{s.short}</span>
              </a>
            ))}
          </div>
        </div>
        <div className="mega-col mega-side">
          <h6>By concern</h6>
          <div className="concern-chips small">
            {CONCERNS.map(c => (
              <a key={c.label} className="chip" href={`#/services/${c.service}`}>{c.label}</a>
            ))}
          </div>
          <div className="mega-feature">
            <div className="mega-feature-img" style={{backgroundImage: "url(media/approach-2.webp)"}} />
            <div>
              <small>Differentiator</small>
              <h5>Dynexus AI gait analysis</h5>
              <p>Objective movement and gait data, in-house — used to drive rehab decisions.</p>
              <a className="text-link" href="#/services/dynexus-gait-analysis">Learn more <Icon.arrow /></a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Booking Modal ---------------- */
function BookingModal({ open, onClose, initialService }) {
  const [step, setStep] = useState(1);
  const [data, setData] = useState({
    location: "dhcc",
    service: initialService || "",
    name: "", email: "", phone: "",
    notes: "", preferred: ""
  });
  useEffect(() => {
    if (open) { setStep(1); setData(d => ({ ...d, service: initialService || "" })); document.body.style.overflow = "hidden"; }
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [open, initialService]);

  if (!open) return null;

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const next = () => setStep(s => s + 1);
  const back = () => setStep(s => s - 1);

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal book" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close"><Icon.close /></button>
        <div className="book-aside">
          <div className="book-aside-inner">
            <small>Book an appointment</small>
            <h3>A consultation, on your terms.</h3>
            <p>Tell us a little about what you need and we'll confirm a time at your chosen location. Most patients are seen within 48 hours.</p>
            <ul className="book-points">
              <li><Icon.check /> No referral required</li>
              <li><Icon.check /> Three locations across Dubai</li>
              <li><Icon.check /> Most insurers accepted — confirm at booking</li>
            </ul>
            <div className="book-help">
              <a href="https://wa.me/971521214295" target="_blank" rel="noopener"><Icon.whatsapp /> Prefer WhatsApp? +971 52 121 4295</a>
              <a href="tel:+97143662334"><Icon.phone /> Call +971 4 366 2334</a>
            </div>
          </div>
        </div>
        <div className="book-main">
          <div className="step-rail">
            {[1,2,3].map(n => (
              <div key={n} className={"step-dot " + (step >= n ? "is-on" : "")}>
                <span>{n}</span>
                <em>{n===1?"Where & what":n===2?"Your details":"Confirm"}</em>
              </div>
            ))}
          </div>

          {step === 1 && (
            <div className="step">
              <h4>Where would you like to be seen?</h4>
              <div className="loc-picker">
                {LOCATIONS.map(l => (
                  <button key={l.id} className={"loc-card " + (data.location === l.id ? "is-on" : "")} onClick={() => set("location", l.id)}>
                    <strong>{l.short}</strong>
                    <span>{l.name}</span>
                    {l.lead && <em className="tag-pill">Flagship</em>}
                  </button>
                ))}
              </div>
              <h4 style={{marginTop:32}}>What's the concern?</h4>
              <div className="select-row">
                <select value={data.service} onChange={e => set("service", e.target.value)}>
                  <option value="">Select a service…</option>
                  {SERVICES.map(s => <option key={s.slug} value={s.slug}>{s.title}</option>)}
                </select>
              </div>
              <div className="concern-chips" style={{marginTop:16}}>
                {CONCERNS.slice(0,6).map(c => (
                  <button key={c.label} className={"chip " + (data.service === c.service ? "is-on" : "")} onClick={() => set("service", c.service)}>{c.label}</button>
                ))}
              </div>
              <div className="step-foot">
                <span></span>
                <button className="primary-btn" disabled={!data.service} onClick={next}>Continue <Icon.arrow /></button>
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="step">
              <h4>How can we reach you?</h4>
              <div className="form-grid">
                <label><span>Full name</span><input value={data.name} onChange={e=>set("name", e.target.value)} placeholder="As it appears on your ID" /></label>
                <label><span>Mobile (incl. country code)</span><input value={data.phone} onChange={e=>set("phone", e.target.value)} placeholder="+971 …" /></label>
                <label className="full"><span>Email</span><input type="email" value={data.email} onChange={e=>set("email", e.target.value)} placeholder="you@example.com" /></label>
                <label className="full"><span>Preferred day / time</span><input value={data.preferred} onChange={e=>set("preferred", e.target.value)} placeholder="e.g. Mid-week mornings" /></label>
                <label className="full"><span>Anything we should know? <em>(optional)</em></span><textarea rows="3" value={data.notes} onChange={e=>set("notes", e.target.value)} placeholder="A sentence is plenty — please don't include sensitive medical detail here." /></label>
              </div>
              <p className="fine">Please keep this brief. Your clinical history will be taken in private at your visit.</p>
              <div className="step-foot">
                <button className="ghost-btn" onClick={back}>Back</button>
                <button className="primary-btn" disabled={!data.name || !data.phone} onClick={next}>Review <Icon.arrow /></button>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="step">
              <h4>You're all set.</h4>
              <p className="lede">Thank you, {data.name.split(" ")[0] || "there"}. A member of our front-of-house team will confirm your appointment shortly.</p>
              <div className="confirm-card">
                <div>
                  <small>Location</small>
                  <strong>{LOCATIONS.find(l=>l.id===data.location).name}</strong>
                </div>
                <div>
                  <small>Service</small>
                  <strong>{SERVICES.find(s=>s.slug===data.service)?.title}</strong>
                </div>
                <div>
                  <small>Preferred time</small>
                  <strong>{data.preferred || "Next available"}</strong>
                </div>
              </div>
              <div className="step-foot">
                <button className="ghost-btn" onClick={() => { setStep(1); }}>Book another</button>
                <button className="primary-btn" onClick={onClose}>Done</button>
              </div>
              <p className="fine" style={{marginTop:18}}>This is a design prototype — no information is sent or stored.</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------------- Footer ---------------- */
function Footer() {
  return (
    <footer className="site-footer">
      <div className="wrap footer-grid">
        <div className="footer-brand">
          <Logo variant="light" />
          <p>Diversified Integrated Sports Clinic — sports medicine, chiropractic, physiotherapy and longevity care in Dubai Healthcare City since 2014.</p>
          <div className="footer-contact">
            <a href="tel:+97143662334"><Icon.phone /> +971 4 366 2334</a>
            <a href="https://wa.me/971521214295" target="_blank" rel="noopener"><Icon.whatsapp /> +971 52 121 4295</a>
            <a href="mailto:contact@disc-me.com">contact@disc-me.com</a>
          </div>
        </div>
        <div>
          <h6>Services</h6>
          <ul>{SERVICES.map(s => <li key={s.slug}><a href={`#/services/${s.slug}`}>{s.title}</a></li>)}</ul>
        </div>
        <div>
          <h6>Clinic</h6>
          <ul>
            <li><a href="#/about">About / Our approach</a></li>
            <li><a href="#/team">Our practitioners</a></li>
            <li><a href="#/locations">Locations</a></li>
            <li><a href="#/before-after">Before &amp; after</a></li>
            <li><a href="#/contact">Book an appointment</a></li>
          </ul>
        </div>
        <div>
          <h6>Locations</h6>
          <ul>{LOCATIONS.map(l => <li key={l.id}><a href={`#/locations#${l.id}`}>{l.short} — {l.addressLines[0]}</a></li>)}</ul>
        </div>
      </div>
      <div className="wrap footer-foot">
        <div>© 2025 D.I.S.C FZ-LLC — Diversified Integrated Sports Clinic. Licensed by DHCC.</div>
        <div className="footer-socials">
          <a href="https://instagram.com/disc.uae" target="_blank" rel="noopener">Instagram</a>
          <a href="https://facebook.com/discdubai" target="_blank" rel="noopener">Facebook</a>
          <a href="https://www.linkedin.com/company/diversified-integrated-sports-clinic" target="_blank" rel="noopener">LinkedIn</a>
        </div>
      </div>
      <p className="compliance">
        All clinical care at DISC is delivered by registered practitioners. Treatment outcomes vary between
        individuals and no specific result is guaranteed. No patient imagery on this site is published
        without explicit consent and full DHA / DHCC advertising compliance.
      </p>
    </footer>
  );
}

/* ---------------- Floating WhatsApp ---------------- */
function WhatsAppFab() {
  return (
    <a className="wa-fab" href="https://wa.me/971521214295?text=Hi%20DISC%2C%20I%27d%20like%20to%20book%20a%20consultation" target="_blank" rel="noopener" aria-label="Chat on WhatsApp">
      <Icon.whatsapp />
    </a>
  );
}

window.DISC_UI = { Icon, Logo, Header, Footer, BookingModal, WhatsAppFab, useHashRoute, navigate };
