/* House of Windsor — UI primitives & chrome */
const { useState, useEffect, useRef } = React;

/* ─── Wordmark ──────────────────────────────────────────────── */
function Wordmark({ variant = 'stacked', color }) {
  const style = color ? { color } : undefined;
  if (variant === 'compact') {
    return (
      <span className="wordmark compact" style={style}>
        <span className="line-1">HOUSE OF WINDSOR</span>
        <span className="line-3">JEWELLERS</span>
      </span>
    );
  }
  return (
    <div className="wordmark" style={style}>
      <span className="line-1">HOUSE OF</span>
      <span className="line-2">WINDSOR</span>
      <span className="line-3">JEWELLERS</span>
    </div>
  );
}

/* ─── Diamond glyph used as ornament ────────────────────────── */
function DiamondGlyph({ size = 14, color = 'currentColor' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none" aria-hidden>
      <path d="M7 0.5L13.5 5L7 13.5L0.5 5L7 0.5Z" stroke={color} strokeWidth="0.8" />
      <path d="M0.5 5H13.5M7 0.5L4 5L7 13.5L10 5L7 0.5Z" stroke={color} strokeWidth="0.5" opacity="0.55" />
    </svg>
  );
}

/* ─── Stars row ─────────────────────────────────────────────── */
function Stars({ n = 5, size = 14 }) {
  return (
    <span className="stars" aria-label={`${n} of 5`}>
      {Array.from({ length: 5 }).map((_, i) => (
        <svg key={i} width={size} height={size} viewBox="0 0 16 16" fill={i < n ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1">
          <path d="M8 1.5l1.9 4.1 4.5.5-3.4 3.1.9 4.5L8 11.5 4.1 13.7l.9-4.5L1.6 6.1l4.5-.5L8 1.5z" />
        </svg>
      ))}
    </span>
  );
}

/* ─── Tripadvisor 5.0 chip ─────────────────────────────────── */
function TripadvisorChip({ tone = 'light' }) {
  const dark = tone === 'dark';
  return (
    <a
      href={HOWJ.contact.social.tripadvisor}
      target="_blank" rel="noreferrer"
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 12,
        padding: '8px 16px',
        border: `1px solid ${dark ? 'rgba(247,244,239,0.25)' : 'var(--line)'}`,
        background: dark ? 'rgba(247,244,239,0.04)' : 'rgba(255,255,255,0.6)',
        color: dark ? 'var(--ivory)' : 'var(--charcoal)',
        borderRadius: 999,
        fontSize: 12, letterSpacing: '0.08em',
      }}
    >
      <Stars n={5} size={12} />
      <span><strong style={{ fontWeight: 600 }}>{HOWJ.rating.score.toFixed(1)}</strong>
        <span style={{ opacity: 0.7 }}> · {HOWJ.rating.count} reviews on Tripadvisor</span>
      </span>
    </a>
  );
}

/* ─── Nav ──────────────────────────────────────────────────── */
function Nav({ route, setRoute, onBook, scrolled }) {
  const [mobileOpen, setMobileOpen] = useState(false);
  return (
    <header
      style={{
        position: 'sticky', top: 0, zIndex: 50,
        background: scrolled ? 'rgba(247,244,239,0.96)' : 'transparent',
        backdropFilter: scrolled ? 'saturate(140%) blur(14px)' : 'none',
        WebkitBackdropFilter: scrolled ? 'saturate(140%) blur(14px)' : 'none',
        borderBottom: scrolled ? '1px solid var(--line)' : '1px solid transparent',
        transition: 'all 240ms ease',
      }}
    >
      <div className="container" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 24,
        padding: scrolled ? '14px 32px' : '22px 32px',
        transition: 'padding 240ms ease',
      }}>
        <button
          onClick={() => setRoute('home')}
          style={{ background: 'none', border: 0, padding: 0, color: scrolled ? 'var(--charcoal)' : 'var(--charcoal)' }}
          aria-label="House of Windsor — Home"
        >
          <Wordmark variant="compact" />
        </button>

        <nav className="desktop-nav" style={{ display: 'flex', gap: 28 }}>
          {HOWJ.navItems.filter(n => n.id !== 'home').map(n => (
            <button
              key={n.id}
              onClick={() => setRoute(n.id)}
              style={{
                background: 'none', border: 0, padding: '8px 0',
                fontFamily: 'var(--font-label)',
                fontSize: 12, letterSpacing: '0.22em',
                textTransform: 'uppercase',
                color: route === n.id ? 'var(--gold-deep)' : 'var(--charcoal)',
                borderBottom: route === n.id ? '1px solid var(--champagne-gold)' : '1px solid transparent',
                transition: 'all 180ms',
              }}
            >{n.label}</button>
          ))}
        </nav>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <button
            className="btn btn-gold btn-sm desktop-only"
            onClick={onBook}
          >Book Consultation</button>
          <button
            className="mobile-only"
            onClick={() => setMobileOpen(true)}
            aria-label="Open menu"
            style={{ background: 'none', border: 0, padding: 8 }}
          >
            <svg width="22" height="14" viewBox="0 0 22 14"><path d="M0 1h22M0 7h22M0 13h22" stroke="currentColor" strokeWidth="1.2" /></svg>
          </button>
        </div>
      </div>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div
          style={{
            position: 'fixed', inset: 0, zIndex: 100,
            background: 'var(--midnight)',
            color: 'var(--ivory)',
            display: 'flex', flexDirection: 'column',
            padding: 28,
          }}
        >
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Wordmark variant="compact" color="var(--ivory)" />
            <button onClick={() => setMobileOpen(false)} style={{ background: 'none', border: 0, color: 'inherit', padding: 8 }}>
              <svg width="18" height="18" viewBox="0 0 18 18"><path d="M1 1l16 16M17 1L1 17" stroke="currentColor" strokeWidth="1.2" /></svg>
            </button>
          </div>
          <nav style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 48 }}>
            {HOWJ.navItems.map(n => (
              <button
                key={n.id}
                onClick={() => { setRoute(n.id); setMobileOpen(false); }}
                style={{
                  background: 'none', border: 0, color: 'inherit',
                  textAlign: 'left', padding: '18px 0',
                  fontFamily: 'var(--font-serif)', fontSize: 32,
                  borderBottom: '1px solid var(--line-dark)',
                }}
              >{n.label}</button>
            ))}
          </nav>
          <div style={{ marginTop: 'auto', paddingTop: 24 }}>
            <button className="btn btn-gold" style={{ width: '100%' }} onClick={() => { setMobileOpen(false); onBook(); }}>
              Book a Private Consultation
            </button>
          </div>
        </div>
      )}

      <style>{`
        @media (max-width: 1180px) {
          .desktop-nav, .desktop-only { display: none !important; }
        }
        @media (min-width: 1181px) {
          .mobile-only { display: none !important; }
        }
      `}</style>
    </header>
  );
}

/* ─── WhatsApp FAB ──────────────────────────────────────────── */
function WhatsAppFab() {
  const href = `https://wa.me/${HOWJ.contact.whatsapp}?text=${encodeURIComponent("Hi House of Windsor, I'd like to book a consultation.")}`;
  return (
    <a
      href={href}
      target="_blank" rel="noreferrer"
      aria-label="WhatsApp House of Windsor"
      style={{
        position: 'fixed', bottom: 24, right: 24, zIndex: 40,
        width: 56, height: 56, borderRadius: '50%',
        background: '#25D366',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 8px 24px rgba(37,211,102,0.4), 0 2px 6px rgba(0,0,0,0.15)',
        transition: 'transform 200ms',
      }}
      onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.06)'}
      onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
    >
      <svg width="28" height="28" viewBox="0 0 24 24" fill="#fff">
        <path d="M17.5 14.4c-.3-.1-1.8-.9-2-1-.3-.1-.5-.1-.7.1-.2.3-.8 1-1 1.2-.2.2-.3.2-.6.1-.3-.1-1.3-.5-2.5-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.4.1-.6.1-.1.3-.3.4-.5.1-.1.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.7-1.7-1-2.3-.3-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.4 0 1.4 1 2.8 1.2 3 .1.2 2 3 4.8 4.2.7.3 1.2.5 1.6.6.7.2 1.3.2 1.8.1.6-.1 1.8-.7 2-1.5.2-.7.2-1.4.2-1.5-.1-.1-.3-.2-.6-.3M12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.6 1.4 5.1L2 22l4.9-1.3C8.5 21.5 10.2 22 12 22c5.5 0 10-4.5 10-10S17.5 2 12 2z"/>
      </svg>
    </a>
  );
}

/* ─── Mobile bottom CTA bar ─────────────────────────────────── */
function MobileBookBar({ onBook }) {
  return (
    <div className="mobile-only" style={{
      position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 35,
      background: 'rgba(247,244,239,0.97)',
      backdropFilter: 'blur(10px)',
      borderTop: '1px solid var(--line)',
      padding: '12px 16px',
      display: 'flex', gap: 8,
    }}>
      <a href={`tel:${HOWJ.contact.phoneLandlineTel}`} className="btn btn-ghost" style={{ flex: 1 }}>Call</a>
      <button className="btn btn-gold" style={{ flex: 2 }} onClick={onBook}>Book Consultation</button>
    </div>
  );
}

/* ─── Consultation modal ───────────────────────────────────── */
function ConsultationModal({ open, onClose, defaultCollection }) {
  const [step, setStep] = useState(0);
  const [form, setForm] = useState({
    name: '', email: '', mobile: '',
    collection: defaultCollection || 'Engagement Rings',
    when: 'In the next two weeks',
    visit: 'In-showroom',
    message: '',
  });
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  useEffect(() => {
    if (open) {
      setStep(0);
      if (defaultCollection) update('collection', defaultCollection);
    }
  }, [open, defaultCollection]);

  if (!open) return null;
  const totalSteps = 3;
  return (
    <div
      role="dialog" aria-modal="true"
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(14,22,38,0.6)',
        backdropFilter: 'blur(8px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          background: 'var(--ivory)',
          maxWidth: 880, width: '100%',
          maxHeight: '92vh', overflow: 'auto',
          display: 'grid', gridTemplateColumns: 'minmax(0, 280px) 1fr',
          boxShadow: '0 40px 100px rgba(14,22,38,0.5)',
        }}
        className="modal-grid"
      >
        {/* Sidebar */}
        <aside style={{
          background: 'var(--royal-blue)',
          color: 'var(--ivory)',
          padding: '40px 32px',
          display: 'flex', flexDirection: 'column',
          minHeight: 480,
        }}>
          <div style={{ marginBottom: 32 }}>
            <Wordmark variant="compact" color="var(--ivory)" />
          </div>
          <div style={{ marginBottom: 'auto' }}>
            <div className="eyebrow" style={{ color: 'var(--champagne-gold)', marginBottom: 12 }}>Private Consultation</div>
            <h2 className="display-md" style={{ margin: 0, color: 'var(--ivory)', fontFamily: 'var(--font-serif)' }}>
              Tell us a little about the piece you have in mind.
            </h2>
            <p style={{ marginTop: 16, fontSize: 14, opacity: 0.8, lineHeight: 1.6 }}>
              Mehul or Vicky will reply personally within one business day, in English, by email or WhatsApp.
            </p>
          </div>
          <div style={{ borderTop: '1px solid var(--line-dark)', paddingTop: 20, marginTop: 32, fontSize: 12, letterSpacing: '0.08em', opacity: 0.75 }}>
            <div style={{ marginBottom: 6 }}>+971 4 340 8324</div>
            <div>mehul@houseofwindsorjewellers.com</div>
          </div>
        </aside>

        {/* Form */}
        <div style={{ padding: '40px 36px', position: 'relative' }}>
          <button
            onClick={onClose}
            aria-label="Close"
            style={{ position: 'absolute', top: 16, right: 16, background: 'none', border: 0, padding: 10 }}
          >
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="1.2" /></svg>
          </button>

          {/* progress */}
          <div style={{ display: 'flex', gap: 8, marginBottom: 28 }}>
            {Array.from({ length: totalSteps }).map((_, i) => (
              <div key={i} style={{ flex: 1, height: 2, background: i <= step ? 'var(--champagne-gold)' : 'var(--line)' }} />
            ))}
          </div>

          {step < totalSteps && (
            <div className="eyebrow" style={{ marginBottom: 6 }}>Step {step + 1} of {totalSteps}</div>
          )}

          {step === 0 && (
            <>
              <h3 className="display-sm" style={{ marginTop: 4 }}>What are you looking to commission?</h3>
              <div style={{ display: 'grid', gap: 14, marginTop: 24 }}>
                <div className="field">
                  <label>Collection of interest</label>
                  <select value={form.collection} onChange={e => update('collection', e.target.value)}>
                    {HOWJ.collections.map(c => (
                      <option key={c.id} value={c.name}>{c.name}</option>
                    ))}
                    <option value="Bespoke / Tailor-Made">Bespoke / Tailor-Made</option>
                    <option value="Not sure yet">Not sure yet — please advise</option>
                  </select>
                </div>
                <div className="field">
                  <label>How soon?</label>
                  <select value={form.when} onChange={e => update('when', e.target.value)}>
                    <option>This week</option>
                    <option>In the next two weeks</option>
                    <option>In the next month</option>
                    <option>Exploring — no timeline yet</option>
                  </select>
                </div>
                <div className="field">
                  <label>How would you like to meet?</label>
                  <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                    {['In-showroom', 'WhatsApp video', 'Phone call'].map(o => (
                      <button
                        key={o}
                        onClick={() => update('visit', o)}
                        style={{
                          padding: '10px 16px',
                          border: `1px solid ${form.visit === o ? 'var(--champagne-gold)' : 'var(--line)'}`,
                          background: form.visit === o ? 'rgba(201,168,106,0.1)' : '#fff',
                          color: 'var(--charcoal)',
                          fontFamily: 'var(--font-label)', fontSize: 12, letterSpacing: '0.18em',
                          textTransform: 'uppercase',
                        }}
                      >{o}</button>
                    ))}
                  </div>
                </div>
              </div>
            </>
          )}

          {step === 1 && (
            <>
              <h3 className="display-sm" style={{ marginTop: 4 }}>How can we reach you?</h3>
              <div style={{ display: 'grid', gap: 14, marginTop: 24 }}>
                <div className="field">
                  <label>Your name</label>
                  <input value={form.name} onChange={e => update('name', e.target.value)} placeholder="Full name" />
                </div>
                <div className="field">
                  <label>Email</label>
                  <input type="email" value={form.email} onChange={e => update('email', e.target.value)} placeholder="you@example.com" />
                </div>
                <div className="field">
                  <label>Mobile (with country code)</label>
                  <input value={form.mobile} onChange={e => update('mobile', e.target.value)} placeholder="+44 …" />
                </div>
                <div className="field">
                  <label>Anything we should know?</label>
                  <textarea
                    rows="3"
                    value={form.message}
                    onChange={e => update('message', e.target.value)}
                    placeholder="Inspiration, finger size, stone preference, budget band — anything that helps."
                  ></textarea>
                </div>
              </div>
            </>
          )}

          {step === 2 && (
            <>
              <h3 className="display-sm" style={{ marginTop: 4 }}>One last look.</h3>
              <div style={{ display: 'grid', gap: 16, marginTop: 24, padding: 24, background: 'var(--cream-card)', border: '1px solid var(--line)' }}>
                {[
                  ['Collection', form.collection],
                  ['Meeting by', form.visit],
                  ['Timeframe', form.when],
                  ['Name', form.name || '—'],
                  ['Email', form.email || '—'],
                  ['Mobile', form.mobile || '—'],
                  ['Note', form.message || '—'],
                ].map(([k, v]) => (
                  <div key={k} style={{ display: 'flex', borderBottom: '1px dashed var(--line)', paddingBottom: 12, gap: 16 }}>
                    <div className="eyebrow" style={{ flex: '0 0 110px', color: 'var(--charcoal)' }}>{k}</div>
                    <div style={{ fontSize: 14, color: 'var(--charcoal)' }}>{v}</div>
                  </div>
                ))}
              </div>
              <p style={{ fontSize: 13, marginTop: 20, opacity: 0.75, lineHeight: 1.6 }}>
                By sending this you agree to be contacted by House of Windsor Jewellers about your enquiry. We do not share your details.
              </p>
            </>
          )}

          {step === 3 && (
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <div style={{ color: 'var(--champagne-gold)', display: 'flex', justifyContent: 'center', marginBottom: 20 }}>
                <DiamondGlyph size={36} />
              </div>
              <h3 className="display-md" style={{ marginTop: 0, marginBottom: 16 }}>
                Thank you{form.name ? `, ${form.name.split(' ')[0]}` : ''}.
              </h3>
              <p className="body-lg" style={{ maxWidth: 380, margin: '0 auto', opacity: 0.85 }}>
                We'll be in touch within one business day. In the meantime, feel free to message us directly on WhatsApp.
              </p>
              <div style={{ marginTop: 28, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
                <button className="btn btn-ghost" onClick={onClose}>Close</button>
                <a className="btn btn-gold" href={`https://wa.me/${HOWJ.contact.whatsapp}`} target="_blank" rel="noreferrer">
                  Open WhatsApp
                </a>
              </div>
            </div>
          )}

          {step < totalSteps && (
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 32, alignItems: 'center' }}>
              <button
                className="btn btn-ghost"
                disabled={step === 0}
                style={{ visibility: step === 0 ? 'hidden' : 'visible' }}
                onClick={() => setStep(s => s - 1)}
              >Back</button>
              <button
                className="btn btn-gold"
                onClick={() => setStep(s => s + 1)}
                disabled={step === 1 && (!form.name || !form.email)}
              >
                {step === totalSteps - 1 ? 'Send Request' : 'Continue'}
              </button>
            </div>
          )}
        </div>
      </div>

      <style>{`
        @media (max-width: 720px) {
          .modal-grid { grid-template-columns: 1fr !important; }
          .modal-grid aside { min-height: auto !important; padding: 24px !important; }
        }
      `}</style>
    </div>
  );
}

/* ─── Footer ───────────────────────────────────────────────── */
function Footer({ setRoute, onBook }) {
  return (
    <footer style={{ background: 'var(--midnight)', color: 'var(--ivory)', paddingTop: 72, paddingBottom: 40 }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 48, paddingBottom: 56 }}>
          <div>
            <Wordmark color="var(--ivory)" />
            <p style={{ marginTop: 28, opacity: 0.7, fontSize: 14, lineHeight: 1.7 }}>
              Independent Dubai diamond house. Bespoke design, certified stones, owner-led from the bench up.
            </p>
            <div style={{ marginTop: 20 }}>
              <TripadvisorChip tone="dark" />
            </div>
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Visit</div>
            <div style={{ fontSize: 14, opacity: 0.8, lineHeight: 1.8 }}>
              {HOWJ.contact.addressLines.map((l, i) => <div key={i}>{l}</div>)}
            </div>
            <div style={{ marginTop: 16, fontSize: 14, opacity: 0.85 }}>
              {HOWJ.contact.hours.map(h => (
                <div key={h.day} style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid var(--line-dark)', padding: '6px 0' }}>
                  <span>{h.day}</span><span>{h.time}</span>
                </div>
              ))}
            </div>
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Reach Mehul</div>
            <div style={{ fontSize: 14, opacity: 0.85, lineHeight: 2 }}>
              <div><a href={`tel:${HOWJ.contact.phoneLandlineTel}`} style={{ borderBottom: '1px solid var(--line-dark)' }}>{HOWJ.contact.phoneLandline}</a></div>
              <div><a href={`https://wa.me/${HOWJ.contact.whatsapp}`} style={{ borderBottom: '1px solid var(--line-dark)' }}>WhatsApp · {HOWJ.contact.phoneMobile}</a></div>
              <div><a href={`mailto:${HOWJ.contact.email}`} style={{ borderBottom: '1px solid var(--line-dark)' }}>{HOWJ.contact.email}</a></div>
            </div>
            <div style={{ marginTop: 20, display: 'flex', gap: 10 }}>
              <button className="btn btn-gold btn-sm" onClick={onBook}>Book Consultation</button>
            </div>
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Browse</div>
            <div style={{ display: 'grid', gap: 10, fontSize: 14, opacity: 0.85 }}>
              {HOWJ.navItems.filter(n => n.id !== 'home').map(n => (
                <button
                  key={n.id} onClick={() => setRoute(n.id)}
                  style={{ background: 'none', border: 0, color: 'inherit', padding: 0, textAlign: 'left', fontSize: 14 }}
                >{n.label}</button>
              ))}
            </div>
            <div className="eyebrow" style={{ marginTop: 24, marginBottom: 12 }}>Follow</div>
            <div style={{ display: 'flex', gap: 14, fontSize: 13, opacity: 0.85 }}>
              <a href={`https://instagram.com/${HOWJ.contact.social.instagram}`} target="_blank" rel="noreferrer">Instagram</a>
              <a href={`https://facebook.com/${HOWJ.contact.social.facebook}`} target="_blank" rel="noreferrer">Facebook</a>
              <a href={HOWJ.contact.social.tripadvisor} target="_blank" rel="noreferrer">Tripadvisor</a>
            </div>
          </div>
        </div>

        <div style={{ borderTop: '1px solid var(--line-dark)', paddingTop: 24, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16, fontSize: 12, opacity: 0.55 }}>
          <div>© {new Date().getFullYear()} House of Windsor Jewellers FZCO</div>
          <div style={{ display: 'flex', gap: 18 }}>
            <span>GIA · IGI · HRD · IDL Certified</span>
            <span>Gold &amp; Diamond Park, Dubai</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ─── Page transition wrapper ──────────────────────────────── */
function PageFade({ k, children }) {
  return <div key={k} className="reveal">{children}</div>;
}

Object.assign(window, {
  Wordmark, DiamondGlyph, Stars, TripadvisorChip,
  Nav, WhatsAppFab, MobileBookBar, ConsultationModal, Footer, PageFade,
});
