/* Shared components — Nav, Footer, primitives */
const { useState, useEffect, useRef, useMemo } = React;

const NAV_ITEMS = [
  { id: 'story', label: 'The Story' },
  { id: 'collections', label: 'Collections' },
  { id: 'craftsmanship', label: 'Craftsmanship' },
  { id: 'projects', label: 'Projects' },
  { id: 'bespoke', label: 'Bespoke' },
  { id: 'impact', label: 'Impact' },
  { id: 'showroom', label: 'Showroom' },
  { id: 'contact', label: 'Contact' }
];

function go(id) {
  window.location.hash = '#/' + id;
  window.scrollTo({ top: 0, behavior: 'instant' });
}

function useRoute() {
  const [route, setRoute] = useState(() => (window.location.hash.replace(/^#\//, '') || 'home'));
  useEffect(() => {
    const onHash = () => setRoute(window.location.hash.replace(/^#\//, '') || 'home');
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return [route, (id) => go(id)];
}

function Nav({ route, onNav, transparent }) {
  const [solid, setSolid] = useState(!transparent);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    if (!transparent) { setSolid(true); return; }
    const onScroll = () => setSolid(window.scrollY > 60);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [transparent]);

  return (
    <React.Fragment>
      <header className={'nav ' + (solid ? 'nav-solid' : 'nav-transparent')}>
        <div className="nav-inner">
          <a className="nav-logo" onClick={() => onNav('home')}>
            <div>
              <div className="wordmark">zuleya</div>
              <div className="subline">by FBMI · Dubai</div>
            </div>
          </a>
          <nav className="nav-links">
            {NAV_ITEMS.map(item => (
              <a key={item.id} className={'nav-link ' + (route === item.id ? 'active' : '')}
                 onClick={() => onNav(item.id)}>{item.label}</a>
            ))}
          </nav>
          <a className="nav-cta" onClick={() => onNav('consultation')}>Book a consultation</a>
          <button className="nav-mobile-toggle" onClick={() => setOpen(true)} aria-label="Open menu">Menu</button>
        </div>
      </header>
      <div className={'mobile-menu ' + (open ? 'open' : '')}>
        <button className="modal-close" onClick={() => setOpen(false)} style={{ top: 24, right: 24 }}>×</button>
        {NAV_ITEMS.map(item => (
          <a key={item.id} className={route === item.id ? 'active' : ''}
             onClick={() => { onNav(item.id); setOpen(false); }}>{item.label}</a>
        ))}
        <a onClick={() => { onNav('consultation'); setOpen(false); }} style={{ color: 'var(--gold)' }}>Book a consultation →</a>
      </div>
    </React.Fragment>
  );
}

function Footer({ onNav }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-top">
          <div className="footer-col">
            <div className="footer-wordmark">
              zuleya
              <span className="by">by FBMI · woven to change lives</span>
            </div>
            <p style={{ color: '#BFB29C', fontSize: 14, lineHeight: 1.6, marginTop: 36, maxWidth: 360 }}>
              An enterprise of the Fatima Bint Mohamed Bin Zayed Initiative — hand-knotted Afghan carpets,
              made in Mazar-i-Sharif by more than eight thousand artisans.
            </p>
          </div>
          <div className="footer-col">
            <h5>Explore</h5>
            <a onClick={() => onNav('story')}>The story</a>
            <a onClick={() => onNav('collections')}>Collections</a>
            <a onClick={() => onNav('craftsmanship')}>Craftsmanship</a>
            <a onClick={() => onNav('projects')}>Projects</a>
            <a onClick={() => onNav('bespoke')}>Bespoke</a>
            <a onClick={() => onNav('impact')}>Impact</a>
          </div>
          <div className="footer-col">
            <h5>Visit</h5>
            <div className="item">Showroom 1, Building 2</div>
            <div className="item">Dubai Design District (d3)</div>
            <div className="item">PO Box 27677, Dubai, UAE</div>
            <a onClick={() => onNav('showroom')} style={{ color: 'var(--gold-2)', marginTop: 12 }}>Plan a visit →</a>
          </div>
          <div className="footer-col">
            <h5>Contact</h5>
            <a href="tel:+97142432327">FBMI · +971 4 243 2327</a>
            <a href="tel:8009853929">Zuleya · 800 ZULEYA</a>
            <a href="mailto:info@fbmi.ae">info@fbmi.ae</a>
            <a href="mailto:hello@zuleya.ae">hello@zuleya.ae</a>
            <div style={{ marginTop: 18, display: 'flex', gap: 14 }}>
              <a>Instagram</a><a>LinkedIn</a><a>Houzz</a>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 Fatima Bint Mohamed Bin Zayed Initiative · all carpets hand-knotted in Mazar-i-Sharif</div>
          <div style={{ display: 'flex', gap: 24 }}>
            <a style={{ display: 'inline' }}>Privacy</a>
            <a style={{ display: 'inline' }}>Terms</a>
            <a style={{ display: 'inline' }}>Press</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* Primitives */
function Eyebrow({ children, dark }) {
  return <div className={'eyebrow' + (dark ? ' dark' : '')}>{children}</div>;
}

function CarpetCard({ c, dark, onOpen }) {
  const formatPrice = (n) => 'AED ' + n.toLocaleString('en-US');
  return (
    <a className={'carpet-card ' + (dark ? 'dark' : '')} onClick={() => onOpen && onOpen(c)}>
      <div className="img-wrap">
        <span className="collection-tag">{c.collection}</span>
        <img src={c.img} alt={c.name} loading="lazy" />
      </div>
      <div className="meta">
        <div>
          <div className="name serif">{c.name}</div>
          <div className="size mono">{c.size}</div>
        </div>
        <div className="price serif">
          <span className="from">From</span>
          {formatPrice(c.priceAed)}
        </div>
      </div>
    </a>
  );
}

function QuickViewModal({ carpet, onClose, onEnquire, onSave, saved }) {
  useEffect(() => {
    if (!carpet) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [carpet, onClose]);

  return (
    <div className={'modal-bg ' + (carpet ? 'open' : '')} onClick={onClose}>
      {carpet && (
        <div className="modal" onClick={(e) => e.stopPropagation()}>
          <div className="modal-img" style={{ backgroundImage: `url(${carpet.img})` }}>
            <button className="modal-close" onClick={onClose}>×</button>
          </div>
          <div className="modal-body">
            <Eyebrow>{carpet.collection} collection</Eyebrow>
            <h2 className="serif" style={{ fontSize: 56, lineHeight: 1, margin: '20px 0 8px', fontWeight: 400 }}>
              {carpet.name}
            </h2>
            <p className="lead" style={{ fontSize: 16, marginBottom: 28 }}>{carpet.notes}</p>

            <div style={{ marginBottom: 28 }}>
              <div className="spec-row"><span className="k">Size</span><span className="v mono">{carpet.size}</span></div>
              <div className="spec-row"><span className="k">Knots</span><span className="v mono">{carpet.knots}</span></div>
              <div className="spec-row"><span className="k">Time at loom</span><span className="v">{carpet.months}</span></div>
              <div className="spec-row"><span className="k">Dye</span><span className="v">{carpet.dye}</span></div>
              <div className="spec-row"><span className="k">Woven in</span><span className="v">{carpet.origin}</span></div>
            </div>

            <div style={{ borderTop: '1px solid var(--line)', paddingTop: 24, marginBottom: 32 }}>
              <div className="serif" style={{ fontSize: 36, lineHeight: 1, marginBottom: 4 }}>
                AED {carpet.priceAed.toLocaleString('en-US')}
              </div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.14em' }}>
                ONE-OF-ONE · INCL. CERTIFICATE OF AUTHENTICITY
              </div>
            </div>

            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <button className="btn btn-primary" onClick={() => onEnquire(carpet)}>
                Enquire about this carpet <span className="arrow">→</span>
              </button>
              <button className="btn btn-ghost-dark" onClick={() => onSave(carpet)}>
                {saved ? 'Saved ✓' : 'Save to portfolio'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function Toast({ message, onDone }) {
  useEffect(() => {
    if (!message) return;
    const t = setTimeout(() => onDone(), 3400);
    return () => clearTimeout(t);
  }, [message, onDone]);
  return <div className={'toast ' + (message ? 'show' : '')}>{message}</div>;
}

function PageHeader({ eyebrow, title, lead, dark }) {
  return (
    <section className={'section-sm ' + (dark ? 'noir' : '')} style={{ paddingTop: 180 }}>
      <div className="container">
        <Eyebrow dark={dark}>{eyebrow}</Eyebrow>
        <h1 className="h-display" style={{ marginTop: 24, maxWidth: 1100 }}>{title}</h1>
        {lead && <p className="lead" style={{ marginTop: 32, fontSize: 19, maxWidth: 720 }}>{lead}</p>}
      </div>
    </section>
  );
}

function DiplomacyBand({ onNav }) {
  return (
    <section className="diplomacy">
      <div className="diplomacy-bg" style={{ backgroundImage: 'url(media/media-01-fbmi-slider-main-img.webp)' }}></div>
      <div className="container diplomacy-content">
        <div className="mark serif">“</div>
        <Eyebrow dark>The Tolerance Carpet · 2016</Eyebrow>
        <h2 className="h-section serif" style={{ margin: '24px 0 24px', maxWidth: 800 }}>
          The carpet presented to His Holiness Pope Francis by His Highness Sheikh Mohamed bin Zayed Al Nahyan was hand-knotted in Mazar-i-Sharif.
        </h2>
        <p style={{ color: '#BFB29C', fontSize: 15, lineHeight: 1.7, maxWidth: 640, margin: '0 auto' }}>
          Zuleya carpets have been gifted by His Highness Sheikh Mohamed bin Zayed Al Nahyan as state gifts —
          to Pope Francis, to President Barack Obama, to Bill Gates, to Christine Lagarde — drawn for each recipient,
          knotted by the same artisans who weave a Zuleya runner you can take home from Dubai Design District.
        </p>
        <div style={{ marginTop: 40 }}>
          <button className="btn btn-ghost-light" onClick={() => onNav('impact')}>
            The full story <span className="arrow">→</span>
          </button>
        </div>
      </div>
    </section>
  );
}

function CtaBand({ onNav }) {
  return (
    <section className="cta-band">
      <div className="container cta-band-inner">
        <div>
          <Eyebrow dark>Begin a piece</Eyebrow>
          <div className="serif" style={{ fontSize: 'clamp(32px, 4vw, 56px)', lineHeight: 1.05, marginTop: 18, color: 'var(--ivory)' }}>
            A consultation in d3, or a video call from your studio.
          </div>
          <div style={{ color: '#BFB29C', fontSize: 15, marginTop: 16, maxWidth: 540 }}>
            Forty-five minutes with our design team. Bring a floor plan, a fabric, a mood — we will brief
            samples within two weeks and a strike-off within six.
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <button className="btn btn-primary" onClick={() => onNav('consultation')}>Book a consultation <span className="arrow">→</span></button>
          <button className="btn btn-ghost-light" onClick={() => onNav('bespoke')}>How bespoke works</button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  useRoute, go, Nav, Footer, Eyebrow,
  CarpetCard, QuickViewModal, Toast,
  PageHeader, DiplomacyBand, CtaBand,
  NAV_ITEMS
});
