/* global React */
const { useState, useEffect, useRef } = React;

// ────────────────────────────────────────────────────────────
// TOP PULSE BANNER
// ────────────────────────────────────────────────────────────
function Pulse() {
  const items = [
    'System online',
    'KI-Systeme für Selbstständige',
    'Antwort in unter 24h',
    'Erstgespräch kostenlos',
    'Kein Abo. Kein Lock-in.',
  ];
  const loop = [...items, ...items, ...items, ...items];
  return (
    <div className="kat-pulse">
      <div className="kat-pulse__track">
        {loop.map((it, i) => (
          <span key={i}>
            <i className="kat-pulse__dot"></i>{it}
          </span>
        ))}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// NAV
// ────────────────────────────────────────────────────────────
function scrollTo(id) {
  const el = document.getElementById(id);
  if (el) el.scrollIntoView({ behavior: 'smooth' });
}

function Nav({ bannerOn = true }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const links = [
    { id: 'problem',  label: 'Problem' },
    { id: 'system',   label: 'System' },
    { id: 'prozess',  label: 'Prozess' },
    { id: 'preise',   label: 'Preise' },
    { id: 'julian',   label: 'Julian' },
    { id: 'faq',      label: 'FAQ' },
  ];

  const handleNav = (id) => {
    setMenuOpen(false);
    document.body.style.overflow = '';
    setTimeout(() => scrollTo(id), 10);
  };

  const toggleMenu = () => {
    const next = !menuOpen;
    setMenuOpen(next);
    document.body.style.overflow = next ? 'hidden' : '';
  };

  return (
    <>
      <nav className="kat-nav" style={{ top: bannerOn ? 28 : 0 }}>
        <a className="kat-nav__logo" href="/" onClick={e => { e.preventDefault(); scrollTo('top'); }}>
          <span className="kat-nav__k">K</span>
          <span className="kat-nav__name">KATLUN</span>
        </a>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <ul className="kat-nav__links">
            {links.map(l => (
              <li key={l.id}><a href="/" onClick={e => { e.preventDefault(); scrollTo(l.id); }}>{l.label}</a></li>
            ))}
          </ul>
          <a className="kat-nav__cta kat-nav__cta--desktop" href="https://calendly.com/jtakatlun/30min" target="_blank" rel="noreferrer">
            Erstgespräch <span style={{ fontSize: 14, lineHeight: 1 }}>→</span>
          </a>
          <button className="kat-nav__burger" onClick={toggleMenu} aria-label="Menü">
            <span className={'kat-burger' + (menuOpen ? ' kat-burger--open' : '')}>
              <span></span><span></span><span></span>
            </span>
          </button>
        </div>
      </nav>

      {menuOpen && (
        <div className="kat-mobile-menu" style={{ top: (bannerOn ? 28 : 0) + 56 }}>
          <ul className="kat-mobile-menu__links">
            {links.map(l => (
              <li key={l.id}>
                <a href="/" onClick={e => { e.preventDefault(); handleNav(l.id); }}>{l.label}</a>
              </li>
            ))}
          </ul>
          <a className="kat-btn kat-btn--primary kat-mobile-menu__cta" href="https://calendly.com/jtakatlun/30min" target="_blank" rel="noreferrer" onClick={() => { setMenuOpen(false); document.body.style.overflow = ''; }}>
            Erstgespräch buchen <span className="kat-arrow"></span>
          </a>
        </div>
      )}
    </>
  );
}

// ────────────────────────────────────────────────────────────
// HERO
// ────────────────────────────────────────────────────────────
function Hero() {
  const [hours, setHours] = useState(0);
  useEffect(() => {
    let raf, start;
    const target = 40;
    const step = (ts) => {
      if (!start) start = ts;
      const t = Math.min(1, (ts - start) / 1400);
      const eased = 1 - Math.pow(1 - t, 3);
      setHours(Math.round(eased * target));
      if (t < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, []);

  const now = new Date();
  const stamp = `${String(now.getFullYear()).slice(2)}.${String(now.getMonth()+1).padStart(2,'0')}.${String(now.getDate()).padStart(2,'0')}`;

  return (
    <section className="kat-hero" id="top">
      <div className="kat-hero__crumbs">
        <span>// KI-Systeme für Selbstständige</span>
        <span className="kat-coords">N53.5511° / E9.9937° / HAM</span>
        <span>v1.0 / Build {stamp}</span>
      </div>

      <div className="kat-hero__layout">
        <div>
          <h1 className="kat-hero__title">Dein KI</h1>
          <h1 className="kat-hero__title kat-hero__title--outline">System<span className="kat-hero__period">.</span></h1>
        </div>

        <div className="kat-hero__right">
          <span className="kat-hero__sysbadge">Aktiv / 2 Slots Mai 26</span>
          <p className="kat-hero__lede">
            Damit du wieder Zeit hast.<br/>
            <span>Ich baue dir ein maßgeschneidertes KI-System. Lead-Management,
            Marketing-Automatisierung und alles dazwischen. Kein Abo. Kein Tool von der Stange.</span>
          </p>
          <div className="kat-hero__sig">
            <span>Julian Katlun / 16 / Hamburg</span>
            <span className="kat-volt">/ persönlich</span>
          </div>
        </div>
      </div>

      <div className="kat-hero__band">
        <div className="kat-hero__ctas">
          <a className="kat-btn kat-btn--primary" href="https://calendly.com/jtakatlun/30min" target="_blank" rel="noreferrer">
            Kostenloses Erstgespräch buchen
            <span className="kat-arrow"></span>
          </a>
          <a className="kat-btn kat-btn--ghost" href="/" onClick={e => { e.preventDefault(); scrollTo('system'); }}>Mehr erfahren</a>
        </div>
        <div></div>
        <div className="kat-hero__counter">
          <b>{hours}h</b>
          <span>// Zeitersparnis / Monat / typisch</span>
        </div>
      </div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────
// BLUEPRINT — animated SVG system diagram
// ────────────────────────────────────────────────────────────
function Blueprint() {
  const ref = useRef(null);
  const [tick, setTick] = useState(0);
  useEffect(() => {
    let raf, last = performance.now();
    const loop = (ts) => {
      if (ts - last > 80) { setTick(t => t + 1); last = ts; }
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  const nodes = [
    { x: 60,   y: 110, label: 'INBOX',      kind: 'in' },
    { x: 60,   y: 60,  label: 'LINKEDIN',   kind: 'in' },
    { x: 60,   y: 160, label: 'CRM',        kind: 'in' },
    { x: 280,  y: 110, label: 'PARSER',     kind: 'mid' },
    { x: 480,  y: 60,  label: 'SCORING',    kind: 'mid' },
    { x: 480,  y: 110, label: 'KATLUN /AI', kind: 'core' },
    { x: 480,  y: 160, label: 'TEMPLATES',  kind: 'mid' },
    { x: 700,  y: 60,  label: 'FOLLOW-UP',  kind: 'out' },
    { x: 700,  y: 110, label: 'CRM-SYNC',   kind: 'out' },
    { x: 700,  y: 160, label: 'REPORT',     kind: 'out' },
    { x: 900,  y: 110, label: 'DU',         kind: 'you' },
  ];
  const edges = [
    [0,3],[1,3],[2,3],[3,4],[3,5],[3,6],[4,7],[5,8],[6,9],[7,10],[8,10],[9,10]
  ];

  return (
    <section className="kat-blueprint">
      <div className="kat-blueprint__head">
        <span>// Live-Blueprint / Beispielsystem Lead-Reaktivierung</span>
        <span><b>{(tick % 200).toString().padStart(3,'0')}</b> events processed</span>
      </div>
      <svg className="kat-blueprint__svg" viewBox="0 0 980 220" preserveAspectRatio="xMidYMid meet" ref={ref}>
        {edges.map(([a, b], i) => {
          const A = nodes[a], B = nodes[b];
          const offset = ((tick + i * 7) % 24);
          return (
            <line key={i} x1={A.x+58} y1={A.y} x2={B.x-58} y2={B.y}
              stroke="#2A2A2A" strokeWidth="1"
              strokeDasharray="4 4" strokeDashoffset={-offset} />
          );
        })}
        {edges.map(([a, b], i) => {
          const A = nodes[a], B = nodes[b];
          const p = ((tick * 0.6 + i * 13) % 60) / 60;
          const x = (A.x+58) + (B.x-58 - (A.x+58)) * p;
          const y = A.y + (B.y - A.y) * p;
          return <circle key={'d'+i} cx={x} cy={y} r="2" fill="#DCFF1E" />;
        })}
        {nodes.map((n, i) => {
          const isCore = n.kind === 'core';
          const isYou = n.kind === 'you';
          const w = 116;
          const h = 28;
          return (
            <g key={i} transform={`translate(${n.x - w/2}, ${n.y - h/2})`}>
              <rect width={w} height={h}
                fill={isCore ? '#DCFF1E' : '#111111'}
                stroke={isCore || isYou ? '#DCFF1E' : '#2A2A2A'}
                strokeWidth="1.5" />
              <text x={w/2} y={h/2 + 4} textAnchor="middle"
                fontFamily="Space Mono, monospace" fontSize="10"
                letterSpacing="1.2"
                fill={isCore ? '#080808' : (isYou ? '#DCFF1E' : '#FFFFFF')}>
                {n.label}
              </text>
            </g>
          );
        })}
        <text x="60" y="200" fontFamily="Space Mono" fontSize="9" fill="#444" letterSpacing="1.5">// INPUT</text>
        <text x="430" y="200" fontFamily="Space Mono" fontSize="9" fill="#444" letterSpacing="1.5">// LOGIC</text>
        <text x="680" y="200" fontFamily="Space Mono" fontSize="9" fill="#444" letterSpacing="1.5">// OUTPUT</text>
        <text x="880" y="200" fontFamily="Space Mono" fontSize="9" fill="#DCFF1E" letterSpacing="1.5">// SPART ZEIT</text>
      </svg>
    </section>
  );
}

// ────────────────────────────────────────────────────────────
// TRUST MARQUEE
// ────────────────────────────────────────────────────────────
function Trust() {
  const logos = [
    { name: 'Leaders Academy', img: 'assets/leaders-academy.png' },
    { name: 'Pilates Loft Quickborn' },
  ];
  const loop = [...logos, ...logos, ...logos, ...logos, ...logos, ...logos];
  return (
    <div className="kat-trust">
      <div className="kat-trust__inner">
        <div className="kat-trust__label">Vertrauen<br/>aktuelle Kunden</div>
        <div className="kat-trust__mask">
          <div className="kat-trust__track">
            {loop.map((l, i) => (
              <span key={i} className="kat-trust__logo">
                {l.img
                  ? <img src={l.img} alt={l.name} className="kat-trust__logo-img" />
                  : <><i></i>{l.name}</>}
              </span>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.Pulse = Pulse;
window.Nav = Nav;
window.Hero = Hero;
window.Blueprint = Blueprint;
window.Trust = Trust;
