const { motion, useInView, useScroll, useTransform } = window.Motion || window.framerMotion || {};
// fallback: framer-motion exposes on window as `window.Motion`
const FM = window.Motion || {};

// ====== NAVBAR ======
const Navbar = () => {
  const tw = useTweaks();
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <nav className={`fixed top-0 left-0 right-0 z-50 px-6 md:px-10 py-5 flex items-center justify-between transition-colors duration-300 ${scrolled ? 'bg-black/60 backdrop-blur-md' : ''}`}>
      <a href="#top" className="flex items-center gap-2 text-xl font-semibold tracking-tight font-body">
        <img src="assets/logo.png" alt="" className="w-6 h-6 object-contain" draggable="false" />
        187N<span className="text-muted-foreground">.AI</span>
      </a>

      <div className="hidden md:flex items-center gap-1 liquid-glass rounded-full px-2 py-1.5">
        {['Security', 'Proces', 'Pricing', 'Team', 'FAQ'].map(link => (
          <a key={link}
             href={`#${link.toLowerCase()}`}
             className="nav-link px-4 py-2 text-sm font-medium text-foreground/90 hover:text-white rounded-full transition-colors">
            {link}
          </a>
        ))}
      </div>

      <div className="flex items-center gap-3">
        <div className="hidden sm:flex items-center gap-2 text-[11px] font-mono tracking-widest uppercase text-muted-foreground">
          <span className="text-white">NL</span>
          <span className="opacity-40">·</span>
          <a href="en/" className="hover:text-white transition-colors">EN</a>
        </div>
        <a href={tw.ctaHref} target="_blank" rel="noopener noreferrer" className="liquid-glass-strong rounded-full px-5 py-2.5 text-sm font-medium text-foreground btn-hover inline-flex items-center">
          {tw.ctaLabel}
        </a>
      </div>
    </nav>
  );
};

// ====== HERO ======
const Hero = () => {
  const t = useTweaks();
  return (
    <section id="top" className="relative w-full min-h-screen overflow-hidden flex flex-col hero-bg">
      {/* Background video */}
      <video
        autoPlay
        muted
        loop
        playsInline
        className="absolute inset-0 w-full h-full object-cover object-top z-0"
        style={{ opacity: t.heroVideoOpacity / 100 }}
        src="https://d8j0ntlcm91z4.cloudfront.net/user_38xzZboKViGWJOttwIXH07lWA1P/hf_20260411_104032_69319010-2458-492b-b04d-b40a5dfa4482.mp4"
      />
      <div className="absolute inset-0 bg-gradient-to-b from-black/20 via-black/10 to-black/75 z-0 pointer-events-none"></div>
      <div className="absolute inset-0 z-0 pointer-events-none" style={{ background: `rgba(0,0,0,${t.heroOverlayDarkness / 100})` }}></div>
      <div className="absolute inset-0 grid-overlay pointer-events-none z-0"></div>

      <div className="absolute top-1/3 left-1/4 w-[400px] h-[400px] rounded-full bg-white/5 blur-[120px] pointer-events-none z-0"></div>
      <div className="absolute bottom-1/4 right-1/4 w-[300px] h-[300px] rounded-full bg-white/4 blur-[120px] pointer-events-none z-0"></div>

      <div className="relative z-10 w-full text-center pt-24 md:pt-28">
        <div className="text-[11px] tracking-[0.32em] text-muted-foreground uppercase font-mono">
          {t.heroEyebrow}
        </div>
      </div>

      <div className="relative z-10 flex-1 flex flex-col items-center justify-end text-center max-w-5xl mx-auto px-6 pb-14">
        <InfinityLoop className="w-32 h-32 md:w-44 md:h-44 mb-10 hidden" interactive={true} />

        <h1 className="mt-[32vh] text-4xl sm:text-5xl md:text-6xl lg:text-7xl font-medium tracking-[-1px] md:tracking-[-2.5px] leading-[1.02] max-w-4xl">
          {t.heroTitlePre}
          <span className="font-accent italic font-normal" style={{ color: t.accentColor }}>{t.heroTitleAccent}</span>
          {t.heroTitlePost}
        </h1>

        <p className="text-base md:text-lg text-muted-foreground max-w-2xl mt-7 leading-relaxed">
          {t.heroSub}
        </p>

        <div className="mt-10 flex flex-col sm:flex-row gap-3 sm:gap-4">
          <a href={t.ctaHref} target="_blank" rel="noopener noreferrer" className="bg-foreground text-background rounded-full px-8 py-3.5 text-sm font-medium btn-hover inline-flex items-center justify-center">
            {t.ctaLabel} →
          </a>
          <button className="liquid-glass-strong rounded-full px-8 py-3.5 text-sm font-medium btn-hover">
            Meer Weten
          </button>
        </div>

        <div className="mt-20 flex flex-wrap justify-center gap-x-12 md:gap-x-20 gap-y-6">
          {[
            { v: '10–20u', l: 'Bespaard per week' },
            { v: '24/7', l: 'Autonome ops' },
            { v: '30 Dagen', l: 'Nazorg inbegrepen' },
          ].map((m) => (
            <div key={m.l} className="flex flex-col items-center">
              <div className="font-accent italic text-4xl md:text-5xl text-white leading-none">{m.v}</div>
              <div className="text-[10px] tracking-[0.28em] uppercase text-muted-foreground mt-2 font-mono">{m.l}</div>
            </div>
          ))}
        </div>

        <div className="mt-14 flex items-center gap-8 opacity-50 text-xs font-mono tracking-widest uppercase">
          <span>built with</span>
          {['Claude', 'OpenClaw', 'Codex', 'Telegram'].map(b => (
            <span key={b} className="flex items-center gap-2">
              <span className="w-1.5 h-1.5 bg-white rounded-full"></span>
              {b}
            </span>
          ))}
        </div>
      </div>

      {/* Bottom fade */}
      <div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-t from-background to-transparent pointer-events-none z-20"></div>
    </section>
  );
};

// ====== COMMAND CENTER ======
const CommandCenter = () => {
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    const o = new IntersectionObserver(([e]) => e.isIntersecting && setInView(true), { threshold: 0.15 });
    if (ref.current) o.observe(ref.current);
    return () => o.disconnect();
  }, []);

  const stats = [
    { label: 'Agents', value: '12' },
    { label: 'Skills', value: '1.152' },
    { label: 'Cron Jobs', value: '8' },
    { label: 'Uptime', value: '14d 6u' },
    { label: 'Bridge', value: 'OK', ok: true },
  ];

  const agents = [
    { name: 'Research Agent', status: 'ACTIVE', color: 'text-emerald-300', tasks: 47 },
    { name: 'Ad Manager', status: 'ACTIVE', color: 'text-emerald-300', tasks: 12 },
    { name: 'Content Agent', status: 'RUNNING', color: 'text-sky-300', tasks: 3 },
    { name: 'Support Bot', status: 'IDLE', color: 'text-white/50', tasks: 0 },
    { name: 'Finance Agent', status: 'IDLE', color: 'text-white/50', tasks: 0 },
  ];

  const activity = [
    { t: 'just now', a: 'Research Agent', msg: 'completed competitor analysis — 14 threats flagged' },
    { t: '2m ago', a: 'Ad Manager', msg: 'paused 3 campaigns below ROAS threshold' },
    { t: '5m ago', a: 'Content Agent', msg: 'generated 6 draft posts for review' },
    { t: '12m ago', a: 'Bridge', msg: 'synced 142 events from Telegram integration' },
    { t: '28m ago', a: 'Finance Agent', msg: 'reconciled 89 transactions from Stripe' },
    { t: '1h ago', a: 'Research Agent', msg: 'mapped TAM for Q2 expansion scenario' },
    { t: '2h ago', a: 'Cron', msg: 'nightly skill vetting — 0 anomalies' },
  ];

  return (
    <section className="relative py-32 px-6 md:px-8 max-w-6xl mx-auto z-10">
      <div className="text-[11px] tracking-[0.32em] text-muted-foreground uppercase mb-6 text-center font-mono">
        Command Center
      </div>
      <h2 className="text-4xl md:text-5xl lg:text-6xl font-medium tracking-[-2px] text-center mb-4 leading-[1.05]">
        Jouw Enterprise <span className="font-accent italic font-normal">Command Center</span>.
      </h2>
      <p className="text-muted-foreground text-lg text-center max-w-2xl mx-auto mb-16">
        Volledig zicht. Totale controle. Één dashboard om je complete AI operations layer te deployen, monitoren en schalen.
      </p>

      <div ref={ref} className={`liquid-glass-strong rounded-2xl p-5 md:p-6 fade-up dashboard-fade-bottom ${inView ? 'is-in' : ''}`}>
        {/* top chrome */}
        <div className="flex items-center justify-between pb-5 border-b border-white/5 mb-5">
          <div className="flex items-center gap-2">
            <span className="w-2.5 h-2.5 rounded-full bg-white/20"></span>
            <span className="w-2.5 h-2.5 rounded-full bg-white/20"></span>
            <span className="w-2.5 h-2.5 rounded-full bg-white/20"></span>
            <span className="ml-3 font-mono text-[11px] text-muted-foreground">187n.ai / ops / dashboard</span>
          </div>
          <div className="flex items-center gap-2 font-mono text-[11px] text-muted-foreground">
            <span className="op-dot pulse-dot"></span>
            <span>all systems operational</span>
          </div>
        </div>

        {/* stats row */}
        <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-5">
          {stats.map(s => (
            <div key={s.label} className="liquid-glass rounded-xl p-3 md:p-4">
              <div className="text-[10px] tracking-[0.25em] uppercase text-muted-foreground font-mono">{s.label}</div>
              <div className={`font-accent italic text-2xl md:text-3xl mt-1 ${s.ok ? 'text-emerald-300' : ''}`}>{s.value}</div>
            </div>
          ))}
        </div>

        {/* body */}
        <div className="grid grid-cols-12 gap-4">
          {/* sidebar */}
          <aside className="hidden md:block col-span-2 liquid-glass rounded-xl p-3">
            <div className="text-[10px] tracking-[0.25em] uppercase text-muted-foreground font-mono mb-3 px-2">Menu</div>
            {['Dashboard', 'Agents', 'Integraties', 'Taken', 'Skills', 'Logs', 'Settings'].map((t, i) => (
              <div key={t}
                className={`px-3 py-2 rounded-md text-sm mb-0.5 flex items-center justify-between ${i === 0 ? 'bg-white/10 text-white' : 'text-muted-foreground hover:text-white'}`}>
                <span>{t}</span>
                {i === 1 && <span className="text-[10px] font-mono bg-white/10 px-1.5 rounded">12</span>}
              </div>
            ))}
          </aside>

          {/* agents list */}
          <div className="col-span-12 md:col-span-6 liquid-glass rounded-xl p-4">
            <div className="flex items-center justify-between mb-4">
              <div className="text-sm font-medium">Active Agents</div>
              <div className="text-[10px] font-mono text-muted-foreground">REFRESH · 2s</div>
            </div>
            <div className="space-y-2">
              {agents.map(a => (
                <div key={a.name} className="flex items-center justify-between py-2.5 px-3 rounded-lg hover:bg-white/[0.03]">
                  <div className="flex items-center gap-3">
                    <div className="w-8 h-8 rounded-md bg-white/[0.06] flex items-center justify-center text-xs font-mono">
                      {a.name.split(' ').map(x => x[0]).join('').slice(0, 2)}
                    </div>
                    <div>
                      <div className="text-sm font-medium">{a.name}</div>
                      <div className="text-[11px] text-muted-foreground font-mono">{a.tasks} taken vandaag</div>
                    </div>
                  </div>
                  <div className={`flex items-center gap-2 text-[11px] font-mono tracking-wider ${a.color}`}>
                    <span className={`w-1.5 h-1.5 rounded-full ${a.status === 'IDLE' ? 'bg-white/30' : 'bg-current'} ${a.status !== 'IDLE' ? 'pulse-dot' : ''}`}></span>
                    {a.status}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* activity feed */}
          <div className="col-span-12 md:col-span-4 liquid-glass rounded-xl p-4 overflow-hidden">
            <div className="flex items-center justify-between mb-4">
              <div className="text-sm font-medium">Activity</div>
              <div className="op-dot pulse-dot"></div>
            </div>
            <div className="relative h-72 overflow-hidden">
              <div className="activity-scroll space-y-3">
                {[...activity, ...activity].map((e, i) => (
                  <div key={i} className="text-xs border-l border-white/10 pl-3">
                    <div className="text-muted-foreground font-mono text-[10px] mb-0.5">{e.t}</div>
                    <div className="leading-snug">
                      <span className="font-medium">{e.a}</span>{' '}
                      <span className="text-muted-foreground">{e.msg}</span>
                    </div>
                  </div>
                ))}
              </div>
              <div className="absolute top-0 left-0 right-0 h-10 bg-gradient-to-b from-[#0a0a0a] to-transparent pointer-events-none"></div>
              <div className="absolute bottom-0 left-0 right-0 h-10 bg-gradient-to-t from-[#0a0a0a] to-transparent pointer-events-none"></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ====== HLS HERO VIDEO BREAK ======
const HlsVideoBreak = () => {
  const vref = React.useRef(null);
  const src = 'https://stream.mux.com/01yW6GoUz01OTXk5w1Rt1MHkJWlCGIwj46SUONJZ4DJUE.m3u8';

  React.useEffect(() => {
    const video = vref.current;
    if (!video) return;
    if (video.canPlayType('application/vnd.apple.mpegurl')) {
      video.src = src;
    } else if (window.Hls && window.Hls.isSupported()) {
      const hls = new window.Hls({ enableWorker: true, lowLatencyMode: false });
      hls.loadSource(src);
      hls.attachMedia(video);
      return () => hls.destroy();
    } else {
      video.src = src;
    }
  }, []);

  return (
    <section className="relative w-full h-[80vh] min-h-[520px] overflow-hidden">
      <video
        ref={vref}
        autoPlay muted loop playsInline
        className="absolute inset-0 w-full h-full object-cover"
      />
      <div className="absolute inset-0 bg-black/20"></div>
      <div className="absolute top-0 left-0 right-0 h-32 bg-gradient-to-b from-background to-transparent"></div>
      <div className="absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-background to-transparent"></div>
      <div className="absolute bottom-8 left-1/2 -translate-x-1/2 flex items-center gap-3 font-mono text-[10px] tracking-[0.3em] uppercase text-white/70">
        <span className="op-dot pulse-dot"></span>
        <span>live · 187n.ops.layer</span>
      </div>
    </section>
  );
};

// ====== HLS VIDEO INTERLUDE ======
const HlsInterlude = () => {
  const vref = React.useRef(null);
  const src = 'https://stream.mux.com/00qQnfNo7sSpn3pB1hYKkyeSDvxs01NxiQ3sr29uL3e028.m3u8';
  React.useEffect(() => {
    const video = vref.current;
    if (!video) return;
    if (video.canPlayType('application/vnd.apple.mpegurl')) {
      video.src = src;
    } else if (window.Hls && window.Hls.isSupported()) {
      const hls = new window.Hls();
      hls.loadSource(src);
      hls.attachMedia(video);
      return () => hls.destroy();
    } else {
      video.src = src;
    }
  }, []);

  return (
    <section className="relative w-full overflow-hidden -my-20 md:-my-28 pointer-events-none">
      <div className="relative h-[55vh] min-h-[420px] md:h-[70vh]">
        <video
          ref={vref}
          autoPlay muted loop playsInline
          className="absolute inset-0 w-full h-full object-cover"
        />
        <div className="absolute inset-0 bg-black/35"></div>
        <div className="absolute top-0 left-0 right-0 h-40 md:h-56 bg-gradient-to-b from-background via-background/85 to-transparent"></div>
        <div className="absolute bottom-0 left-0 right-0 h-40 md:h-56 bg-gradient-to-t from-background via-background/85 to-transparent"></div>
        <div className="absolute inset-y-0 left-0 w-24 bg-gradient-to-r from-background to-transparent"></div>
        <div className="absolute inset-y-0 right-0 w-24 bg-gradient-to-l from-background to-transparent"></div>
      </div>
    </section>
  );
};

// ====== MP4 VIDEO INTERLUDE ======
// Pulled-in negatively so adjacent section copy flows over the video edges.
const Mp4Interlude = ({ src, pullTop = true, pullBottom = true }) => {
  const cls = [
    'relative w-full overflow-hidden pointer-events-none',
    pullTop ? '-mt-64 md:-mt-80' : '',
    pullBottom ? '-mb-40 md:-mb-56' : '',
  ].filter(Boolean).join(' ');
  return (
    <section className={cls}>
      <div className="relative h-[75vh] min-h-[540px] md:h-[95vh]">
        <video
          autoPlay muted loop playsInline
          className="absolute inset-0 w-full h-full object-cover"
          src={src}
        />
        <div className="absolute inset-0 bg-black/20"></div>
        <div className="absolute top-0 left-0 right-0 h-72 md:h-96 bg-gradient-to-b from-background via-background/60 to-transparent"></div>
        <div className="absolute bottom-0 left-0 right-0 h-56 md:h-72 bg-gradient-to-t from-background via-background/80 to-transparent"></div>
        <div className="absolute inset-y-0 left-0 w-24 bg-gradient-to-r from-background/40 to-transparent"></div>
        <div className="absolute inset-y-0 right-0 w-24 bg-gradient-to-l from-background/40 to-transparent"></div>
      </div>
    </section>
  );
};

Object.assign(window, { HlsInterlude, Mp4Interlude });
