/* ViZO Studio — Top navigation with Platform mega-menu.
   Spec: 4 items (Platform ▾, Solutions, Gallery, Pricing) + Sign in / Start free trial.
   Transparent on hero, paper bg + blur after 80px scroll. */

const { useState: useStateTN, useEffect: useEffectTN, useRef: useRefTN } = React;

/* ------- Tweak context (filled by App; safe fallbacks here) ------- */
const NavTweaksCtx = React.createContext({ logoGap: 24, linkGap: 32 });
window.NavTweaksCtx = NavTweaksCtx;
function useNavTweaks() { return React.useContext(NavTweaksCtx); }

/* ------- Mega-menu content ------- */

const PLATFORM_COLUMNS = [
{
  heading: 'Inputs',
  items: [
  { title: 'Garment & product upload', desc: 'Drop a flat-lay. We extract the silhouette.', icon: 'shirt' },
  { title: 'Accessory upload', desc: 'Bags, shoes, jewellery — composited in scene.', icon: 'package' },
  { title: 'SKU batch upload', desc: 'Spreadsheet in, full season out.', icon: 'list' },
  { title: 'Flat-lay & ghost mannequin', desc: 'Either silhouette source works.', icon: 'ghost' }]

},
{
  heading: 'Generation',
  items: [
  { title: 'Model generation', desc: 'Real faces. Sized, posed, lit on direction.', icon: 'user' },
  { title: 'Environment creation', desc: 'Studio, location, season — your set.', icon: 'tree' },
  { title: 'Studio briefing', desc: 'Direct the shoot in plain language.', icon: 'wand' },
  { title: 'Digital twin creation', desc: 'Lock a model and reuse them all season.', icon: 'scan' }]

},
{
  heading: 'Output',
  items: [
  { title: 'Resolution: 1K / 2K / 4K', desc: 'Pay only for what you export.', icon: 'resolution' },
  { title: 'Bulk processing', desc: 'Overnight queue across thousands of SKUs.', icon: 'layers' },
  { title: 'SEO friendly text generation', desc: 'Auto-generated product descriptions, tuned for search engines.', icon: 'type' },
  { title: 'Image editing', desc: 'Refine before you download.', icon: 'pencil' }]

}];


window.PLATFORM_COLUMNS = PLATFORM_COLUMNS;

/* ------- Helpers ------- */

function MegaTrigger({ label, open, onEnter, onLeave, onClick, active }) {
  const [hover, setHover] = useStateTN(false);
  return (
    <button
      onMouseEnter={() => {setHover(true);onEnter && onEnter();}}
      onMouseLeave={() => {setHover(false);onLeave && onLeave();}}
      onClick={onClick}
      aria-expanded={open}
      style={{
        position: 'relative',
        display: 'inline-flex', alignItems: 'center', gap: 6,
        background: 'transparent', border: 'none', cursor: 'pointer',
        padding: '8px 0',
        fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 500,
        color: hover || open || active ? 'var(--ink)' : 'var(--graphite)',
        transition: 'color 150ms var(--ease-standard)'
      }}>
      
      {label}
      <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? 'rotate(180deg)' : 'rotate(0)', transition: 'transform 200ms var(--ease-standard)' }}><polyline points="6 9 12 15 18 9" /></svg>
      <span style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, height: 2,
        background: 'var(--ink)',
        transform: hover || open ? 'scaleX(1)' : 'scaleX(0)',
        transformOrigin: 'left center',
        transition: 'transform 200ms var(--ease-standard)'
      }} />
      {active &&
      <span style={{ position: 'absolute', left: 0, right: 0, bottom: -8, height: 2, background: 'var(--ink)' }} />
      }
    </button>);

}

function NavDirect({ to, label, active }) {
  const [hover, setHover] = useStateTN(false);
  return (
    <Link to={to} style={{
      position: 'relative',
      padding: '8px 0',
      fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 500,
      color: hover || active ? 'var(--ink)' : 'var(--graphite)',
      textDecoration: 'none',
      transition: 'color 150ms var(--ease-standard)'
    }}
    onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
      
      {label}
      <span style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, height: 2,
        background: 'var(--ink)',
        transform: hover ? 'scaleX(1)' : 'scaleX(0)',
        transformOrigin: 'left center',
        transition: 'transform 200ms var(--ease-standard)'
      }} />
      {active &&
      <span style={{ position: 'absolute', left: 0, right: 0, bottom: -8, height: 2, background: 'var(--ink)' }} />
      }
    </Link>);

}

/* ------- Mega-menu panels ------- */

function PlatformMenu({ onClose }) {
  const { isTablet } = useBreakpoint();
  return (
    <div onMouseLeave={onClose} style={{
      position: 'absolute', top: '100%', left: 0, right: 0,
      background: 'var(--canvas)',
      borderTop: '1px solid var(--bone)',
      borderBottom: '1px solid var(--bone)',
      boxShadow: '0 24px 40px rgba(0,0,0,0.06)',
      animation: 'megaIn 200ms var(--ease-standard)',
      maxHeight: 'calc(100vh - 72px)', overflowY: 'auto'
    }}>
      <div style={{
        maxWidth: 1280, margin: '0 auto',
        padding: `clamp(28px, 4vw, 40px) clamp(24px, 4vw, 48px) clamp(32px, 5vw, 48px)`,
        display: 'grid',
        gridTemplateColumns: isTablet ? '1fr 1fr' : '1fr 1fr 1fr 0.9fr',
        gap: 'clamp(28px, 4vw, 56px)'
      }}>
        {PLATFORM_COLUMNS.map((col) =>
        <div key={col.heading}>
            <Eyebrow color="var(--graphite)">{col.heading}</Eyebrow>
            <ul style={{ listStyle: 'none', padding: 0, margin: '20px 0 0', display: 'flex', flexDirection: 'column', gap: 18 }}>
              {col.items.map((it) => {
              const IconComp = Icon[it.icon] || Icon.sparkle;
              return (
                <li key={it.title}>
                    <a href="/platform" onClick={(e) => {e.preventDefault();navigate('/platform');onClose();}}
                  style={{ display: 'flex', gap: 12, textDecoration: 'none', color: 'inherit' }}
                  onMouseEnter={(e) => {e.currentTarget.querySelector('.t').style.color = 'var(--ink)';}}
                  onMouseLeave={(e) => {e.currentTarget.querySelector('.t').style.color = 'var(--ink)';}}>
                      <span style={{ flex: '0 0 auto', width: 28, height: 28, borderRadius: 6, background: 'var(--paper)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)' }}>
                        <IconComp width="16" height="16" />
                      </span>
                      <span>
                        <span className="t" style={{ display: 'block', fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.005em' }}>{it.title}</span>
                        <span style={{ display: 'block', marginTop: 2, fontSize: 12.5, lineHeight: 1.5, color: 'var(--slate)' }}>{it.desc}</span>
                      </span>
                    </a>
                  </li>);

            })}
            </ul>
          </div>
        )}

        {/* Featured tile */}
        <a href="/gallery" onClick={(e) => {e.preventDefault();navigate('/gallery');onClose();}}
        style={{ display: 'block', textDecoration: 'none', color: 'inherit' }}>
          <FashionPlate ratio="4 / 5" label="Studio · 4K" subject="see it in action" src="assets/hero-model-garden.png" position="center 22%" idx={1} />
          <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 8, color: 'var(--ink)', fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600 }}>
            See the Studio in action <span>→</span>
          </div>
        </a>
      </div>
    </div>);

}

/* ------- Mobile menu ------- */

function MobileMenu({ open, onClose }) {
  const [openAccordion, setOpenAcc] = useStateTN(null);
  const { theme } = useTheme();
  const logoSrc = theme === 'dark' ? 'assets/vizo-logo-white.png' : 'assets/vizo-logo-black.png';
  if (!open) return null;
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 60,
      background: 'var(--paper)',
      animation: 'slideIn 280ms var(--ease-entrance)',
      display: 'flex', flexDirection: 'column',
      overflowY: 'auto'
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 20px', height: 64, borderBottom: '1px solid var(--bone)' }}>
        <img src={logoSrc} alt="ViZO" style={{ height: 20 }} />
        <button onClick={onClose} aria-label="Close menu" style={{
          width: 40, height: 40, borderRadius: 999, background: 'transparent',
          border: '1px solid var(--mist)', cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
        </button>
      </div>
      <nav style={{ padding: '24px 20px 32px', flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <a href="/platform" onClick={(e) => {e.preventDefault();navigate('/platform');onClose();}} style={mobileLink}>Platform</a>
        <a href="/solutions" onClick={(e) => {e.preventDefault();navigate('/solutions');onClose();}} style={mobileLink}>Solutions</a>
        <a href="/gallery" onClick={(e) => {e.preventDefault();navigate('/gallery');onClose();}} style={mobileLink}>Gallery</a>
        <a href="/pricing" onClick={(e) => {e.preventDefault();navigate('/pricing');onClose();}} style={mobileLink}>Pricing</a>
        <div style={{ marginTop: 'auto', paddingTop: 32, display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Button variant="primary" size="large" arrow style={{ width: '100%', justifyContent: 'center' }}>Start free trial</Button>
          <Button variant="secondary" size="large" style={{ width: '100%', justifyContent: 'center' }}>Sign in</Button>
        </div>
      </nav>
    </div>);

}

const mobileLink = {
  display: 'block', padding: '18px 0',
  fontFamily: 'var(--font-display)', fontSize: 'clamp(24px, 6vw, 32px)', fontWeight: 400,
  letterSpacing: '-0.02em', color: 'var(--ink)',
  textDecoration: 'none', borderBottom: '1px solid var(--bone)'
};

function MobileAccordion({ title, open, onToggle, children }) {
  return (
    <div style={{ borderBottom: '1px solid var(--bone)' }}>
      <button onClick={onToggle} style={{
        width: '100%', padding: '18px 0',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: 'transparent', border: 'none', cursor: 'pointer', textAlign: 'left',
        fontFamily: 'var(--font-display)', fontSize: 'clamp(24px, 6vw, 32px)', fontWeight: 400,
        letterSpacing: '-0.02em', color: 'var(--ink)'
      }}>
        {title}
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" style={{ transform: open ? 'rotate(180deg)' : 'rotate(0)', transition: 'transform 200ms var(--ease-standard)' }}><polyline points="6 9 12 15 18 9" /></svg>
      </button>
      {open && <div style={{ paddingBottom: 16 }}>{children}</div>}
    </div>);

}

/* ------- TopNav main ------- */

function TopNav() {
  const { route } = useRoute();
  const navTweaks = useNavTweaks();
  const { theme } = useTheme();
  const logoSrc = theme === 'dark' ? 'assets/vizo-logo-white.png' : 'assets/vizo-logo-black.png';
  const [scrolled, setScrolled] = useStateTN(false);
  const [hidden, setHidden] = useStateTN(false);
  const [openMenu, setOpenMenu] = useStateTN(null); // 'platform' | 'solutions' | null
  const [mobileOpen, setMobileOpen] = useStateTN(false);
  const isMobile = useIsMobile(900);
  const closeTimer = useRefTN(null);
  const lastYRef = useRefTN(0);

  useEffectTN(() => {
    const onScroll = () => {
      const y = window.scrollY;
      const dy = y - lastYRef.current;
      // Always show at the very top.
      if (y <= 10) {
        setHidden(false);
        setScrolled(false);
        lastYRef.current = y;
        return;
      }
      // 10px scroll-direction threshold prevents flicker on micro-movements.
      if (Math.abs(dy) > 10) {
        setHidden(dy > 0);
        lastYRef.current = y;
      }
      setScrolled(true);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffectTN(() => {setOpenMenu(null);setMobileOpen(false);}, [route]);

  // Hero is on home; on inner pages we want the nav already styled solid.
  // Treat all routes the same so the home page nav reads like the other page headers from load.
  const solidNav = true;

  const openWith = (m) => {
    if (closeTimer.current) {clearTimeout(closeTimer.current);closeTimer.current = null;}
    setOpenMenu(m);
  };
  const queueClose = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setOpenMenu(null), 120);
  };

  const navHeight = isMobile ? 64 : 72;

  return (
    <>
      {/* Spacer keeps page content offset by the nav height since the bar is fixed. */}
      <div aria-hidden="true" style={{ height: navHeight }} />
      <nav aria-label="Primary" style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
        height: navHeight,
        background: solidNav ? 'var(--nav-bg-scrolled)' : 'transparent',
        backdropFilter: solidNav ? 'blur(12px)' : 'none',
        WebkitBackdropFilter: solidNav ? 'blur(12px)' : 'none',
        borderBottom: scrolled ? '1px solid var(--bone)' : '1px solid transparent',
        boxShadow: scrolled ? '0 1px 3px rgba(0,0,0,0.06)' : 'none',
        transform: hidden ? `translateY(-${navHeight}px)` : 'translateY(0)',
        transition: 'transform 300ms ease-in-out, border-color 300ms ease-in-out, box-shadow 300ms ease-in-out'
      }} onMouseLeave={queueClose}>
        <div style={{ height: '100%', padding: `0 var(--pad-x)` }}>
        <div style={{ height: '100%', maxWidth: 'var(--container)', margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          {/* Left: logo + primary links — gap controlled via Tweaks */}
          <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 0 : navTweaks.logoGap, height: '100%' }}>
            <Link to="/" style={{ display: 'flex', alignItems: 'center' }}>
              <img src={logoSrc} alt="ViZO" style={{ ...{ height: isMobile ? 18 : 22, objectFit: "fill", width: "6px" }, height: "32px", width: "75px" }} />
            </Link>
            {!isMobile &&
            <div style={{ display: 'flex', alignItems: 'center', gap: navTweaks.linkGap, height: '100%' }}>
                <div onMouseEnter={() => openWith(null)}><NavDirect to="/platform" label="Platform" active={route.startsWith('/platform')} /></div>
                <div onMouseEnter={() => openWith(null)}><NavDirect to="/solutions" label="Solutions" active={route.startsWith('/solutions')} /></div>
                <div onMouseEnter={() => openWith(null)}><NavDirect to="/gallery" label="Gallery" active={route.startsWith('/gallery')} /></div>
                <div onMouseEnter={() => openWith(null)}><NavDirect to="/pricing" label="Pricing" active={route.startsWith('/pricing')} /></div>
                {/* Theme toggle — 24px left of it, separated from Sign in by flex space */}
                <span style={{ marginLeft: 24 - navTweaks.linkGap, display: 'inline-flex' }} onMouseEnter={() => openWith(null)}>
                  <ThemeToggle />
                </span>
              </div>
            }
          </div>

          {/* Right: actions */}
          <div style={{ display: 'flex', gap: isMobile ? 8 : 12, alignItems: 'center' }} onMouseEnter={() => openWith(null)}>
            {isMobile ?
            <>
                <ThemeToggle />
                <Button variant="primary" size="small" arrow onClick={() => { window.location.href = 'https://app.vizostudio.ai'; }} style={{ whiteSpace: 'nowrap' }}>Login / Register</Button>
                <button aria-label="Open menu" onClick={() => setMobileOpen(true)} style={{
                width: 40, height: 40, borderRadius: 999,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                background: 'transparent', color: 'var(--ink)',
                border: '1px solid var(--mist)', cursor: 'pointer', padding: 0
              }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M3 6h18M3 12h18M3 18h18" /></svg>
                </button>
              </> :

            <> {/* Right cluster: Sign in + primary CTA */}
                <Link to="/contact"><Button variant="ghost" size="small">Contact Us</Button></Link>
                <Button variant="primary" size="small" arrow onClick={() => { window.location.href = 'https://app.vizostudio.ai'; }} style={{ whiteSpace: 'nowrap' }}>Login / Register</Button>
              </>
            }
        </div>
        </div>
        </div>

        {/* Mega-menus removed — nav items now route directly */}
      </nav>
      <MobileMenu open={mobileOpen} onClose={() => setMobileOpen(false)} />
      <style>{`
        @keyframes megaIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes slideIn { from { opacity: 0; transform: translateX(20px); } to { opacity: 1; transform: translateX(0); } }
      `}</style>
    </>);

}

window.TopNav = TopNav;