/* chrome.jsx — Navbar, Footer, ConsultationDrawer, ConsultBar, WhatsAppFab */

const Navbar = ({route, setRoute, onOpenConsult, locale, setLocale}) => {
  const [megaOpen, setMegaOpen] = React.useState(null); // 'collections' | 'bespoke' | null
  const closeAll = () => setMegaOpen(null);
  return (
    <nav className="nav" onMouseLeave={closeAll}>
      <div className="shell nav__inner">
        <div className="nav__links">
          <button className="nav__link" data-active={route === 'home' || megaOpen === 'collections'}
                  onMouseEnter={() => setMegaOpen('collections')}
                  onClick={() => { setRoute('home'); closeAll(); }}>
            Collections
          </button>
          <button className="nav__link"
                  onMouseEnter={closeAll}
                  onClick={() => { setRoute('product'); }}>
            Signature
          </button>
          <button className="nav__link" data-active={route === 'bespoke'}
                  onMouseEnter={closeAll}
                  onClick={() => { setRoute('bespoke'); closeAll(); }}>
            Bespoke
          </button>
          <button className="nav__link"
                  onMouseEnter={closeAll}
                  onClick={() => { setRoute('home'); setTimeout(() => { document.getElementById('heritage')?.scrollIntoView({block: 'start'}); }, 50); }}>
            Heritage
          </button>
          <button className="nav__link"
                  onMouseEnter={closeAll}
                  onClick={() => { setRoute('home'); setTimeout(() => { document.getElementById('visit')?.scrollIntoView({block: 'start'}); }, 50); }}>
            Visit
          </button>
        </div>

        <PalacesMark size={24} />

        <div className="nav__right">
          <button className="nav__icon-btn" aria-label="Language"
                  onClick={() => setLocale(locale === 'en' ? 'ar' : 'en')}
                  title="Toggle EN / AR">
            <span style={{display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', fontWeight: 500}}>
              <Icon.Globe size={13} />
              {locale === 'en' ? 'EN · العربية' : 'العربية · EN'}
            </span>
          </button>
          <button className="nav__icon-btn" aria-label="Search"><Icon.Search /></button>
          <button className="nav__icon-btn" aria-label="Account"><Icon.User /></button>
          <button className="nav__icon-btn" aria-label="Bag"><Icon.Bag /></button>
          <button className="btn btn-primary" style={{padding: '12px 20px', fontSize: 11}} onClick={onOpenConsult}>
            Book a Private Consultation
          </button>
        </div>
      </div>

      {megaOpen === 'collections' && (
        <div className="megamenu" onMouseLeave={closeAll}>
          <div className="shell" style={{display: 'grid', gridTemplateColumns: 'repeat(4, 1fr) 1.2fr', gap: 56}}>
            <MegaColumn title="By Story"
              items={['Bridal & Engagement', 'Diamond Jewellery', 'Coloured Gemstones', 'Signature — Eagle of Noor']}
              onPick={(i) => { setRoute('home'); closeAll(); setTimeout(() => document.getElementById('collections')?.scrollIntoView({block: 'start'}), 50); }} />
            <MegaColumn title="By Piece"
              items={['Rings', 'Earrings', 'Necklaces & Pendants', 'Bracelets & Bangles']}
              onPick={() => { setRoute('home'); closeAll(); }} />
            <MegaColumn title="By Stone"
              items={['Diamond', 'Sapphire', 'Emerald', 'Ruby', 'Pink Sapphire']} />
            <MegaColumn title="By Metal"
              items={['18k Yellow Gold', '18k White Gold', '18k Rose Gold', 'Platinum 950']} />
            <div>
              <span className="eyebrow">From the Atelier</span>
              <div style={{marginTop: 14, position: 'relative', aspectRatio: '4/5', background: 'var(--champagne)', overflow: 'hidden'}}>
                <img src="assets/p-aureveris.webp" alt="Aureveris ring" style={{width: '100%', height: '100%', objectFit: 'cover'}} />
              </div>
              <div style={{marginTop: 16}}>
                <h4 className="display" style={{margin: 0, fontSize: 24}}>The Aureveris</h4>
                <p style={{margin: '6px 0 14px', fontSize: 13, color: 'var(--ink-60)'}}>A constellation of multi-coloured sapphires set in 18k rose gold.</p>
                <button className="btn-link" onClick={() => { setRoute('product'); closeAll(); }}>Discover the piece →</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </nav>
  );
};

const MegaColumn = ({title, items, onPick}) => (
  <div>
    <span className="eyebrow">{title}</span>
    <ul style={{listStyle: 'none', margin: '16px 0 0', padding: 0, display: 'flex', flexDirection: 'column', gap: 10}}>
      {items.map((i) => (
        <li key={i}>
          <button onClick={() => onPick && onPick(i)} style={{
            background: 'transparent', border: 0, padding: 0,
            color: 'var(--charcoal)', fontSize: 14, fontFamily: 'inherit',
            cursor: 'pointer', textAlign: 'left',
          }}>{i}</button>
        </li>
      ))}
    </ul>
  </div>
);

// ===========================================================
// Consultation Drawer (multi-step)
// ===========================================================
const ConsultationDrawer = ({open, onClose, prefill}) => {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    occasion: prefill?.occasion || '',
    piece: prefill?.piece || '',
    budget: '',
    metal: '',
    showroom: 'gate-3',
    name: '', email: '', phone: '', date: '', message: '',
  });
  React.useEffect(() => { if (open) { setStep(0); } }, [open]);

  if (!open) return null;

  const set = (k, v) => setData((d) => ({...d, [k]: v}));

  const occasions = ['Engagement', 'Wedding Band', 'Anniversary', 'Gift', 'A piece for myself', 'Bespoke commission'];
  const budgets = ['AED 9k–20k', 'AED 20k–50k', 'AED 50k–100k', 'AED 100k+', 'Open'];
  const metals = ['Yellow Gold', 'White Gold', 'Rose Gold', 'Platinum', 'Mixed / Advise me'];

  const steps = [
    { title: 'The occasion', body: (
      <div>
        <p style={{color: 'var(--ink-60)', marginTop: 0}}>So we know whom to seat you with.</p>
        <div className="chip-row">
          {occasions.map((o) => (
            <button key={o} className="chip" data-selected={data.occasion === o} onClick={() => set('occasion', o)}>{o}</button>
          ))}
        </div>
        {prefill?.piece && (
          <div style={{marginTop: 24, padding: 16, background: 'var(--champagne)', display: 'flex', gap: 16, alignItems: 'center'}}>
            <div style={{width: 56, height: 56, background: '#FFF', display: 'grid', placeItems: 'center', overflow: 'hidden'}}>
              <img src={byId(prefill.piece)?.img} alt="" style={{width: '100%', height: '100%', objectFit: 'cover'}} />
            </div>
            <div>
              <div className="eyebrow">Piece in mind</div>
              <div style={{fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 20, marginTop: 2}}>{byId(prefill.piece)?.name}</div>
            </div>
          </div>
        )}
      </div>
    )},
    { title: 'Budget & metal', body: (
      <div>
        <div className="field">
          <label className="field-label">Comfortable budget</label>
          <div className="chip-row">
            {budgets.map((b) => (
              <button key={b} className="chip" data-selected={data.budget === b} onClick={() => set('budget', b)}>{b}</button>
            ))}
          </div>
        </div>
        <div className="field">
          <label className="field-label">Preferred metal</label>
          <div className="chip-row">
            {metals.map((m) => (
              <button key={m} className="chip" data-selected={data.metal === m} onClick={() => set('metal', m)}>{m}</button>
            ))}
          </div>
        </div>
      </div>
    )},
    { title: 'Where & when', body: (
      <div>
        <div className="field">
          <label className="field-label">Showroom</label>
          <div className="chip-row">
            {[
              {id: 'gate-3', name: 'Gate 3 · Dalmook Bldg'},
              {id: 'gate-1', name: 'Gate 1 · Al Ghurair Bldg'},
              {id: 'virtual', name: 'Virtual call'},
            ].map((s) => (
              <button key={s.id} className="chip" data-selected={data.showroom === s.id} onClick={() => set('showroom', s.id)}>{s.name}</button>
            ))}
          </div>
        </div>
        <div className="field">
          <label className="field-label">Preferred date & time</label>
          <input className="field-input" type="datetime-local" value={data.date} onChange={(e) => set('date', e.target.value)} />
        </div>
      </div>
    )},
    { title: 'Your details', body: (
      <div>
        <div className="field">
          <label className="field-label">Name</label>
          <input className="field-input" value={data.name} onChange={(e) => set('name', e.target.value)} placeholder="Your full name" />
        </div>
        <div className="field">
          <label className="field-label">Email</label>
          <input className="field-input" type="email" value={data.email} onChange={(e) => set('email', e.target.value)} placeholder="name@example.com" />
        </div>
        <div className="field">
          <label className="field-label">WhatsApp / Phone</label>
          <input className="field-input" type="tel" value={data.phone} onChange={(e) => set('phone', e.target.value)} placeholder="+971 …" />
        </div>
        <div className="field">
          <label className="field-label">Anything we should know?</label>
          <textarea className="field-textarea" value={data.message} onChange={(e) => set('message', e.target.value)} placeholder="A stone you have in mind, an heirloom to rework, a reference…" />
        </div>
      </div>
    )},
    { title: 'Booked', body: (
      <div style={{textAlign: 'center', padding: '20px 0'}}>
        <div style={{width: 72, height: 72, borderRadius: '50%', border: '1px solid var(--palace-gold)', display: 'grid', placeItems: 'center', margin: '0 auto 24px', color: 'var(--palace-gold)'}}>
          <Icon.Check size={28} />
        </div>
        <h3 className="display" style={{margin: 0, fontSize: 32}}>Thank you, {data.name?.split(' ')[0] || 'we have you'}.</h3>
        <p style={{color: 'var(--ink-60)', maxWidth: 380, margin: '14px auto 0'}}>
          A consultant from our {data.showroom === 'gate-1' ? 'Gate 1' : data.showroom === 'gate-3' ? 'Gate 3' : 'Virtual'} room will be in touch within the working day. We'll reserve a private table and prepare a curated selection ahead of your visit.
        </p>
        <p style={{color: 'var(--ink-40)', fontSize: 13, marginTop: 32}}>Reference · PJ-{Math.random().toString(36).slice(2, 8).toUpperCase()}</p>
      </div>
    )},
  ];

  const isLast = step === steps.length - 1;
  const canAdvance = (() => {
    if (step === 0) return !!data.occasion;
    if (step === 1) return !!data.budget && !!data.metal;
    if (step === 2) return !!data.showroom;
    if (step === 3) return !!data.name && (data.email || data.phone);
    return true;
  })();

  return (
    <React.Fragment>
      <div className="drawer-backdrop" onClick={onClose} />
      <aside className="drawer" role="dialog" aria-label="Book a private consultation">
        <div style={{padding: '28px 36px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid var(--ink-10)'}}>
          <div>
            <div className="eyebrow">Private Consultation</div>
            <div className="display" style={{fontSize: 24, marginTop: 4}}>{steps[step].title}</div>
          </div>
          <button className="nav__icon-btn" onClick={onClose} aria-label="Close"><Icon.Close /></button>
        </div>

        {!isLast && (
          <div style={{display: 'flex', padding: '0 36px', marginTop: 28, gap: 6}}>
            {steps.slice(0, -1).map((_, i) => (
              <div key={i} style={{
                flex: 1, height: 2,
                background: i <= step ? 'var(--palace-gold)' : 'var(--ink-20)',
                transition: 'background 0.3s',
              }} />
            ))}
          </div>
        )}

        <div style={{padding: '32px 36px 24px', minHeight: 320}}>
          {steps[step].body}
        </div>

        {!isLast && (
          <div style={{padding: '24px 36px 40px', display: 'flex', gap: 12, justifyContent: 'space-between', borderTop: '1px solid var(--ink-10)'}}>
            <button className="btn-link" onClick={() => step > 0 ? setStep(step - 1) : onClose()}>
              {step === 0 ? 'Cancel' : '← Back'}
            </button>
            <button className="btn btn-primary" disabled={!canAdvance} onClick={() => setStep(step + 1)} style={{opacity: canAdvance ? 1 : 0.4}}>
              {step === 3 ? 'Confirm Booking' : 'Continue'}
            </button>
          </div>
        )}
        {isLast && (
          <div style={{padding: '24px 36px 40px', textAlign: 'center'}}>
            <button className="btn btn-ghost" onClick={onClose}>Close</button>
          </div>
        )}
      </aside>
    </React.Fragment>
  );
};

// ===========================================================
// WhatsApp FAB
// ===========================================================
const WhatsAppFab = () => (
  <a className="whatsapp-fab"
     href="https://wa.me/971545839411?text=Hi%20Palaces%20Jewellery%2C%20I%27d%20like%20to%20book%20a%20private%20consultation"
     target="_blank" rel="noreferrer"
     aria-label="WhatsApp Palaces Jewellery">
    <Icon.WhatsApp size={28} />
  </a>
);

// ===========================================================
// Sticky consult bar
// ===========================================================
const ConsultBar = ({onOpen}) => {
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 600);
    onScroll();
    window.addEventListener('scroll', onScroll, {passive: true});
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  if (!visible) return null;
  return (
    <div className="consult-bar">
      <span>Private consultation · Gold Souk, Deira</span>
      <button className="consult-bar__cta" onClick={onOpen}>Book →</button>
    </div>
  );
};

// ===========================================================
// Footer
// ===========================================================
const Footer = () => (
  <footer style={{
    background: 'var(--royal-night)',
    color: '#E6D2A2',
    padding: '80px 0 32px',
    marginTop: 80,
  }}>
    <div className="shell">
      <div style={{display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 56, marginBottom: 64}}>
        <div>
          <div style={{display: 'flex', alignItems: 'center', gap: 10, color: 'var(--palace-gold)'}}>
            <Icon.Crown size={28} />
            <span style={{
              fontFamily: 'var(--font-display)',
              fontStyle: 'italic',
              fontSize: 28,
              color: '#FFF',
            }}>
              Palaces
              <span style={{
                fontStyle: 'normal',
                fontFamily: 'var(--font-body)',
                fontSize: 10,
                letterSpacing: '0.36em',
                marginLeft: 8,
                verticalAlign: 'middle',
                color: 'var(--gold-soft)',
              }}>JEWELLERY</span>
            </span>
          </div>
          <p style={{marginTop: 24, maxWidth: 360, lineHeight: 1.7, color: 'rgba(230, 210, 162, 0.7)'}}>
            A family jewellery house in Dubai's Gold Souk since 1998. Crafted in our own atelier in Bangkok, finished by hand in Deira.
          </p>
          <p style={{marginTop: 24, fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 22, color: 'var(--gold-soft)'}}>
            "look regal, feel royal"
          </p>
        </div>

        <FooterCol title="Visit" items={[
          'Gate 3 · Dalmook Bldg, Shop #5',
          'Gate 1 · Al Ghurair Bldg, Shop #4&5',
          'Old Gold Souk, Deira · Dubai',
          'Daily 10:00 — 22:00',
        ]} />
        <FooterCol title="House" items={[
          'Heritage', 'Bespoke', 'The Atelier · Bangkok', 'Care & Services', 'Certification',
        ]} />
        <FooterCol title="Contact" items={[
          '+971 4 591 2373 (Gate 3)',
          '+971 4 225 5972 (Gate 1)',
          'WhatsApp +971 54 583 9411',
          'info@palacesjewellery.com',
        ]} />
      </div>

      <hr style={{border: 0, height: 1, background: 'rgba(230, 210, 162, 0.15)'}} />

      <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 24, fontSize: 12, color: 'rgba(230, 210, 162, 0.5)', letterSpacing: '0.06em'}}>
        <span>© Palaces Jewellery LLC · Dubai, UAE</span>
        <span>Instagram · Facebook · TikTok · LinkedIn</span>
      </div>
    </div>
  </footer>
);

const FooterCol = ({title, items}) => (
  <div>
    <div className="eyebrow" style={{color: 'var(--palace-gold)'}}>{title}</div>
    <ul style={{listStyle: 'none', margin: '20px 0 0', padding: 0, display: 'flex', flexDirection: 'column', gap: 12}}>
      {items.map((i) => <li key={i} style={{color: 'rgba(230, 210, 162, 0.75)', fontSize: 13, lineHeight: 1.6}}>{i}</li>)}
    </ul>
  </div>
);

Object.assign(window, { Navbar, ConsultationDrawer, WhatsAppFab, ConsultBar, Footer });
