/* Shared components: Nav, Footer, FAB, BottomBar, BookingModal, Lightbox */
const { useState, useEffect, useRef, useMemo } = React;

const D = window.BLO_DATA;
const IMG = (p) => `media/images/${p}`;

// --- Stars row ---
const Stars = ({ n = 5 }) => (
  <span className="stars-row" aria-label={`${n} stars`}>
    {"★★★★★".slice(0, n)}{"☆☆☆☆☆".slice(0, 5 - n)}
  </span>
);

// --- Nav ---
function Navbar({ route, setRoute, openBooking }) {
  const [open, setOpen] = useState(false);
  const links = [
    { id: "home", label: "Home" },
    { id: "services", label: "Services" },
    { id: "memberships", label: "Offers" },
    { id: "gallery", label: "Gallery" },
    { id: "team", label: "Team" },
    { id: "reviews", label: "Reviews" },
    { id: "book", label: "Visit" },
  ];
  const go = (r) => { setRoute(r); setOpen(false); window.scrollTo({ top: 0, behavior: "smooth" }); };
  return (
    <>
      <header className="navbar">
        <div className="container nav-inner">
          <div className="brand" onClick={() => go("home")}>
            <span>Blo<span className="dot"></span></span>
            <small>Beauty Lounge</small>
          </div>
          <nav className="nav-links">
            {links.map(l => (
              <button key={l.id}
                className={"nav-link " + (route === l.id ? "active" : "")}
                onClick={() => go(l.id)}>{l.label}</button>
            ))}
          </nav>
          <div className="nav-actions">
            <a href={D.brand.whatsappHref} target="_blank" rel="noopener" className="btn btn-sm btn-outline" title="WhatsApp" style={{display: "none"}}>WhatsApp</a>
            <button className="btn btn-sm btn-primary" onClick={openBooking}>Book Now</button>
            <button className="menu-toggle" onClick={() => setOpen(true)} aria-label="Open menu"><span></span></button>
          </div>
        </div>
      </header>

      <div className={"mobile-sheet " + (open ? "open" : "")}>
        <div style={{display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24}}>
          <div className="brand"><span>Blo<span className="dot"></span></span><small>Beauty Lounge</small></div>
          <button className="modal-close" onClick={() => setOpen(false)}>×</button>
        </div>
        {links.map(l => (
          <button key={l.id} onClick={() => go(l.id)}>{l.label}</button>
        ))}
        <div style={{display: "flex", gap: 12, marginTop: 24}}>
          <button className="btn btn-primary" onClick={() => { openBooking(); setOpen(false); }}>Book Now</button>
          <a href={D.brand.whatsappHref} className="btn btn-wa" target="_blank" rel="noopener">WhatsApp</a>
        </div>
      </div>
    </>
  );
}

// --- WhatsApp FAB ---
function WhatsAppFab() {
  return (
    <a href={D.brand.whatsappHref} target="_blank" rel="noopener" className="fab" aria-label="WhatsApp">
      <svg width="26" height="26" viewBox="0 0 24 24" fill="currentColor">
        <path d="M17.5 14.4c-.3-.1-1.7-.8-1.9-.9-.3-.1-.4-.1-.6.1-.2.3-.7.9-.8 1-.2.2-.3.2-.6.1-.3-.1-1.2-.5-2.3-1.4-.8-.7-1.4-1.6-1.6-1.9-.2-.3 0-.4.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.5-.9-2.1-.2-.5-.4-.5-.6-.5h-.5c-.2 0-.5.1-.7.3-.3.3-1 1-1 2.4 0 1.4 1 2.8 1.2 3 .1.2 2.1 3.2 5.1 4.4.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.7-.7 2-1.4.2-.7.2-1.3.2-1.4-.1-.1-.3-.2-.6-.3z"/>
        <path d="M20.5 3.5C18.2 1.2 15.2 0 12 0 5.4 0 0 5.4 0 12c0 2.1.6 4.2 1.6 6L0 24l6.2-1.6c1.7.9 3.7 1.4 5.7 1.4 6.6 0 12-5.4 12-12 0-3.2-1.2-6.2-3.4-8.3zM12 21.8c-1.8 0-3.6-.5-5.1-1.4l-.4-.2-3.7 1 1-3.6-.2-.4c-1-1.6-1.5-3.4-1.5-5.2C2.1 6.5 6.5 2.1 12 2.1c2.6 0 5.1 1 7 2.9 1.9 1.9 2.9 4.4 2.9 7 0 5.4-4.4 9.8-9.9 9.8z"/>
      </svg>
    </a>
  );
}

// --- Mobile bottom action bar ---
function BottomBar({ openBooking }) {
  return (
    <div className="bottom-bar">
      <a href={D.brand.phoneHref} className="btn btn-outline btn-sm" style={{borderColor: "rgba(255,253,251,0.3)", color: "var(--ivory)"}}>Call</a>
      <a href={D.brand.whatsappHref} target="_blank" rel="noopener" className="btn btn-wa btn-sm">WhatsApp</a>
      <button className="btn btn-rose btn-sm" onClick={openBooking}>Book Now</button>
    </div>
  );
}

// --- Footer ---
function Footer({ setRoute, openBooking }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="brand" style={{marginBottom: 14}}>
              <span>Blo<span className="dot"></span></span><small>Beauty Lounge</small>
            </div>
            <p style={{color: "var(--plum-soft)", fontSize: 14, maxWidth: 320, margin: "0 0 18px"}}>
              Jumeirah's blow-dry & beauty bar. {D.brand.address}.
            </p>
            <div style={{display: "flex", gap: 8}}>
              <a href={D.brand.instagram} target="_blank" rel="noopener" className="btn btn-sm btn-outline">Instagram</a>
              <a href={D.brand.facebook} target="_blank" rel="noopener" className="btn btn-sm btn-outline">Facebook</a>
            </div>
          </div>
          <div>
            <h5>Visit</h5>
            <ul>
              <li><a href={D.brand.phoneHref}>{D.brand.phone}</a></li>
              <li><a href={D.brand.whatsappHref} target="_blank" rel="noopener">WhatsApp</a></li>
              <li>{D.brand.hours}</li>
              <li>{D.brand.addressShort}</li>
              <li style={{fontSize: 11, color: "var(--plum-soft)", fontStyle: "italic"}}>"The Light House"</li>
            </ul>
          </div>
          <div>
            <h5>Services</h5>
            <ul>
              {D.categories.map(c => (
                <li key={c.id}><button onClick={() => { setRoute("services"); setTimeout(() => { const e = document.getElementById(`svc-${c.id}`); if (e) e.scrollIntoView({block: "start", behavior: "smooth"}); }, 100); }}>{c.title}</button></li>
              ))}
            </ul>
          </div>
          <div>
            <h5>Salon</h5>
            <ul>
              <li><button onClick={() => setRoute("team")}>The Team</button></li>
              <li><button onClick={() => setRoute("reviews")}>Reviews</button></li>
              <li><button onClick={() => setRoute("memberships")}>Offers</button></li>
              <li><button onClick={openBooking}>Book Now</button></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© Blo Out Beauty Lounge L.L.C. {new Date().getFullYear()}.</span>
          <span style={{fontStyle: "italic", opacity: 0.7}}>Prototype — prices marked "verified" only where corroborated by research.</span>
        </div>
      </div>
    </footer>
  );
}

// --- Booking modal (Fresha-style flow simulation) ---
function BookingModal({ open, onClose, preselect }) {
  const [step, setStep] = useState(0);
  const [service, setService] = useState(null);
  const [staff, setStaff] = useState(null);
  const [date, setDate] = useState(0);
  const [time, setTime] = useState(null);

  useEffect(() => {
    if (open) {
      setStep(0); setService(preselect || null); setStaff(null); setDate(0); setTime(null);
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open, preselect]);

  if (!open) return null;

  const services = [
    { id: "blowdry",  name: "Blowdry & Style",   meta: "45 min · from AED — (Fresha)" },
    { id: "moroccan", name: "Moroccan Bath",     meta: "45 min · AED 110.25 (H/H)" },
    { id: "lash-lift", name: "Lash Lifting",     meta: "60 min · AED 162.75 (H/H)" },
    { id: "lash-ext", name: "Lash Extensions",   meta: "2 hr · AED 159 (promo)" },
    { id: "nails-fs", name: "Nails — Full Set",  meta: "2 hr · AED 149 (promo)" },
    { id: "combo",    name: "Classic Combo",     meta: "2 hr · AED 156.50 (H/H)" },
    { id: "colour",   name: "Hair Colour",       meta: "2–3 hr · Price on Fresha" },
    { id: "facial",   name: "Facial",            meta: "60 min · Price on Fresha" },
  ];

  const staffOptions = [
    { id: "any",     name: "Any available", meta: "We'll match you" },
    ...D.team.slice(0, 6).map(t => ({ id: t.name.toLowerCase(), name: t.name, meta: `${t.role} · ${t.rating}★` })),
  ];

  const dates = useMemo(() => {
    const arr = [];
    const today = new Date("2026-05-22");
    const dow = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
    for (let i = 0; i < 10; i++) {
      const d = new Date(today.getFullYear(), today.getMonth(), today.getDate() + i);
      arr.push({ dow: dow[d.getDay()], day: d.getDate(), full: d });
    }
    return arr;
  }, []);

  const times = ["10:00","10:30","11:00","11:30","12:00","12:30","13:00","13:30","14:00","14:30","15:00","15:30","16:00","16:30","17:00","17:30","18:00","18:30","19:00","19:30"];
  // pseudo-busy slots vary by date
  const busy = useMemo(() => {
    const seed = (date * 7) % 19;
    return new Set([(seed) % 20, (seed + 5) % 20, (seed + 11) % 20, (seed + 14) % 20].map(i => times[i]));
  }, [date]);

  const canNext = [service, staff, time, true][step];
  const stepTitles = ["Choose a service", "Choose a specialist", "Pick a time", "Confirm booking"];

  const next = () => setStep(s => Math.min(s + 1, 3));
  const back = () => setStep(s => Math.max(s - 1, 0));
  const confirm = () => setStep(4); // success

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h3>{step < 4 ? stepTitles[step] : "Booking received"}</h3>
            {step < 4 && (
              <div className="step-dots">
                {[0,1,2,3].map(i => <i key={i} className={i <= step ? "on" : ""}/>)}
              </div>
            )}
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        </div>

        <div className="modal-body">
          {step === 0 && (
            <div className="choice-list">
              {services.map(s => (
                <button key={s.id} className={"choice " + (service?.id === s.id ? "active" : "")} onClick={() => setService(s)}>
                  <span className="l">{s.name}</span>
                  <span className="r">{s.meta}</span>
                </button>
              ))}
            </div>
          )}

          {step === 1 && (
            <div className="choice-list">
              {staffOptions.map(s => (
                <button key={s.id} className={"choice " + (staff?.id === s.id ? "active" : "")} onClick={() => setStaff(s)}>
                  <span className="l">{s.name}</span>
                  <span className="r">{s.meta}</span>
                </button>
              ))}
            </div>
          )}

          {step === 2 && (
            <>
              <div className="date-strip">
                {dates.map((d, i) => (
                  <button key={i} className={"date-pill " + (date === i ? "active" : "")} onClick={() => { setDate(i); setTime(null); }}>
                    <div className="dow">{d.dow}</div>
                    <div className="day">{d.day}</div>
                  </button>
                ))}
              </div>
              <div className="time-grid">
                {times.map(t => (
                  <button key={t} className={"time-pill " + (time === t ? "active" : "") + (busy.has(t) ? " busy" : "")} onClick={() => setTime(t)}>
                    {t}
                  </button>
                ))}
              </div>
              <p style={{fontSize: 12, color: "var(--plum-soft)", marginTop: 16, fontStyle: "italic"}}>
                Salon hours daily 09:00 – 21:00. Times in GST.
              </p>
            </>
          )}

          {step === 3 && service && staff && time && (
            <>
              <div className="summary-row"><span className="lbl">Service</span><span className="val">{service.name}<br/><small style={{fontSize: 12, color: "var(--plum-soft)", fontFamily: "var(--font-body)"}}>{service.meta}</small></span></div>
              <div className="summary-row"><span className="lbl">Specialist</span><span className="val">{staff.name}</span></div>
              <div className="summary-row"><span className="lbl">When</span><span className="val">{dates[date].dow} {dates[date].day} May · {time}</span></div>
              <div className="summary-row"><span className="lbl">Where</span><span className="val">Villa 710<br/><small style={{fontSize: 12, color: "var(--plum-soft)", fontFamily: "var(--font-body)"}}>Jumeirah Beach Rd, Umm Suqeim 2</small></span></div>
              <p style={{fontSize: 12, color: "var(--plum-soft)", marginTop: 18, fontStyle: "italic"}}>
                MVP wires this confirmation to Fresha's deep-link; Phase 2 captures payment & pre-auth natively.
              </p>
            </>
          )}

          {step === 4 && (
            <div className="success">
              <div className="check">✓</div>
              <h3>See you soon.</h3>
              <p>We've held your slot. A confirmation will land on WhatsApp.</p>
              <div style={{margin: "24px 0", padding: "18px", background: "var(--blush)", borderRadius: 12, textAlign: "left"}}>
                <div style={{fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--plum-soft)"}}>Booking ref</div>
                <div style={{fontFamily: "var(--font-display)", fontSize: 24, color: "var(--plum)", marginTop: 4}}>BLO–{(Math.random()*9000+1000)|0}</div>
              </div>
            </div>
          )}
        </div>

        <div className="modal-foot">
          {step > 0 && step < 4 && <button className="btn btn-ghost" onClick={back}>← Back</button>}
          {step === 0 && <span style={{fontSize: 12, color: "var(--plum-soft)"}}>Step 1 of 4</span>}
          {step === 4
            ? <button className="btn btn-primary" onClick={onClose} style={{marginLeft: "auto"}}>Done</button>
            : (step < 3
                ? <button className="btn btn-primary" disabled={!canNext} onClick={next} style={{marginLeft: "auto", opacity: canNext ? 1 : 0.4}}>Continue →</button>
                : <button className="btn btn-rose" onClick={confirm} style={{marginLeft: "auto"}}>Confirm booking</button>)
          }
        </div>
      </div>
    </div>
  );
}

// --- Lightbox ---
function Lightbox({ images, index, onClose, setIndex }) {
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowRight") setIndex((i) => (i + 1) % images.length);
      if (e.key === "ArrowLeft") setIndex((i) => (i - 1 + images.length) % images.length);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [images.length, onClose, setIndex]);
  if (index === null) return null;
  return (
    <div className="lightbox" onClick={onClose}>
      <button className="lb-close" onClick={onClose}>×</button>
      <button className="lb-nav lb-prev" onClick={(e) => { e.stopPropagation(); setIndex((i) => (i - 1 + images.length) % images.length); }}>‹</button>
      <button className="lb-nav lb-next" onClick={(e) => { e.stopPropagation(); setIndex((i) => (i + 1) % images.length); }}>›</button>
      <img src={IMG(images[index])} alt="" onClick={e => e.stopPropagation()} />
    </div>
  );
}

// expose
Object.assign(window, { Navbar, Footer, WhatsAppFab, BottomBar, BookingModal, Lightbox, Stars, IMG, D });
