// Shared UI components for VIP Beauty Lounge prototype.
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ── Logo (uses the verified red+white SVG file) ─────────────────────────────
function Logo({ height = 28, mode = 'red' }) {
  return (
    <span className="vip-logo" style={{ display: 'inline-flex', alignItems: 'center', gap: 0 }}>
      <img
        src="assets/logo-red-white.svg"
        alt="VIP Beauty Lounge"
        style={{
          height,
          display: 'block',
          filter: mode === 'all-white' ? 'brightness(0) invert(1)' : 'none',
        }}
      />
    </span>
  );
}

// ── Star rating glyph ───────────────────────────────────────────────────────
function Stars({ n = 5, size = 14 }) {
  return (
    <span className="stars" style={{ display: 'inline-flex', gap: 2 }}>
      {Array.from({ length: 5 }).map((_, i) => (
        <svg key={i} width={size} height={size} viewBox="0 0 20 20" fill={i < n ? 'var(--vip-red)' : 'rgba(0,0,0,0.15)'} aria-hidden="true">
          <path d="M10 1.6l2.6 5.27 5.82.85-4.21 4.1.99 5.8L10 14.88l-5.2 2.74.99-5.8L1.58 7.72l5.82-.85L10 1.6z"/>
        </svg>
      ))}
    </span>
  );
}

// ── Trust strip (5.0 · 421 · Al Manara) ─────────────────────────────────────
function TrustStrip({ tone = 'light' }) {
  const dark = tone === 'dark';
  return (
    <div className={`trust-strip ${dark ? 'trust-strip--dark' : ''}`}>
      <div className="trust-item">
        <div className="trust-num">5.0<span>★</span></div>
        <div className="trust-meta">Fresha rating<br/><span>from 421 guests</span></div>
      </div>
      <div className="trust-rule" />
      <div className="trust-item">
        <div className="trust-num">421</div>
        <div className="trust-meta">five-star reviews<br/><span>6 this week</span></div>
      </div>
      <div className="trust-rule" />
      <div className="trust-item">
        <div className="trust-num">VIP</div>
        <div className="trust-meta">Royal Room<br/><span>private by request</span></div>
      </div>
      <div className="trust-rule" />
      <div className="trust-item">
        <div className="trust-num"><span className="dot" />Open</div>
        <div className="trust-meta">Villa 148, Al Manara<br/><span>Daily 10:00 — 22:00</span></div>
      </div>
    </div>
  );
}

// ── Service row used inside Services and home grids ─────────────────────────
function ServiceRow({ name, price, duration, signature, onBook }) {
  return (
    <div className={`svc-row ${signature ? 'svc-row--sig' : ''}`}>
      <div className="svc-row__name">
        {signature && <span className="svc-row__chip">Signature</span>}
        <span className="svc-row__title">{name}</span>
        {duration && <span className="svc-row__dur">{duration}</span>}
      </div>
      <div className="svc-row__dots" aria-hidden="true" />
      <div className="svc-row__price">
        <span className="svc-row__currency">AED</span>
        <span className="svc-row__num">{price}</span>
      </div>
      <button className="svc-row__book" onClick={onBook}>Book</button>
    </div>
  );
}

// ── Section header with eyebrow + display + lede ────────────────────────────
function SectionHeader({ eyebrow, title, lede, align = 'left' }) {
  return (
    <header className={`sect-head sect-head--${align}`}>
      {eyebrow && <div className="eyebrow">{eyebrow}</div>}
      <h2 className="display">{title}</h2>
      {lede && <p className="lede">{lede}</p>}
    </header>
  );
}

// ── Header / nav ────────────────────────────────────────────────────────────
function Header({ route, navigate, dark = false }) {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const nav = [
    ['home',      'Home'],
    ['services',  'Services'],
    ['vip',       'VIP Room'],
    ['gallery',   'Gallery'],
    ['about',     'About'],
    ['reviews',   'Reviews'],
    ['contact',   'Visit'],
  ];
  return (
    <header className={`site-header ${scrolled ? 'is-scrolled' : ''} ${dark ? 'site-header--dark' : ''}`}>
      <div className="site-header__inner">
        <a className="site-header__logo" onClick={(e) => { e.preventDefault(); navigate('home'); }} href="#home">
          <Logo height={32} mode={dark && !scrolled ? 'all-white' : 'red'} />
        </a>
        <nav className="site-header__nav" aria-label="Primary">
          {nav.map(([id, label]) => (
            <a
              key={id}
              href={`#${id}`}
              className={`nav-link ${route === id ? 'is-active' : ''}`}
              onClick={(e) => { e.preventDefault(); navigate(id); }}
            >
              {label}
            </a>
          ))}
        </nav>
        <div className="site-header__cta">
          <a className="ghost-cta" href={window.LINKS.phoneMob}>+971 555 080 506</a>
          <button className="btn btn--primary" onClick={() => navigate('book')}>Book Now</button>
        </div>
        <button className="site-header__menu" onClick={() => setOpen(v => !v)} aria-label="Open menu">
          <svg width="22" height="22" viewBox="0 0 22 22"><path d="M3 6h16M3 11h16M3 16h16" stroke="currentColor" strokeWidth="1.6" fill="none"/></svg>
        </button>
      </div>
      {open && (
        <div className="site-header__drawer">
          {nav.map(([id, label]) => (
            <a key={id} href={`#${id}`} onClick={(e) => { e.preventDefault(); setOpen(false); navigate(id); }}>{label}</a>
          ))}
          <button className="btn btn--primary" onClick={() => { setOpen(false); navigate('book'); }}>Book Now</button>
        </div>
      )}
    </header>
  );
}

// ── Mobile bottom action bar ────────────────────────────────────────────────
function MobileBar({ navigate }) {
  return (
    <div className="mobile-bar">
      <a className="mobile-bar__btn" href={window.LINKS.phoneMob}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2z"/></svg>
        Call
      </a>
      <a className="mobile-bar__btn" href={window.LINKS.whatsapp}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 21l1.7-5A8 8 0 1 1 8 19l-5 2zM8 9.5c.4 1.6 1.4 2.6 3 3"/></svg>
        WhatsApp
      </a>
      <button className="mobile-bar__btn mobile-bar__btn--primary" onClick={() => navigate('book')}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M7 4v3M17 4v3M4 9h16M5 7h14a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1z"/></svg>
        Book Now
      </button>
    </div>
  );
}

// ── Footer ──────────────────────────────────────────────────────────────────
function Footer({ navigate }) {
  return (
    <footer className="site-footer">
      <div className="site-footer__pattern" aria-hidden="true" />
      <div className="site-footer__inner">
        <div className="ft-col ft-col--brand">
          <Logo height={36} mode="all-white" />
          <p className="ft-blurb">Grooming & Beauty, Al Manara. A boutique villa lounge on Al Manara Street, by appointment.</p>
          <div className="ft-rating">
            <Stars n={5} size={16}/> <strong>5.0</strong>&nbsp;<span>· 421 reviews on Fresha</span>
          </div>
        </div>
        <div className="ft-col">
          <h4>Visit</h4>
          <p>Villa 148, Al Manara Street<br/>Al Manara, Jumeirah, Dubai</p>
          <p><a href={window.LINKS.map} target="_blank" rel="noopener">View on Google Maps →</a></p>
        </div>
        <div className="ft-col">
          <h4>Reach us</h4>
          <p><a href={window.LINKS.phoneMob}>+971 555 080 506</a><br/>
             <a href={window.LINKS.phoneLand}>+971 4 297 1990</a></p>
          <p><a href={window.LINKS.email}>vipbeauty461@gmail.com</a></p>
          <p><a href={window.LINKS.whatsapp} target="_blank" rel="noopener">WhatsApp →</a></p>
        </div>
        <div className="ft-col">
          <h4>Hours</h4>
          <ul className="ft-hours">
            {window.HOURS.map(({ d, h }) => (
              <li key={d}><span>{d}</span><span>{h}</span></li>
            ))}
          </ul>
        </div>
        <div className="ft-col">
          <h4>Browse</h4>
          <ul className="ft-links">
            <li><a href="#services" onClick={(e)=>{e.preventDefault();navigate('services');}}>Services & prices</a></li>
            <li><a href="#vip"      onClick={(e)=>{e.preventDefault();navigate('vip');}}>VIP &amp; Royal Room</a></li>
            <li><a href="#gallery"  onClick={(e)=>{e.preventDefault();navigate('gallery');}}>Gallery</a></li>
            <li><a href="#about"    onClick={(e)=>{e.preventDefault();navigate('about');}}>About &amp; team</a></li>
            <li><a href="#reviews"  onClick={(e)=>{e.preventDefault();navigate('reviews');}}>Reviews</a></li>
            <li><a href={window.LINKS.vouchers} target="_blank" rel="noopener">Gift vouchers ↗</a></li>
          </ul>
        </div>
      </div>
      <div className="site-footer__rule" />
      <div className="site-footer__bottom">
        <span>© 2026 VIP Beauty Lounge · Villa 148, Al Manara Street, Dubai</span>
        <span>Booking by Fresha · Prices in AED · Re-verified 21 May 2026</span>
      </div>
    </footer>
  );
}

// ── Quick book sheet (used from "Book" buttons) ────────────────────────────
function BookSheet({ open, onClose, preselect }) {
  const [step, setStep] = useState(0);
  const [pick, setPick] = useState(preselect || null);
  const [date, setDate] = useState('Sat 24 May');
  const [time, setTime] = useState('17:30');
  const [room, setRoom] = useState('Main floor');
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  useEffect(() => { if (open) { setStep(0); setPick(preselect || null); } }, [open, preselect]);
  if (!open) return null;
  const allSvc = window.SERVICES.flatMap(c => c.items.map(it => ({ ...it, cat: c.title })));
  const popular = ['Hair Cut','Beard Signature','Signature Manicure','Signature Pedicure','Hydra Facial + Diamond Peel','Keratin / Brazilian Blowout'];
  const slots = ['10:00','10:30','11:00','12:30','14:00','15:30','17:30','18:00','19:30','20:30'];
  const dates = ['Fri 23 May','Sat 24 May','Sun 25 May','Mon 26 May','Tue 27 May','Wed 28 May'];

  return (
    <div className="sheet-backdrop" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="sheet__head">
          <div className="sheet__title">
            <Logo height={22}/> <span>Book an appointment</span>
          </div>
          <button className="sheet__close" onClick={onClose} aria-label="Close">×</button>
        </div>
        <div className="sheet__steps">
          {['Service','Time','Room','Confirm'].map((label, i) => (
            <div key={label} className={`sheet__step ${step === i ? 'is-active' : ''} ${step > i ? 'is-done' : ''}`}>
              <span className="sheet__step-num">{i + 1}</span> {label}
            </div>
          ))}
        </div>

        {step === 0 && (
          <div className="sheet__body">
            <h3 className="sheet__h">What would you like booked?</h3>
            <div className="sheet__quickrow">
              {popular.map(p => {
                const svc = allSvc.find(s => s.name === p);
                if (!svc) return null;
                return (
                  <button key={p} className={`sheet__chip ${pick?.name===p?'is-on':''}`} onClick={() => setPick(svc)}>
                    {p}<span>AED {svc.price}</span>
                  </button>
                );
              })}
            </div>
            <details className="sheet__more">
              <summary>Browse the full menu</summary>
              <div className="sheet__svclist">
                {window.SERVICES.map(cat => (
                  <div key={cat.id}>
                    <div className="sheet__cat">{cat.title}</div>
                    <ul>
                      {cat.items.map(it => (
                        <li key={it.name}>
                          <button className={`sheet__svc ${pick?.name===it.name?'is-on':''}`} onClick={() => setPick({ ...it, cat: cat.title })}>
                            <span>{it.name}</span><span>AED {it.price}</span>
                          </button>
                        </li>
                      ))}
                    </ul>
                  </div>
                ))}
              </div>
            </details>
          </div>
        )}

        {step === 1 && (
          <div className="sheet__body">
            <h3 className="sheet__h">Pick a date and time</h3>
            <div className="sheet__dates">
              {dates.map(d => (
                <button key={d} className={`sheet__date ${date===d?'is-on':''}`} onClick={() => setDate(d)}>{d}</button>
              ))}
            </div>
            <div className="sheet__slotgrid">
              {slots.map(s => (
                <button key={s} className={`sheet__slot ${time===s?'is-on':''}`} onClick={() => setTime(s)}>{s}</button>
              ))}
            </div>
            <p className="sheet__note">Times shown are illustrative. Final availability is reconciled with Fresha at confirmation.</p>
          </div>
        )}

        {step === 2 && (
          <div className="sheet__body">
            <h3 className="sheet__h">Where would you like to be seated?</h3>
            <div className="sheet__rooms">
              {[
                { id: 'Main floor',   sub: 'Standard service · included',         add: 0 },
                { id: 'Private Room', sub: 'Private suite · one stylist',         add: 150 },
                { id: 'Royal Room',   sub: 'Royal Room — full suite, full team',  add: 200 },
              ].map(r => (
                <button key={r.id} className={`sheet__room ${room===r.id?'is-on':''}`} onClick={() => setRoom(r.id)}>
                  <div>
                    <div className="sheet__room-name">{r.id}</div>
                    <div className="sheet__room-sub">{r.sub}</div>
                  </div>
                  <div className="sheet__room-add">{r.add ? `+ AED ${r.add}` : 'Included'}</div>
                </button>
              ))}
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="sheet__body">
            <h3 className="sheet__h">Confirm your reservation</h3>
            <div className="sheet__confirm">
              <div className="sheet__line"><span>Service</span><span>{pick?.name || '—'}</span></div>
              <div className="sheet__line"><span>Date</span><span>{date} · {time}</span></div>
              <div className="sheet__line"><span>Seating</span><span>{room}</span></div>
              <div className="sheet__line sheet__line--total">
                <span>Estimated total</span>
                <span>AED {(pick?.price || 0) + (room === 'Private Room' ? 150 : room === 'Royal Room' ? 200 : 0)}</span>
              </div>
            </div>
            <div className="sheet__fields">
              <label>Your name<input type="text" value={name} onChange={(e)=>setName(e.target.value)} placeholder="Full name"/></label>
              <label>Mobile<input type="tel" value={phone} onChange={(e)=>setPhone(e.target.value)} placeholder="+971…"/></label>
            </div>
            <p className="sheet__note">A team member will confirm by WhatsApp within a few minutes during opening hours. No payment is taken here.</p>
          </div>
        )}

        <div className="sheet__foot">
          {step > 0 && <button className="btn btn--ghost" onClick={() => setStep(s => s - 1)}>Back</button>}
          <div className="sheet__spacer"/>
          {step < 3 && (
            <button className="btn btn--primary" disabled={step === 0 && !pick} onClick={() => setStep(s => s + 1)}>
              Continue
            </button>
          )}
          {step === 3 && (
            <button className="btn btn--primary" onClick={() => { alert('Booking request sent.\n\n(Prototype — would post to Fresha or salon CRM.)'); onClose(); }}>
              Request booking
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Logo, Stars, TrustStrip, ServiceRow, SectionHeader, Header, MobileBar, Footer, BookSheet });
