/* ============================================================
   Tectus — notification bar, mega-menu nav, mobile menu
   ============================================================ */
const { Button: TButton, Badge: TBadge, Eyebrow: TEyebrow } = window.TectusDesignSystem_c42b34;

/* ---------- Theme toggle (light / dark) ---------- */
function setTheme(t) {
  document.documentElement.setAttribute('data-theme', t);
  try { localStorage.setItem('tectus-theme', t); } catch (e) {}
  window.dispatchEvent(new CustomEvent('tectus-theme', { detail: t }));
}
function ThemeToggle() {
  const [theme, setLocal] = useState(() => document.documentElement.getAttribute('data-theme') || 'dark');
  const toggle = () => { const next = theme === 'light' ? 'dark' : 'light'; setLocal(next); setTheme(next); };
  const dark = theme !== 'light';
  return (
    <button type="button" onClick={toggle} aria-label={dark ? 'Switch to light mode' : 'Switch to dark mode'} title={dark ? 'Light mode' : 'Dark mode'}
      style={{ flex: '0 0 auto', width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--color-surface-2)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', color: 'var(--color-text-muted)', cursor: 'pointer', transition: 'color var(--dur-base), border-color var(--dur-base)' }}
      className="tt-theme-toggle">
      <Icon name={dark ? 'sun' : 'moon'} size={18} />
    </button>
  );
}
window.ThemeToggle = ThemeToggle;

/* ---------- Rotating notification bar ---------- */
function NotificationBar({ messages }) {
  const [i, setI] = useState(0);
  const intervalRef = useRef(null);
  const touchStartX = useRef(null);

  const startInterval = React.useCallback(() => {
    clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => setI((p) => (p + 1) % messages.length), 5200);
  }, [messages.length]);

  useEffect(() => { startInterval(); return () => clearInterval(intervalRef.current); }, [startInterval]);

  const goTo = (idx) => { setI(idx); startInterval(); };
  const goNext = () => goTo((i + 1) % messages.length);
  const goPrev = () => goTo((i - 1 + messages.length) % messages.length);

  const onTouchStart = (e) => { touchStartX.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchStartX.current === null) return;
    const dx = e.changedTouches[0].clientX - touchStartX.current;
    if (Math.abs(dx) > 40) { dx < 0 ? goNext() : goPrev(); }
    touchStartX.current = null;
  };

  const m = messages[i];
  return (
    <div style={{ background: 'var(--color-deep)', borderBottom: '1px solid var(--color-divider)', position: 'relative', zIndex: 60 }}
      onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
      <div className="wrap tt-notif-row" style={{ height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12, fontSize: 12.5 }}>
        <span style={{ color: 'var(--color-primary)', fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', fontSize: 10, padding: '3px 7px', border: '1px solid rgba(212,175,55,0.32)', borderRadius: 'var(--radius-pill)', lineHeight: 1, flex: '0 0 auto' }}>{m.tag}</span>
        <span key={i} className="tt-notif-text" style={{ color: 'var(--color-text-muted)', textAlign: 'center', animation: 'tt-fade .5s var(--ease-standard)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0 }}>{m.text}</span>
        <a href={m.href} style={{ color: 'var(--color-text)', display: 'inline-flex', alignItems: 'center', gap: 4, fontWeight: 600, flex: '0 0 auto', whiteSpace: 'nowrap' }} className="tt-notif-cta">{m.cta} <Icon name="arrow-right" size={13} /></a>
      </div>
      <div style={{ position: 'absolute', bottom: 0, left: '50%', transform: 'translateX(-50%)', display: 'flex', alignItems: 'flex-end', gap: 5, padding: '0 6px' }}>
        {messages.map((_, idx) => (
          <button key={idx} onClick={() => goTo(idx)} aria-label={`Go to message ${idx + 1}`}
            style={{ width: idx === i ? 16 : 5, height: 3, minHeight: 3, maxHeight: 3, borderRadius: 2, background: idx === i ? 'var(--color-primary)' : 'var(--color-border-strong)', transition: 'all var(--dur-base) var(--ease-standard)', border: 'none', cursor: 'pointer', padding: 0, outline: 'none', flexShrink: 0, display: 'block' }} />
        ))}
      </div>
    </div>
  );
}

/* ---------- Brand lockup ---------- */
function Brand({ size = 24 }) {
  const [theme, setLocal] = useState(() => document.documentElement.getAttribute('data-theme') || 'dark');
  useEffect(function() {
    function onTheme(e) { setLocal(e.detail); }
    window.addEventListener('tectus-theme', onTheme);
    return function() { window.removeEventListener('tectus-theme', onTheme); };
  }, []);
  const logoSrc = theme === 'light'
    ? asset('logoBlack', 'assets/tectus-logo-black.webp')
    : asset('logoWhite', 'assets/tectus-logo-white.webp');
  return (
    <a href="#/" aria-label="Tectus — home" style={{ display: 'flex', alignItems: 'center' }}>
      <img src={logoSrc} alt="Tectus" style={{ height: Math.round(size * 1.12), width: 'auto', display: 'block' }} />
    </a>
  );
}

/* ---------- Mega-menu panel ---------- */
function MegaPanel({ data, onNavigate }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 0.92fr', gap: 8, padding: 14 }}>
      {data.columns.map((col) => (
        <div key={col.heading} style={{ padding: '10px 8px' }}>
          <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--color-text-faint)', fontWeight: 700, marginBottom: 10, paddingLeft: 12 }}>{col.heading}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
            {col.links.map((lnk) => (
              <a key={lnk.label} href={lnk.href} onClick={onNavigate} className="tt-mega-link"
                 style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '10px 12px', borderRadius: 'var(--radius-md)' }}>
                <span className="tt-mega-ico" style={{ flex: '0 0 auto', width: 34, height: 34, borderRadius: 9, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--color-surface-3)', border: '1px solid var(--color-border)', color: 'var(--color-text-muted)' }}>
                  <Icon name={lnk.icon} size={16} />
                </span>
                <span style={{ minWidth: 0 }}>
                  <span style={{ display: 'block', fontSize: 14, fontWeight: 600, color: 'var(--color-text)', lineHeight: 1.3 }}>{lnk.label}</span>
                  <span style={{ display: 'block', fontSize: 12.5, color: 'var(--color-text-faint)', lineHeight: 1.35, marginTop: 2 }}>{lnk.desc}</span>
                </span>
              </a>
            ))}
          </div>
        </div>
      ))}
      {/* Feature card */}
      <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 18, padding: 22, margin: 6, borderRadius: 'var(--radius-lg)', background: 'linear-gradient(160deg, rgba(212,175,55,0.10), rgba(212,175,55,0.02) 60%), var(--color-surface-3)', border: '1px solid rgba(212,175,55,0.22)', position: 'relative', overflow: 'hidden' }} className="tt-mega-feature">
        <a href={data.feature.href} onClick={onNavigate} style={{ display: 'block' }}>
          <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--color-primary-light)', fontWeight: 700, marginBottom: 12 }}>{data.feature.eyebrow}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, letterSpacing: '-0.01em', marginBottom: 8, lineHeight: 1.2 }}>{data.feature.title}</div>
          <p style={{ fontSize: 13, color: 'var(--color-text-muted)', lineHeight: 1.55, margin: 0 }}>{data.feature.desc}</p>
        </a>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          <a href={data.feature.href} onClick={onNavigate} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, fontWeight: 600, color: data.feature.primary ? 'var(--color-on-primary)' : 'var(--color-text)', background: data.feature.primary ? 'var(--color-primary)' : 'transparent', border: data.feature.primary ? 'none' : '1px solid var(--color-border-strong)', padding: '8px 14px', borderRadius: 'var(--radius-md)' }}>
            {data.feature.cta} <Icon name="arrow-right" size={14} />
          </a>
          {data.feature.secondary && (
            <a href={data.feature.secondary.href} onClick={onNavigate} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, fontWeight: 600, color: 'var(--color-text)', border: '1px solid var(--color-border-strong)', padding: '8px 14px', borderRadius: 'var(--radius-md)' }}>{data.feature.secondary.label}</a>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- Desktop nav ---------- */
function Nav({ onOpenMobile }) {
  const [open, setOpen] = useState(null);
  const [scrolled, setScrolled] = useState(false);
  const closeTimer = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    const onKey = (e) => e.key === 'Escape' && setOpen(null);
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const openMenu = (g) => { clearTimeout(closeTimer.current); setOpen(g); };
  const scheduleClose = () => { clearTimeout(closeTimer.current); closeTimer.current = setTimeout(() => setOpen(null), 120); };

  const groups = Object.keys(SITEMAP);

  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 50 }} onMouseLeave={scheduleClose}>
      <div style={{ background: scrolled || open ? 'var(--color-nav-strong)' : 'var(--color-nav-soft)', backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)', borderBottom: '1px solid ' + (scrolled || open ? 'var(--color-border)' : 'transparent'), transition: 'background var(--dur-base) var(--ease-standard), border-color var(--dur-base) var(--ease-standard)' }}>
        <div className="wrap" style={{ height: 70, display: 'flex', alignItems: 'center', gap: 8 }}>
          <Brand />
          <nav className="tt-desktop-nav" style={{ display: 'flex', gap: 2, marginLeft: 26 }}>
            {groups.map((g) => (
              <a key={g} href={SITEMAP[g].href}
                onMouseEnter={() => openMenu(g)}
                onClick={() => setOpen(null)}
                className="tt-nav-trigger"
                style={{ display: 'inline-flex', alignItems: 'center', gap: 5, height: 36, padding: '0 13px', background: open === g ? 'var(--color-surface-2)' : 'transparent', border: 'none', borderRadius: 'var(--radius-md)', color: open === g ? 'var(--color-text)' : 'var(--color-text-muted)', font: 'inherit', fontSize: 14, fontWeight: 500, cursor: 'pointer', transition: 'color var(--dur-fast), background var(--dur-fast)' }}>
                {g}
                <Icon name="chevron-down" size={14} style={{ transform: open === g ? 'rotate(180deg)' : 'none', transition: 'transform var(--dur-base) var(--ease-standard)', opacity: 0.7 }} />
              </a>
            ))}
          </nav>
          <div className="tt-desktop-actions" style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 12 }}>
            <ThemeToggle />
            <a href="#/get-started"><TButton variant="secondary" size="sm">Get Started</TButton></a>
            <a href="#/demo"><TButton variant="primary" size="sm" iconRight={<Icon name="arrow-right" size={15} />}>Book a Demo</TButton></a>
          </div>
          <div className="tt-burger" style={{ marginLeft: 'auto', display: 'none', alignItems: 'center', gap: 10 }}>
            <ThemeToggle />
            <button type="button" onClick={onOpenMobile} aria-label="Open menu"
              style={{ width: 42, height: 42, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--color-surface-2)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', color: 'var(--color-text)', cursor: 'pointer' }}>
              <Icon name="menu" size={20} />
            </button>
          </div>
        </div>
      </div>

      {/* Mega panel */}
      <div style={{ position: 'absolute', top: 70, left: 0, right: 0, display: 'flex', justifyContent: 'center', pointerEvents: open ? 'auto' : 'none' }}>
        <div onMouseEnter={() => clearTimeout(closeTimer.current)} onMouseLeave={scheduleClose}
          style={{ width: 'min(960px, calc(100vw - 48px))', background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-xl)', boxShadow: 'var(--shadow-xl)', overflow: 'hidden',
            opacity: open ? 1 : 0, transform: open ? 'translateY(10px)' : 'translateY(0px)', transition: 'opacity var(--dur-base) var(--ease-standard), transform var(--dur-base) var(--ease-standard)' }}>
          {open && (
            <div>
              <div style={{ padding: '20px 24px 0', maxWidth: 560 }}>
                <p style={{ fontSize: 13.5, color: 'var(--color-text-faint)', lineHeight: 1.5, margin: 0 }}>{SITEMAP[open].intro}</p>
              </div>
              <MegaPanel data={SITEMAP[open]} onNavigate={() => setOpen(null)} />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- Mobile menu ---------- */
function MobileMenu({ open, onClose }) {
  const [expanded, setExpanded] = useState(null);
  const groups = Object.keys(SITEMAP);
  return (
    <div aria-hidden={!open} style={{ position: 'fixed', inset: 0, zIndex: 70, pointerEvents: open ? 'auto' : 'none' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.6)', opacity: open ? 1 : 0, transition: 'opacity var(--dur-base) var(--ease-standard)' }} />
      <div style={{ position: 'absolute', top: 0, right: 0, bottom: 0, width: 'min(420px, 92vw)', background: 'var(--color-bg)', borderLeft: '1px solid var(--color-border)', transform: open ? 'translateX(0)' : 'translateX(100%)', transition: 'transform var(--dur-slow) var(--ease-standard)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 20px', borderBottom: '1px solid var(--color-border)' }}>
          <Brand size={22} />
          <button type="button" onClick={onClose} aria-label="Close" style={{ width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--color-surface-2)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', color: 'var(--color-text)', cursor: 'pointer' }}><Icon name="x" size={20} /></button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '12px 14px' }}>
          {groups.map((g) => {
            const on = expanded === g;
            return (
              <div key={g} style={{ borderBottom: '1px solid var(--color-divider)' }}>
                <div style={{ display: 'flex', alignItems: 'stretch' }}>
                  <a href={SITEMAP[g].href} onClick={onClose} style={{ flex: 1, display: 'flex', alignItems: 'center', padding: '15px 10px', color: 'var(--color-text)', font: 'inherit', fontSize: 16, fontWeight: 600, minHeight: 52 }}>
                    {g}
                  </a>
                  <button type="button" onClick={() => setExpanded(on ? null : g)} aria-label={on ? 'Collapse ' + g : 'Expand ' + g} aria-expanded={on} style={{ flex: '0 0 auto', width: 52, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'transparent', border: 'none', borderLeft: '1px solid var(--color-divider)', color: 'var(--color-text-faint)', cursor: 'pointer' }}>
                    <Icon name="chevron-down" size={20} style={{ transform: on ? 'rotate(180deg)' : 'none', transition: 'transform var(--dur-base)' }} />
                  </button>
                </div>
                <div style={{ maxHeight: on ? 600 : 0, overflow: 'hidden', transition: 'max-height var(--dur-slow) var(--ease-standard)' }}>
                  <div style={{ padding: '0 10px 12px', display: 'flex', flexDirection: 'column', gap: 2 }}>
                    {SITEMAP[g].columns.flatMap((c) => c.links).map((lnk) => (
                      <a key={lnk.label} href={lnk.href} onClick={onClose} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 10px', borderRadius: 'var(--radius-md)', color: 'var(--color-text-muted)', fontSize: 14, minHeight: 44 }}>
                        <Icon name={lnk.icon} size={16} style={{ color: 'var(--color-text-faint)' }} />{lnk.label}
                      </a>
                    ))}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ padding: 18, borderTop: '1px solid var(--color-border)', display: 'flex', flexDirection: 'column', gap: 10 }}>
          <a href="#/demo" onClick={onClose}><TButton variant="primary" size="md" block iconRight={<Icon name="arrow-right" size={16} />}>Book a Demo</TButton></a>
          <a href="#/get-started" onClick={onClose}><TButton variant="secondary" size="md" block>Get Started</TButton></a>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { NotificationBar, Nav, MobileMenu, Brand });
