// Shared site chrome — Navbar + Footer.
// Every page mounts <SiteNav active="..."> and <SiteFooter />.

function OctodusLogo({ size = 32, glow = false }) {
  return (
    <span
      style={{
        display: 'inline-flex',
        width: size, height: size,
        color: 'var(--accent-light)',
        filter: glow ? 'drop-shadow(0 0 10px var(--accent-tint-45))' : 'none',
      }}
    >
      {Icons.mark({ width: size, height: size })}
    </span>
  );
}

const SITE_NAV = [
  { id: 'home',         label: 'Home',         href: '/' },
  { id: 'capabilities', label: 'Capabilities', href: 'Capabilities.html' },
  { id: 'integrations', label: 'Integrations', href: 'Integrations.html' },
  { id: 'stories',      label: 'Stories',      href: 'Stories.html' },
  { id: 'pricing',      label: 'Pricing',      href: 'Pricing.html' },
  { id: 'blog',         label: 'Blog',         href: 'Blog.html' },
];

function SiteNav({ active = 'home' }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);

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

  return (
    <nav className={`site-nav ${scrolled ? 'scrolled' : ''}`}>
      <a className="site-nav-brand" href="/">
        <OctodusLogo size={26} />
        <span className="site-nav-word">octodus</span>
      </a>

      <div className="site-nav-links">
        {SITE_NAV.map((item) => (
          <a
            key={item.id}
            href={item.href}
            className={`site-nav-link ${item.id === active ? 'on' : ''}`}
          >
            {item.label}
          </a>
        ))}
      </div>

      <div className="site-nav-cta-wrap">
        <a className="btn btn-primary site-nav-cta" href="https://calend.ly/emdx" target="_blank" rel="noopener">
          {Icons.telegram({ width: 16, height: 16 })} Hire octodus
        </a>
      </div>

      <button
        className="site-nav-burger"
        aria-label="Open menu"
        aria-expanded={open}
        onClick={() => setOpen((v) => !v)}
      >
        <span /><span /><span />
      </button>

      {open && (
        <div className="site-nav-mobile" onClick={() => setOpen(false)}>
          <div className="site-nav-mobile-inner" onClick={(e) => e.stopPropagation()}>
            {SITE_NAV.map((item) => (
              <a
                key={item.id}
                href={item.href}
                className={`site-nav-mobile-link ${item.id === active ? 'on' : ''}`}
              >
                {item.label}
              </a>
            ))}
            <a className="btn btn-primary" href="https://calend.ly/emdx" target="_blank" rel="noopener">
              {Icons.telegram({ width: 16, height: 16 })} Hire octodus
            </a>
          </div>
        </div>
      )}

      <style>{`
        .site-nav {
          position: sticky;
          top: 16px;
          z-index: 50;
          display: flex;
          align-items: center;
          gap: 24px;
          padding: 12px 14px 12px 22px;
          margin: 16px auto 0;
          max-width: 1280px;
          background: rgba(235, 227, 210, 0.65);
          backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
          border: 1px solid var(--border);
          border-radius: 999px;
          box-shadow: 0 8px 30px -10px rgba(58, 49, 32, 0.14);
          transition: background 200ms var(--ease-out), border-color 200ms var(--ease-out);
        }
        .site-nav.scrolled {
          background: rgba(235, 227, 210, 0.95);
          border-color: var(--border-light);
        }
        .site-nav-brand {
          display: inline-flex;
          align-items: center;
          gap: 10px;
          color: var(--text);
          flex-shrink: 0;
        }
        .site-nav-word {
          font-family: var(--font-heading);
          font-weight: 700;
          font-size: 18px;
          letter-spacing: -0.03em;
        }
        .site-nav-links {
          display: flex;
          align-items: center;
          gap: 4px;
          flex: 1;
          justify-content: center;
        }
        .site-nav-link {
          font-size: 14px;
          color: var(--text-secondary);
          padding: 8px 14px;
          border-radius: 999px;
          transition: color 180ms var(--ease-out), background 180ms var(--ease-out);
          position: relative;
        }
        .site-nav-link:hover { color: var(--text); }
        .site-nav-link.on {
          color: var(--text);
          background: var(--accent-tint-10);
        }
        .site-nav-cta-wrap { flex-shrink: 0; }
        .site-nav-cta { height: 40px; padding: 0 16px; font-size: 13.5px; }

        .site-nav-burger {
          display: none;
          width: 40px; height: 40px;
          border-radius: 50%;
          background: transparent;
          border: 1px solid var(--border-light);
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: 4px;
        }
        .site-nav-burger span {
          width: 16px; height: 1.5px;
          background: var(--text);
          border-radius: 1px;
        }

        @media (max-width: 960px) {
          .site-nav {
            gap: 12px;
            padding: 10px 12px 10px 18px;
            margin: 12px 12px 0;
          }
          .site-nav-links { display: none; }
          .site-nav-cta { display: none; }
          .site-nav-burger { display: flex; }
        }

        .site-nav-mobile {
          position: fixed;
          inset: 0;
          background: rgba(235, 227, 210, 0.95);
          backdrop-filter: blur(12px);
          z-index: 100;
          padding: 80px 20px 20px;
        }
        .site-nav-mobile-inner {
          background: var(--bg-card);
          border: 1px solid var(--border);
          border-radius: 20px;
          padding: 20px;
          display: flex;
          flex-direction: column;
          gap: 4px;
        }
        .site-nav-mobile-link {
          padding: 14px 16px;
          border-radius: 12px;
          font-size: 16px;
          color: var(--text-secondary);
        }
        .site-nav-mobile-link.on {
          color: var(--text);
          background: var(--accent-tint-12);
        }
        .site-nav-mobile .btn { margin-top: 12px; justify-content: center; }
      `}</style>
    </nav>
  );
}

function SiteFooter() {
  return (
    <footer className="site-foot">
      <div className="container">
        <div className="site-foot-top">
          <div className="site-foot-brand">
            <OctodusLogo size={36} />
            <div>
              <div className="site-foot-word">octodus</div>
              <div className="site-foot-tagline">The AI coworker that lives in your chat.</div>
            </div>
          </div>

          <div className="site-foot-cols">
            <div className="site-foot-col">
              <div className="site-foot-col-head">Product</div>
              <a href="Capabilities.html">Capabilities</a>
              <a href="Integrations.html">Integrations</a>
              <a href="Pricing.html">Pricing</a>
              <a href="Stories.html">Stories</a>
              <a href="/#chat">Live demo</a>
            </div>
            <div className="site-foot-col">
              <div className="site-foot-col-head">For your role</div>
              <a href="for-creators.html">Solo creators</a>
              <a href="for-agencies.html">Agencies</a>
              <a href="for-engineers.html">Engineers</a>
              <a href="for-ops.html">Ops &amp; programs</a>
            </div>
            <div className="site-foot-col">
              <div className="site-foot-col-head">Resources</div>
              <a href="Blog.html">Blog</a>
              <a href="/#faq">FAQ</a>
              <a href="https://t.me/octodusdev" target="_blank" rel="noopener">Changelog</a>
              <a href="Capabilities.html#compare">Compare</a>
            </div>
            <div className="site-foot-col">
              <div className="site-foot-col-head">Company</div>
              <a href="https://t.me/octodusdev" target="_blank" rel="noopener">Telegram channel</a>
              <a href="https://calend.ly/emdx" target="_blank" rel="noopener">Schedule a call</a>
              <a href="#">Privacy</a>
              <a href="#">Terms</a>
            </div>
          </div>
        </div>

        <div className="site-foot-rule" />

        <div className="site-foot-bottom">
          <div>© 2026 · octodus.com</div>
          <div className="site-foot-bottom-meta">
            <span>EN · DE · FR</span>
            <span className="site-foot-dot">·</span>
            <span>Made in chat</span>
          </div>
        </div>
      </div>

      <style>{`
        .site-foot {
          padding: 80px 0 40px;
          border-top: 1px solid var(--border);
          background: linear-gradient(180deg, transparent, var(--bg-deep));
        }
        .site-foot-top {
          display: grid;
          grid-template-columns: 1fr 2fr;
          gap: 64px;
          padding-bottom: 64px;
          border-bottom: 1px solid var(--border);
        }
        @media (max-width: 720px) { .site-foot-top { grid-template-columns: 1fr; gap: 40px; } }

        .site-foot-brand { display: flex; gap: 14px; align-items: center; }
        .site-foot-word {
          font-family: var(--font-heading);
          font-size: 28px;
          font-weight: 700;
          letter-spacing: -0.03em;
          line-height: 1;
        }
        .site-foot-tagline {
          font-size: 13px;
          color: var(--text-muted);
          margin-top: 4px;
        }

        .site-foot-cols {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 24px;
        }
        @media (max-width: 720px) { .site-foot-cols { grid-template-columns: 1fr 1fr; } }
        @media (max-width: 420px) { .site-foot-cols { grid-template-columns: 1fr; } }
        .site-foot-col { display: flex; flex-direction: column; gap: 10px; }
        .site-foot-col-head {
          font-family: var(--font-mono);
          font-size: 11px;
          letter-spacing: 0.15em;
          text-transform: uppercase;
          color: var(--text-muted);
          margin-bottom: 8px;
        }
        .site-foot-col a {
          font-size: 14px;
          color: var(--text-secondary);
          transition: color 180ms var(--ease-out);
        }
        .site-foot-col a:hover { color: var(--accent-light); }

        .site-foot-rule {
          margin: 32px 0;
          height: 1px;
          background: var(--border);
        }

        .site-foot-bottom {
          display: flex; justify-content: space-between; align-items: center;
          font-family: var(--font-mono);
          font-size: 12px;
          color: var(--text-muted);
          letter-spacing: 0.05em;
          flex-wrap: wrap; gap: 12px;
        }
        .site-foot-bottom-meta { display: flex; gap: 10px; }
        .site-foot-dot { opacity: 0.5; }
      `}</style>
    </footer>
  );
}

// ── Shared final CTA used across every sub-page ──
function FinalCTA({ heading, sub, ctaLabel = 'Hire octodus', secondary }) {
  return (
    <section className="final-cta">
      <div className="container">
        <div className="final-cta-wrap">
          <div className="final-cta-mark" aria-hidden="true">
            {Icons.mark({ width: 420, height: 420 })}
          </div>
          <div className="final-cta-glow" />

          <div className="final-cta-copy">
            <div className="eyebrow">Add octodus to your chat</div>
            <h2 className="final-cta-title">
              {heading || (<>Send your first message.<br/><em>Watch what happens.</em></>)}
            </h2>
            <p className="final-cta-sub">
              {sub || '$15 of credits to start. No credit card. No setup call. Credits never expire. Paste a message into Telegram and let Octodus get to work.'}
            </p>

            <div className="final-cta-ctas">
              <a className="btn btn-primary" href="https://calend.ly/emdx" target="_blank" rel="noopener">
                {Icons.telegram({ width: 18, height: 18 })} {ctaLabel} {Icons.arrow({ width: 16, height: 16 })}
              </a>
              {secondary !== false && (
                <a className="btn btn-ghost" href="Stories.html">Read field stories</a>
              )}
            </div>

            <div className="final-cta-meta">
              <span>EN · DE · FR</span>
              <span>·</span>
              <span>Telegram today · Slack &amp; Discord soon</span>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .final-cta {
          padding: 140px 0 80px;
          position: relative;
          overflow: hidden;
        }
        .final-cta::before {
          content: "";
          position: absolute;
          inset: -2px 0 0 0;
          border-top: 1px solid var(--border);
        }
        .final-cta-wrap {
          position: relative;
          padding: 88px 64px;
          border-radius: 32px;
          background:
            radial-gradient(ellipse 70% 80% at 100% 20%, var(--accent-soft), transparent 60%),
            linear-gradient(180deg, var(--bg-card) 0%, var(--bg-elev) 100%);
          border: 1px solid var(--border);
          overflow: hidden;
          text-align: center;
        }
        @media (max-width: 920px) {
          .final-cta-wrap { padding: 56px 28px; }
        }
        .final-cta-mark {
          position: absolute;
          right: -80px; top: 50%;
          transform: translateY(-50%);
          color: var(--accent);
          opacity: 0.07;
          pointer-events: none;
        }
        .final-cta-glow {
          position: absolute;
          width: 600px; height: 600px;
          border-radius: 50%;
          right: -120px; top: -120px;
          background: radial-gradient(circle, var(--accent-soft) 0%, transparent 70%);
          filter: blur(60px);
          pointer-events: none;
        }
        .final-cta-copy {
          position: relative;
          z-index: 1;
          max-width: 720px;
          margin: 0 auto;
        }
        .final-cta-title {
          font-size: clamp(2.6rem, 5vw, 4.2rem);
          line-height: 1.0;
          letter-spacing: -0.045em;
          margin: 14px 0 22px;
        }
        .final-cta-title em {
          font-style: normal;
          background: linear-gradient(120deg, var(--accent-light), var(--accent));
          -webkit-background-clip: text; background-clip: text; color: transparent;
          text-shadow: 0 0 60px var(--accent-tint-30);
        }
        .final-cta-sub {
          font-size: 17px;
          color: var(--text-secondary);
          line-height: 1.6;
          max-width: 500px;
          margin: 0 auto;
        }
        .final-cta-ctas { margin-top: 32px; display: flex; gap: 12px; flex-wrap: wrap; justify-content: center; }
        .final-cta-ctas .btn { height: 54px; padding: 0 24px; font-size: 16px; }
        .final-cta-meta { margin-top: 24px; display: flex; gap: 10px; font-family: var(--font-mono); font-size: 12px; color: var(--text-muted); letter-spacing: 0.05em; flex-wrap: wrap; justify-content: center; }
      `}</style>
    </section>
  );
}

// ── Shared accent-palette tweak (mounted on every page) ──
// Mono-light sub-variants. All keep the cream-paper substrate; only the
// pop changes.
const ACCENT_PALETTES = [
  ['#C9501A', '#E0571E', '#7A2C0A'], // Terracotta (default)
  ['#6B7A1C', '#8A9938', '#3E4711'], // Olive
  ['#1A3E66', '#2C5A99', '#0E2440'], // Ink Blue
  ['#161311', '#3D3934', '#06040E'], // Pure ink (no pop)
];

function useAccentTweaks() {
  const defaults = (typeof window !== 'undefined' && window.__OCTODUS_TWEAKS) || {
    accent: ACCENT_PALETTES[0],
  };
  const [tweaks, setTweak] = useTweaks(defaults);

  React.useEffect(() => {
    const palette = Array.isArray(tweaks.accent) ? tweaks.accent : ACCENT_PALETTES[0];
    const [primary, light, deep] = palette;
    const root = document.documentElement.style;
    root.setProperty('--accent', primary);
    root.setProperty('--accent-light', light);
    root.setProperty('--accent-deep', deep);
    const hex = primary.replace('#', '');
    const r = parseInt(hex.slice(0, 2), 16);
    const g = parseInt(hex.slice(2, 4), 16);
    const b = parseInt(hex.slice(4, 6), 16);
    root.setProperty('--accent-soft', `rgba(${r}, ${g}, ${b}, 0.12)`);
  }, [tweaks.accent]);

  return [tweaks, setTweak];
}

function SiteTweaks({ children }) {
  const [tweaks, setTweak] = useAccentTweaks();
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Accent">
        <TweakColor
          label="Brand palette"
          value={tweaks.accent}
          onChange={(v) => setTweak('accent', v)}
          options={ACCENT_PALETTES}
        />
      </TweakSection>
      {children}
    </TweaksPanel>
  );
}

// ── Scroll-reveal: toggles `revealed` class on [data-reveal] elements
//    as they intersect the viewport. Also auto-tags common card selectors
//    so I don't have to sprinkle attributes everywhere. ──
const AUTO_REVEAL_SELECTORS = [
  // Cards & grids
  '.skill-card', '.st-card', '.story', '.stt',
  '.plan', '.int-card', '.featured-cell',
  '.post', '.bf', '.spotlight',
  '.compare-card', '.role-bullet',
  '.cmp-group', '.faq-item',
  '.how-card', '.powered-pill', '.powered-feat',
  '.rule',
  // Section heads
  '.page-hero-body', '.skills-head', '.stories-head',
  '.chat-section-head', '.cmp-head', '.faq-head',
  '.compare-head', '.roles-head',
];

function useScrollReveal() {
  React.useEffect(() => {
    if (typeof window === 'undefined') return;
    const reduceMotion = window.matchMedia &&
      window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    // Auto-tag matching elements
    const autoTag = () => {
      AUTO_REVEAL_SELECTORS.forEach((sel) => {
        document.querySelectorAll(sel).forEach((el) => {
          if (!el.hasAttribute('data-reveal')) el.setAttribute('data-reveal', '');
        });
      });
    };

    if (reduceMotion) {
      autoTag();
      document.querySelectorAll('[data-reveal]').forEach((el) => el.classList.add('revealed'));
      return;
    }

    // Scroll-based reveal — works in sandboxed iframes where IntersectionObserver
    // doesn't fire its initial callback.
    const REVEAL_OFFSET = 80; // px below viewport edge before we count as "near"
    let ticking = false;

    const scan = () => {
      ticking = false;
      const vh = window.innerHeight;
      const pending = document.querySelectorAll('[data-reveal]:not(.revealed)');
      pending.forEach((el) => {
        const rect = el.getBoundingClientRect();
        if (rect.top < vh - REVEAL_OFFSET && rect.bottom > 0) {
          el.classList.add('revealed');
        }
      });
    };

    const onScroll = () => {
      if (!ticking) {
        ticking = true;
        requestAnimationFrame(scan);
      }
    };

    // Initial pass + observe later-mounted nodes
    autoTag();
    // Multiple staggered scans to catch slow-mounting React subtrees
    // (Babel-in-browser pages mount progressively).
    requestAnimationFrame(scan);
    setTimeout(scan, 100);
    setTimeout(scan, 400);
    setTimeout(scan, 1000);
    setTimeout(scan, 2000);

    window.addEventListener('scroll', onScroll, { passive: true });
    document.addEventListener('scroll', onScroll, { passive: true, capture: true });
    window.addEventListener('resize', onScroll);

    // Belt-and-suspenders: keep scanning every 300ms for the first 5 seconds
    // after mount so progressively-rendered React subtrees never get stuck.
    const interval = setInterval(scan, 300);
    setTimeout(() => clearInterval(interval), 5000);

    const mo = new MutationObserver(() => {
      autoTag();
      requestAnimationFrame(scan);
    });
    mo.observe(document.body, { subtree: true, childList: true });

    return () => {
      window.removeEventListener('scroll', onScroll);
      document.removeEventListener('scroll', onScroll, { capture: true });
      window.removeEventListener('resize', onScroll);
      clearInterval(interval);
      mo.disconnect();
    };
  }, []);
}

// Drop-in wrapper that activates reveal + accent tweaks on any page
function SiteEffects() {
  useScrollReveal();
  return null;
}

Object.assign(window, { SiteNav, SiteFooter, FinalCTA, OctodusLogo, SiteTweaks, SiteEffects, useScrollReveal, ACCENT_PALETTES, useAccentTweaks });
