// Shared UI: Nav, Footer, Reveal, helpers
const { useState, useEffect, useRef, useContext, createContext } = React;

// Router context
const RouterContext = createContext({ route: { name: 'home' }, navigate: () => {} });
const useRouter = () => useContext(RouterContext);

// Format AED
function aed(n) {
  return 'AED ' + n.toLocaleString('en-US');
}

// Reveal-on-scroll
function Reveal({ children, delay = 0, as: As = 'div', className = '', ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } });
      },
      { threshold: 0.12, rootMargin: '0px 0px -40px 0px' }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <As
      ref={ref}
      className={`reveal ${seen ? 'is-in' : ''} ${className}`}
      style={{ transitionDelay: delay + 'ms' }}
      {...rest}
    >
      {children}
    </As>
  );
}

// Link that uses router navigate
function NavLink({ to, params, children, className = '', onClick }) {
  const { navigate } = useRouter();
  return (
    <a
      href="#"
      className={className}
      onClick={(e) => {
        e.preventDefault();
        if (onClick) onClick(e);
        navigate(to, params);
      }}
    >
      {children}
    </a>
  );
}

// Top bar
function TopNav({ arabicAccent }) {
  const { route, navigate } = useRouter();
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = [
    { to: 'collections', label: 'Collections' },
    { to: 'bespoke', label: 'Bespoke' },
    { to: 'concierge', label: 'Concierge' },
    { to: 'story', label: 'Our Story' },
    { to: 'boutiques', label: 'Boutiques' },
    { to: 'contact', label: 'Contact' },
  ];

  return (
    <>
      <style>{`
        .topnav {
          position: fixed;
          top: 0; left: 0; right: 0;
          z-index: 50;
          padding: 18px 0;
          transition: all 0.4s ease;
          background: ${scrolled ? 'color-mix(in oklab, var(--bg) 86%, transparent)' : 'transparent'};
          backdrop-filter: ${scrolled ? 'blur(14px) saturate(1.2)' : 'none'};
          border-bottom: 1px solid ${scrolled ? 'var(--rule)' : 'transparent'};
        }
        .topnav__inner {
          display: grid;
          grid-template-columns: 1fr auto 1fr;
          align-items: center;
          gap: 24px;
        }
        .topnav__left { display: flex; align-items: center; gap: 22px; font-size: 12px; letter-spacing: 0.16em; text-transform: uppercase; color: var(--fg-mute); }
        .topnav__right { display: flex; align-items: center; justify-content: flex-end; gap: 22px; font-size: 12px; letter-spacing: 0.16em; text-transform: uppercase; color: var(--fg-mute); }
        .topnav__link { transition: color 0.25s ease; cursor: pointer; }
        .topnav__link:hover, .topnav__link.is-active { color: var(--accent); }
        .topnav__brand {
          display: flex; flex-direction: column; align-items: center; gap: 2px;
          font-family: var(--display, var(--serif));
          font-size: 28px;
          letter-spacing: 0.28em;
          padding: 0 12px;
          cursor: pointer;
        }
        .topnav__brand-arabic {
          font-family: var(--arabic);
          font-size: 14px;
          letter-spacing: 0;
          color: var(--accent);
          opacity: ${arabicAccent ? 1 : 0};
          height: ${arabicAccent ? 'auto' : 0};
          transition: opacity 0.4s ease;
          margin-top: -2px;
        }
        .topnav__cta {
          font-size: 11px;
          letter-spacing: 0.2em;
          padding: 10px 16px;
          border: 1px solid var(--rule-strong);
          transition: all 0.3s ease;
        }
        .topnav__cta:hover { border-color: var(--accent); color: var(--accent); }
        .topnav__burger { display: none; }
        @media (max-width: 980px) {
          .topnav__left, .topnav__right { display: none; }
          .topnav__inner { grid-template-columns: 1fr auto 1fr; }
          .topnav__burger { display: flex; justify-self: start; flex-direction: column; gap: 4px; padding: 8px; }
          .topnav__burger span { width: 22px; height: 1px; background: var(--fg); }
          .topnav__right-mobile { justify-self: end; display: flex; gap: 10px; }
        }
        .mobile-sheet {
          position: fixed; inset: 0; z-index: 60;
          background: var(--bg);
          padding: 80px var(--pad);
          display: flex; flex-direction: column; gap: 8px;
          transform: ${mobileOpen ? 'translateX(0)' : 'translateX(100%)'};
          transition: transform 0.4s ease;
        }
        .mobile-sheet a {
          font-family: var(--display, var(--serif));
          font-size: 36px;
          padding: 10px 0;
          border-bottom: 1px solid var(--rule);
        }
        .mobile-sheet__close {
          position: absolute; top: 24px; right: 24px;
          font-size: 22px;
        }
      `}</style>
      <header className="topnav">
        <div className="container topnav__inner">
          <div className="topnav__left">
            {links.slice(0, 3).map((l) => (
              <a key={l.to} href="#" className={`topnav__link ${route.name === l.to ? 'is-active' : ''}`}
                onClick={(e) => { e.preventDefault(); navigate(l.to); }}>{l.label}</a>
            ))}
          </div>
          <button className="topnav__burger" onClick={() => setMobileOpen(true)} aria-label="Menu">
            <span></span><span></span><span></span>
          </button>
          <a href="#" className="topnav__brand"
            onClick={(e) => { e.preventDefault(); navigate('home'); }}>
            GAFLA
            <span className="topnav__brand-arabic">قافِلة</span>
          </a>
          <div className="topnav__right">
            {links.slice(3).map((l) => (
              <a key={l.to} href="#" className={`topnav__link ${route.name === l.to ? 'is-active' : ''}`}
                onClick={(e) => { e.preventDefault(); navigate(l.to); }}>{l.label}</a>
            ))}
            <a href="#" className="topnav__cta"
              onClick={(e) => { e.preventDefault(); navigate('contact', { tab: 'majlis' }); }}>
              Book a Viewing
            </a>
          </div>
          <div className="topnav__right-mobile" style={{ display: 'none' }}>
            <a href="#" className="topnav__cta"
              onClick={(e) => { e.preventDefault(); navigate('contact', { tab: 'majlis' }); }}>
              Book
            </a>
          </div>
        </div>
      </header>
      <div className="mobile-sheet">
        <button className="mobile-sheet__close" onClick={() => setMobileOpen(false)} aria-label="Close">✕</button>
        {links.map((l) => (
          <a key={l.to} href="#"
            onClick={(e) => { e.preventDefault(); navigate(l.to); setMobileOpen(false); }}>
            {l.label}
          </a>
        ))}
      </div>
    </>
  );
}

// Footer
function Footer() {
  const { navigate } = useRouter();
  return (
    <>
      <style>{`
        .footer {
          background: var(--surface);
          padding: 100px 0 28px;
          margin-top: 0;
          color: var(--fg);
          border-top: 1px solid var(--rule);
        }
        .footer__top {
          display: grid;
          grid-template-columns: 1.4fr 1fr 1fr 1fr;
          gap: 60px;
          padding-bottom: 60px;
          border-bottom: 1px solid var(--rule);
        }
        @media (max-width: 880px) {
          .footer__top { grid-template-columns: 1fr 1fr; gap: 40px; }
        }
        .footer__brand h3 {
          font-family: var(--display, var(--serif));
          font-size: 40px;
          letter-spacing: 0.18em;
          margin-bottom: 8px;
        }
        .footer__brand p {
          color: var(--fg-mute);
          max-width: 320px;
          font-size: 14px;
          line-height: 1.6;
        }
        .footer__col h4 {
          font-family: var(--sans);
          font-size: 11px;
          font-weight: 500;
          letter-spacing: 0.22em;
          text-transform: uppercase;
          color: var(--fg-mute);
          margin-bottom: 22px;
        }
        .footer__col ul { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; }
        .footer__col a {
          font-size: 14px;
          color: var(--fg);
          transition: color 0.2s;
          cursor: pointer;
        }
        .footer__col a:hover { color: var(--accent); }
        .footer__bottom {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-top: 28px;
          font-size: 12px;
          color: var(--fg-mute);
          letter-spacing: 0.08em;
        }
        .footer__socials { display: flex; gap: 18px; }
        .footer__socials a { font-size: 12px; letter-spacing: 0.18em; text-transform: uppercase; }
        .footer__flag {
          display: inline-flex; align-items: center; gap: 8px;
          padding: 4px 10px;
          border: 1px solid var(--rule-strong);
          font-size: 10px;
          letter-spacing: 0.18em;
          text-transform: uppercase;
          color: var(--fg-mute);
        }
        .footer__flag::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--accent); display: inline-block; }
      `}</style>
      <footer className="footer">
        <div className="container">
          <div className="footer__top">
            <div className="footer__brand">
              <h3>GAFLA</h3>
              <p>Gafla — a caravan. Contemporary fine jewellery rooted in Emirati heritage, designed and curated from Dubai Design District.</p>
              <div style={{ marginTop: 22 }} className="footer__flag">
                <span>Publicly launched 2015</span>
              </div>
            </div>
            <div className="footer__col">
              <h4>Maison</h4>
              <ul>
                <li><a onClick={() => navigate('story')}>Our Story</a></li>
                <li><a onClick={() => navigate('bespoke')}>Bespoke</a></li>
                <li><a onClick={() => navigate('concierge')}>Concierge</a></li>
                <li><a onClick={() => navigate('boutiques')}>Boutiques</a></li>
              </ul>
            </div>
            <div className="footer__col">
              <h4>Collections</h4>
              <ul>
                {COLLECTIONS.slice(0, 7).map((c) => (
                  <li key={c.id}><a onClick={() => navigate('collection', { id: c.id })}>{c.name}</a></li>
                ))}
              </ul>
            </div>
            <div className="footer__col">
              <h4>Contact</h4>
              <ul style={{ color: 'var(--fg-mute)' }}>
                <li>{CONTACT.address}</li>
                <li>{CONTACT.district}</li>
                <li style={{ marginTop: 8 }}><a href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a></li>
                <li><a href={`tel:${CONTACT.landline.replace(/\s/g,'')}`}>{CONTACT.landline}</a></li>
                <li><a href={CONTACT.whatsapp} target="_blank" rel="noreferrer">WhatsApp · {CONTACT.mobile}</a></li>
              </ul>
            </div>
          </div>
          <div className="footer__bottom">
            <div>© Gafla Jewellery LLC. All rights reserved.</div>
            <div className="footer__socials">
              <a href={CONTACT.instagram} target="_blank" rel="noreferrer">Instagram</a>
              <a href={CONTACT.facebook} target="_blank" rel="noreferrer">Facebook</a>
              <a href={CONTACT.snapchat} target="_blank" rel="noreferrer">Snapchat</a>
            </div>
          </div>
        </div>
      </footer>
    </>
  );
}

// Generic split layout — image + text
function Split({ image, alt, kicker, title, body, cta, reverse, tall }) {
  return (
    <>
      <style>{`
        .split { display: grid; grid-template-columns: 1fr 1fr; gap: clamp(40px, 6vw, 100px); align-items: center; }
        .split--reverse { direction: rtl; }
        .split--reverse > * { direction: ltr; }
        .split__img { aspect-ratio: ${tall ? '3/4' : '4/5'}; overflow: hidden; }
        .split__img img { width: 100%; height: 100%; object-fit: cover; transition: transform 1.2s ease; }
        .split:hover .split__img img { transform: scale(1.03); }
        .split__title { font-size: clamp(36px, 5vw, 64px); margin: 16px 0 24px; }
        .split__body { color: var(--fg-mute); font-size: 16px; line-height: 1.7; max-width: 480px; }
        @media (max-width: 760px) {
          .split { grid-template-columns: 1fr; }
          .split--reverse { direction: ltr; }
        }
      `}</style>
      <div className={`split ${reverse ? 'split--reverse' : ''}`}>
        <Reveal className="split__img"><img src={image} alt={alt} loading="lazy" /></Reveal>
        <div>
          <Reveal>
            <div className="eyebrow">{kicker}</div>
            <h2 className="split__title" dangerouslySetInnerHTML={{ __html: title }} />
            <p className="split__body">{body}</p>
            {cta && (
              <div style={{ marginTop: 32 }}>{cta}</div>
            )}
          </Reveal>
        </div>
      </div>
    </>
  );
}

// Caravan divider — animated dotted line referencing the caravan name + 4-bead pattern from Sak
function CaravanDivider({ label }) {
  return (
    <>
      <style>{`
        .caravan { display: flex; align-items: center; gap: 20px; padding: 8px 0; color: var(--fg-mute); }
        .caravan__line { flex: 1; height: 1px; background: linear-gradient(to right, transparent, var(--rule-strong), transparent); }
        .caravan__dots { display: flex; gap: 6px; }
        .caravan__dots i { width: 4px; height: 4px; border-radius: 50%; background: var(--accent); display: inline-block; }
        .caravan__label { font-size: 11px; letter-spacing: 0.28em; text-transform: uppercase; }
      `}</style>
      <div className="caravan">
        <div className="caravan__line"></div>
        <div className="caravan__dots"><i></i><i></i><i></i><i></i></div>
        {label && <div className="caravan__label">{label}</div>}
        <div className="caravan__dots"><i></i><i></i><i></i><i></i></div>
        <div className="caravan__line"></div>
      </div>
    </>
  );
}

// Product card
function ProductCard({ product, onClick }) {
  return (
    <>
      <style>{`
        .pcard { cursor: pointer; display: flex; flex-direction: column; gap: 14px; }
        .pcard__img {
          aspect-ratio: 1/1;
          background: var(--surface);
          overflow: hidden;
          position: relative;
        }
        .pcard__img img { width: 100%; height: 100%; object-fit: contain; padding: 16%; transition: transform 0.6s ease; }
        .pcard:hover .pcard__img img { transform: scale(1.06); }
        .pcard__col {
          position: absolute; top: 14px; left: 14px;
          font-size: 10px; letter-spacing: 0.22em; text-transform: uppercase;
          color: var(--accent);
        }
        .pcard__name { font-family: var(--display, var(--serif)); font-size: 18px; line-height: 1.25; }
        .pcard__meta { display: flex; justify-content: space-between; align-items: center; color: var(--fg-mute); font-size: 13px; }
        .pcard__price { color: var(--fg); font-feature-settings: "tnum"; }
      `}</style>
      <div className="pcard" onClick={onClick}>
        <div className="pcard__img">
          <div className="pcard__col">{product.type}</div>
          <img src={product.image} alt={product.name} loading="lazy" />
        </div>
        <div className="pcard__name">{product.name}</div>
        <div className="pcard__meta">
          <span>{COLLECTIONS.find(c => c.id === product.collection)?.name}</span>
          <span className="pcard__price">{aed(product.price)}</span>
        </div>
      </div>
    </>
  );
}

// Quiet "scroll" indicator
function ScrollHint({ label = 'Scroll' }) {
  return (
    <>
      <style>{`
        .scroll-hint {
          position: absolute; bottom: 36px; left: 50%; transform: translateX(-50%);
          display: flex; flex-direction: column; align-items: center; gap: 14px;
          color: var(--fg-mute);
          font-size: 10px; letter-spacing: 0.32em; text-transform: uppercase;
        }
        .scroll-hint__line {
          width: 1px; height: 36px;
          background: linear-gradient(to bottom, transparent, var(--fg-mute));
          animation: scrollPulse 2.4s ease-in-out infinite;
          transform-origin: top;
        }
        @keyframes scrollPulse {
          0%, 100% { transform: scaleY(0.3); opacity: 0.3; }
          50% { transform: scaleY(1); opacity: 1; }
        }
      `}</style>
      <div className="scroll-hint">
        <span>{label}</span>
        <span className="scroll-hint__line"></span>
      </div>
    </>
  );
}

Object.assign(window, {
  useRouter, RouterContext, aed,
  Reveal, NavLink, TopNav, Footer, Split, CaravanDivider, ProductCard, ScrollHint,
});
