// Modern Vet — shared components

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

// ── ICONS ─────────────────────────────────────────────────────────
const Icon = ({ name, className = "" }) => {
  const common = { width: 24, height: 24, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round", className };
  switch (name) {
    case "phone": return <svg {...common}><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.72 12.84 12.84 0 0 0 .7 2.81 2 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-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>;
    case "whatsapp": return <svg {...common}><path d="M3 21l1.65-3.8a9 9 0 1 1 3.4 3.35z"/><path d="M9 10c.5 1.5 1.5 2.5 3 3"/></svg>;
    case "menu": return <svg {...common}><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>;
    case "close": return <svg {...common}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>;
    case "arrow-right": return <svg {...common}><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>;
    case "chevron-down": return <svg {...common}><polyline points="6 9 12 15 18 9"/></svg>;
    case "chevron-right": return <svg {...common}><polyline points="9 18 15 12 9 6"/></svg>;
    case "map-pin": return <svg {...common}><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>;
    case "clock": return <svg {...common}><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 14"/></svg>;
    case "emergency": return <svg {...common}><circle cx="12" cy="12" r="9"/><line x1="12" y1="8" x2="12" y2="13"/><circle cx="12" cy="16.5" r="0.6" fill="currentColor"/></svg>;
    case "consult": return <svg {...common}><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8z"/></svg>;
    case "syringe": return <svg {...common}><path d="m18 2 4 4"/><path d="m17 7 3-3"/><path d="M19 9 9 19l-3 1-1-1 1-3L16 6"/><path d="m8 14 4 4"/></svg>;
    case "surgery": return <svg {...common}><path d="M6 6a3 3 0 1 1 6 0v6"/><path d="M9 12v3a3 3 0 1 0 6 0v-3"/><line x1="12" y1="3" x2="12" y2="12"/></svg>;
    case "dentistry": return <svg {...common}><path d="M12 2C8 2 5 5 5 9c0 5 2 13 4 13 1 0 1-2 3-2s2 2 3 2c2 0 4-8 4-13 0-4-3-7-7-7z"/></svg>;
    case "heart": return <svg {...common}><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>;
    case "brain": return <svg {...common}><path d="M9 3a3 3 0 0 0-3 3v0a3 3 0 0 0-3 3 3 3 0 0 0 1.5 2.6A3 3 0 0 0 3 14a3 3 0 0 0 3 3 3 3 0 0 0 3 3 3 3 0 0 0 3-3V6a3 3 0 0 0-3-3z"/><path d="M15 3a3 3 0 0 1 3 3v0a3 3 0 0 1 3 3 3 3 0 0 1-1.5 2.6A3 3 0 0 1 21 14a3 3 0 0 1-3 3 3 3 0 0 1-3 3 3 3 0 0 1-3-3V6a3 3 0 0 1 3-3z"/></svg>;
    case "oncology": return <svg {...common}><circle cx="12" cy="12" r="9"/><circle cx="10" cy="10" r="2"/><circle cx="15" cy="14" r="1.5"/></svg>;
    case "eye": return <svg {...common}><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7z"/><circle cx="12" cy="12" r="3"/></svg>;
    case "ortho": return <svg {...common}><path d="m17 3 4 4-4 4"/><path d="m7 21-4-4 4-4"/><path d="M14 7H8a4 4 0 0 0-4 4v0"/><path d="M10 17h6a4 4 0 0 0 4-4v0"/></svg>;
    case "imaging": return <svg {...common}><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 4v16M17 4v16"/><circle cx="12" cy="12" r="3"/></svg>;
    case "physio": return <svg {...common}><circle cx="12" cy="5" r="2"/><path d="M12 7v6l-3 4M12 13l3 4"/><path d="M9 11h6"/></svg>;
    case "grooming": return <svg {...common}><path d="M3 21h18"/><path d="M8 21V8l-2 2M16 21V8l2 2"/><path d="M8 8c0-3 2-5 4-5s4 2 4 5"/></svg>;
    case "mobile": return <svg {...common}><rect x="1" y="6" width="15" height="11" rx="1"/><polygon points="16 9 21 9 23 12 23 17 16 17 16 9"/><circle cx="5.5" cy="18.5" r="1.5"/><circle cx="18.5" cy="18.5" r="1.5"/></svg>;
    case "chip": return <svg {...common}><rect x="5" y="5" width="14" height="14" rx="2"/><path d="M9 1v4M15 1v4M9 19v4M15 19v4M1 9h4M1 15h4M19 9h4M19 15h4"/></svg>;
    case "paw": return <svg {...common}><circle cx="6" cy="11" r="2"/><circle cx="18" cy="11" r="2"/><circle cx="9" cy="6" r="2"/><circle cx="15" cy="6" r="2"/><path d="M8 17a4 4 0 0 1 8 0c0 2-1.5 3-4 3s-4-1-4-3z"/></svg>;
    case "check": return <svg {...common}><polyline points="20 6 9 17 4 12"/></svg>;
    case "search": return <svg {...common}><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>;
    case "globe": return <svg {...common}><circle cx="12" cy="12" r="9"/><line x1="3" y1="12" x2="21" y2="12"/><path d="M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>;
    case "calendar": return <svg {...common}><rect x="3" y="5" width="18" height="16" rx="2"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="8" y1="3" x2="8" y2="7"/><line x1="16" y1="3" x2="16" y2="7"/></svg>;
    default: return null;
  }
};

// ── BRAND MARK ────────────────────────────────────────────────────
// The wedge / pet silhouette mark from the logo, simplified as a recurring graphic device
const Wedge = ({ className = "", color = "currentColor" }) => (
  <svg viewBox="0 0 60 60" className={className} fill="none" aria-hidden="true">
    <path d="M5 55 L5 8 C30 10 50 28 55 55 Z" fill={color}/>
    <ellipse cx="38" cy="38" rx="6" ry="9" fill="var(--paper)"/>
    <ellipse cx="48" cy="44" rx="3.5" ry="5" fill="var(--paper)"/>
  </svg>
);

// ── LOGO LOCKUP ───────────────────────────────────────────────────
const Logo = ({ onNavy = false, onClick }) => (
  <a href="#/" onClick={(e) => { e.preventDefault(); onClick && onClick(); }} className="logo">
    <Wedge className="logo-mark" color={onNavy ? "var(--peach)" : "var(--navy)"} />
    <div className="logo-text">
      <div className="logo-wordmark" style={{ color: onNavy ? "var(--paper)" : "var(--navy)" }}>MODERN VET</div>
      <div className="logo-tag" style={{ color: onNavy ? "var(--peach)" : "var(--muted)" }}>SINCE 1995 · DUBAI</div>
    </div>
  </a>
);

// ── NAV ───────────────────────────────────────────────────────────
const NAV_ITEMS = [
  { label: "Services", href: "#/services" },
  { label: "Vets & Team", href: "#/vets" },
  { label: "Branches", href: "#/branches" },
  { label: "Prices", href: "#/prices" },
  { label: "About", href: "#/about" },
];

const Nav = ({ onBook, currentHash, branch, onBranchChange }) => {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [branchOpen, setBranchOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const activeBranch = BRANCHES.find(b => b.slug === branch) || BRANCHES[0];

  return (
    <header className={"nav " + (scrolled ? "nav-scrolled" : "")}>
      <div className="nav-inner">
        <Logo onClick={() => (window.location.hash = "/")} />
        <nav className="nav-links" aria-label="Primary">
          {NAV_ITEMS.map(item => (
            <a key={item.href} href={item.href} className={"nav-link " + (currentHash.startsWith(item.href) ? "is-active" : "")}>{item.label}</a>
          ))}
        </nav>
        <div className="nav-cta">
          <div className="branch-picker" onMouseLeave={() => setBranchOpen(false)}>
            <button className="branch-trigger" onClick={() => setBranchOpen(!branchOpen)}>
              <Icon name="map-pin" />
              <span>{activeBranch.name.replace(" Hospital", "").replace(" Clinic", "")}</span>
              <Icon name="chevron-down" className="chev"/>
            </button>
            {branchOpen && (
              <div className="branch-menu">
                <div className="branch-menu-head">Choose your nearest branch</div>
                {BRANCHES.map(b => (
                  <button key={b.slug} className={"branch-opt " + (b.slug === branch ? "is-active" : "")} onClick={() => { onBranchChange(b.slug); setBranchOpen(false); }}>
                    <div>
                      <div className="branch-opt-name">{b.name}</div>
                      <div className="branch-opt-meta">{b.hoursShort}{b.is24 && <span className="dot-24"> · 24/7</span>}</div>
                    </div>
                    {b.slug === branch && <Icon name="check" />}
                  </button>
                ))}
              </div>
            )}
          </div>
          <button className="btn btn-primary" onClick={onBook}>Book Appointment</button>
          <button className="nav-burger" onClick={() => setOpen(!open)} aria-label="Menu">
            <Icon name={open ? "close" : "menu"} />
          </button>
        </div>
      </div>
      {open && (
        <div className="nav-mobile">
          {NAV_ITEMS.map(item => (
            <a key={item.href} href={item.href} onClick={() => setOpen(false)} className="nav-mobile-link">{item.label}</a>
          ))}
          <button className="btn btn-primary btn-block" onClick={() => { onBook(); setOpen(false); }}>Book Appointment</button>
        </div>
      )}
    </header>
  );
};

// ── EMERGENCY STRIP ───────────────────────────────────────────────
const EmergencyStrip = () => (
  <div className="emergency-strip" role="region" aria-label="24/7 Emergency">
    <div className="emergency-strip-inner">
      <span className="pulse-dot" aria-hidden="true"></span>
      <span className="emergency-label">24/7 Emergency Hospital · Al Wasl, Umm Suqeim</span>
      <span className="emergency-sep">·</span>
      <span className="emergency-cta-wrap">
        <a href="tel:80082" className="emergency-cta"><Icon name="phone" /> Call 800-VET</a>
        <a href="https://wa.me/971506304573?text=Emergency%20—%20my%20pet%20needs%20urgent%20help" className="emergency-cta emergency-wa" target="_blank" rel="noopener"><Icon name="whatsapp"/> WhatsApp</a>
      </span>
    </div>
  </div>
);

// ── FOOTER ────────────────────────────────────────────────────────
const Footer = () => (
  <footer className="footer">
    <div className="footer-inner">
      <div className="footer-col footer-brand">
        <Logo onNavy />
        <p className="footer-tag">Dubai's trusted pet hospital since 1995. 24/7 multi-specialty care across 6 branches plus a mobile clinic that comes to you.</p>
        <div className="footer-contact">
          <a href="tel:80082" className="footer-call"><Icon name="phone"/> 800-VET (800-82)</a>
          <a href="https://wa.me/971506304573" className="footer-wa" target="_blank" rel="noopener"><Icon name="whatsapp"/> +971 50 630 4573</a>
        </div>
      </div>
      <div className="footer-col">
        <div className="footer-head">Care</div>
        <a href="#/services/emergency">Emergency 24/7</a>
        <a href="#/services">All services</a>
        <a href="#/prices">Transparent pricing</a>
        <a href="#/services/mobile-clinic">Mobile clinic</a>
      </div>
      <div className="footer-col">
        <div className="footer-head">Branches</div>
        {BRANCHES.map(b => <a key={b.slug} href={`#/branches/${b.slug}`}>{b.name.replace(" Hospital", "").replace(" Clinic", "")}{b.is24 && " · 24/7"}</a>)}
      </div>
      <div className="footer-col">
        <div className="footer-head">About</div>
        <a href="#/about">Our story since 1995</a>
        <a href="#/vets">Vets &amp; team</a>
        <a href="#/contact">Contact</a>
        <a href="https://shop.modernvet.live" target="_blank" rel="noopener">Shop ↗</a>
      </div>
    </div>
    <div className="footer-bottom">
      <span>© 2026 Modern Vet LLC · Dubai, UAE</span>
      <span className="footer-legal">Licence numbers (MOCCAE · Dubai Municipality) — to be supplied</span>
      <div className="footer-lang">
        <button className="is-active">EN</button>
        <button>عربي</button>
        <button>RU</button>
        <button>中文</button>
      </div>
    </div>
  </footer>
);

// ── MOBILE BOTTOM BAR ─────────────────────────────────────────────
const MobileBar = ({ onBook }) => (
  <div className="mobile-bar">
    <a href="tel:80082" className="mobile-bar-btn mobile-bar-call"><Icon name="phone"/><span>Call 800-VET</span></a>
    <a href="https://wa.me/971506304573" target="_blank" rel="noopener" className="mobile-bar-btn mobile-bar-wa"><Icon name="whatsapp"/><span>WhatsApp</span></a>
    <button className="mobile-bar-btn mobile-bar-book" onClick={onBook}><Icon name="calendar"/><span>Book</span></button>
  </div>
);

// ── BOOKING MODAL (multi-step) ────────────────────────────────────
const BookModal = ({ open, onClose, branch, defaultService }) => {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    branch: branch || "al-wasl",
    service: defaultService || "pet-consultation",
    petType: "Dog",
    petName: "",
    petAge: "",
    date: "",
    time: "10:00",
    name: "",
    phone: "",
    email: "",
    notes: "",
  });
  useEffect(() => { if (open) { setStep(0); setData(d => ({ ...d, branch: branch || d.branch, service: defaultService || d.service })); } }, [open, branch, defaultService]);
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;
  const update = (k, v) => setData(d => ({ ...d, [k]: v }));
  const activeBranch = BRANCHES.find(b => b.slug === data.branch);
  const activeService = SERVICES.find(s => s.slug === data.service);

  const steps = ["Branch & service", "Your pet", "Date & contact", "Confirm"];

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

  // Date helpers — generate next 14 days
  const days = Array.from({ length: 14 }, (_, i) => {
    const d = new Date(); d.setDate(d.getDate() + i);
    return d;
  });
  const fmtDay = (d) => d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" });
  const TIMES = ["08:00", "09:00", "10:00", "11:00", "12:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00"];

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal book-modal" onClick={e => e.stopPropagation()} role="dialog" aria-label="Book appointment">
        <button className="modal-close" onClick={onClose} aria-label="Close"><Icon name="close"/></button>
        <div className="book-side">
          <div className="book-side-head">
            <Wedge className="book-side-mark" color="var(--peach)" />
            <div>
              <div className="eyebrow on-navy">Book an appointment</div>
              <h2 className="book-title">A vet you can call by name.</h2>
              <p className="book-side-sub">No phone tag. Pick a branch, a time and we'll confirm by WhatsApp within an hour.</p>
            </div>
          </div>
          <ol className="book-steps">
            {steps.map((s, i) => (
              <li key={s} className={i === step ? "is-active" : i < step ? "is-done" : ""}>
                <span className="book-step-num">{i < step ? "✓" : i + 1}</span>
                <span className="book-step-label">{s}</span>
              </li>
            ))}
          </ol>
          <div className="book-side-foot">
            <div className="eyebrow on-navy">Emergency?</div>
            <a href="tel:80082" className="book-side-emerg"><Icon name="phone" /> Call 800-VET — open now</a>
          </div>
        </div>

        <div className="book-main">
          {step === 0 && (
            <div className="book-step">
              <h3 className="book-h">Where would you like to be seen?</h3>
              <div className="book-branches">
                {BRANCHES.map(b => (
                  <button key={b.slug} className={"book-branch " + (data.branch === b.slug ? "is-active" : "")} onClick={() => update("branch", b.slug)}>
                    <div className="book-branch-top">
                      <span className="book-branch-name">{b.name.replace(" Hospital", "").replace(" Clinic", "")}</span>
                      {b.is24 && <span className="badge-24">24/7</span>}
                    </div>
                    <div className="book-branch-meta"><Icon name="clock" /> {b.hoursShort}</div>
                  </button>
                ))}
              </div>
              <h3 className="book-h" style={{ marginTop: 32 }}>What is this visit for?</h3>
              <div className="book-services">
                {SERVICES.filter(s => !s.isEmergency).slice(0, 9).map(s => (
                  <button key={s.slug} className={"book-service " + (data.service === s.slug ? "is-active" : "")} onClick={() => update("service", s.slug)}>
                    <Icon name={s.icon} />
                    <span>{s.name}</span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {step === 1 && (
            <div className="book-step">
              <h3 className="book-h">Tell us about your pet</h3>
              <div className="field-row">
                <label className="field-radio">
                  {["Dog", "Cat", "Bird", "Exotic"].map(t => (
                    <button key={t} className={"pet-pill " + (data.petType === t ? "is-active" : "")} onClick={() => update("petType", t)}>{t}</button>
                  ))}
                </label>
              </div>
              <div className="field-grid">
                <label className="field">
                  <span className="field-lab">Pet's name</span>
                  <input value={data.petName} onChange={e => update("petName", e.target.value)} placeholder="e.g. Luna" />
                </label>
                <label className="field">
                  <span className="field-lab">Age</span>
                  <input value={data.petAge} onChange={e => update("petAge", e.target.value)} placeholder="e.g. 3 years" />
                </label>
              </div>
              <label className="field">
                <span className="field-lab">Anything we should know? <span className="field-opt">(optional)</span></span>
                <textarea value={data.notes} onChange={e => update("notes", e.target.value)} rows={3} placeholder="Recent symptoms, allergies, anxious in clinics — anything helps." />
              </label>
            </div>
          )}

          {step === 2 && (
            <div className="book-step">
              <h3 className="book-h">When suits you?</h3>
              <div className="book-days">
                {days.map((d, i) => {
                  const key = d.toISOString().slice(0, 10);
                  return (
                    <button key={key} className={"book-day " + (data.date === key ? "is-active" : "")} onClick={() => update("date", key)}>
                      <span className="book-day-dow">{d.toLocaleDateString("en-US", { weekday: "short" })}</span>
                      <span className="book-day-num">{d.getDate()}</span>
                      <span className="book-day-mon">{d.toLocaleDateString("en-US", { month: "short" })}</span>
                    </button>
                  );
                })}
              </div>
              <div className="book-times">
                {TIMES.map(t => (
                  <button key={t} className={"book-time " + (data.time === t ? "is-active" : "")} onClick={() => update("time", t)}>{t}</button>
                ))}
              </div>
              <h3 className="book-h" style={{ marginTop: 32 }}>How can we reach you?</h3>
              <div className="field-grid">
                <label className="field"><span className="field-lab">Your name</span><input value={data.name} onChange={e => update("name", e.target.value)} placeholder="Full name" /></label>
                <label className="field"><span className="field-lab">Phone</span><input value={data.phone} onChange={e => update("phone", e.target.value)} placeholder="+971 …" /></label>
                <label className="field" style={{ gridColumn: "1 / -1" }}><span className="field-lab">Email</span><input value={data.email} onChange={e => update("email", e.target.value)} placeholder="you@email.com" /></label>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="book-step book-confirm">
              <h3 className="book-h">All set — please confirm</h3>
              <dl className="book-summary">
                <div><dt>Branch</dt><dd>{activeBranch?.name}</dd></div>
                <div><dt>Service</dt><dd>{activeService?.name}</dd></div>
                <div><dt>Pet</dt><dd>{data.petName || "—"} · {data.petType}{data.petAge ? ` · ${data.petAge}` : ""}</dd></div>
                <div><dt>When</dt><dd>{data.date || "—"} at {data.time}</dd></div>
                <div><dt>You</dt><dd>{data.name || "—"} · {data.phone || "—"}</dd></div>
              </dl>
              <p className="book-confirm-note">We'll send a confirmation on WhatsApp within an hour. If your pet needs care sooner, please call <a href="tel:80082">800-VET</a>.</p>
              <div className="book-success-spot">
                <span className="pulse-dot"></span> A vet will see {data.petName || "your pet"} at {activeBranch?.name.replace(" Hospital", "").replace(" Clinic", "")}.
              </div>
            </div>
          )}
        </div>

        <div className="book-foot">
          <div className="book-foot-step">Step {step + 1} of {steps.length}</div>
          <div className="book-foot-actions">
            {step > 0 && <button className="btn btn-ghost" onClick={prev}>← Back</button>}
            {step < steps.length - 1 && <button className="btn btn-primary" onClick={next}>Continue <Icon name="arrow-right" /></button>}
            {step === steps.length - 1 && <button className="btn btn-primary" onClick={onClose}>Request appointment</button>}
          </div>
        </div>
      </div>
    </div>
  );
};

// ── PHOTO SLOT (placeholder for tasteful image use) ───────────────
const Photo = ({ src, alt, ratio = "4 / 3", className = "", focal = "center" }) => (
  <div className={"photo " + className} style={{ aspectRatio: ratio }}>
    <img src={src} alt={alt} loading="lazy" style={{ objectPosition: focal }} />
  </div>
);

// ── SECTION HEADER ────────────────────────────────────────────────
const SectionHead = ({ eyebrow, title, sub, align = "left", onNavy = false }) => (
  <header className={"section-head section-head-" + align + (onNavy ? " on-navy" : "")}>
    {eyebrow && <div className={"eyebrow" + (onNavy ? " on-navy" : "")}>{eyebrow}</div>}
    <h2 className="section-title">{title}</h2>
    {sub && <p className="section-sub">{sub}</p>}
  </header>
);

Object.assign(window, { Icon, Wedge, Logo, Nav, EmergencyStrip, Footer, MobileBar, BookModal, Photo, SectionHead });
