// DIRECTION 2 — LIVING DIAGRAM
// Hero centered on an animated AI↔human workflow diagram.
// Agentic, motion-forward, futuristic.

function LivingDiagram() {
  const t = useTweaks();
  const lang = t.language;
  const copy = COPY[lang];
  const headline = copy.headlines[t.headlineVariant] || copy.headlines[0];
  const ctaText = t.ctaVariant === 0 ? copy.cta : copy.ctaAlt;

  return (
    <div className="nf-artboard" style={{ width: '100%', height: '100%' }}>
      <div className="nf-scroll">
        <LdNav copy={copy} />
        <LdHero headline={headline} copy={copy} ctaText={ctaText} lang={lang} />
        <LdSplitLive lang={lang} />
        <LdPrompts lang={lang} />
        <LdProcess lang={lang} />
        <LdCases lang={lang} />
        <LdQuote lang={lang} />
        <LdStack lang={lang} />
        <LdDIY lang={lang} />
        <LdFAQ lang={lang} />
        <LdCTA copy={copy} ctaText={ctaText} lang={lang} />
        <LdFooter lang={lang} />
      </div>
    </div>
  );
}

function LdNav({ copy }) {
  const vp = useViewport();
  const [drawerOpen, setDrawerOpen] = useState(false);
  // Close drawer if viewport grows past mobile breakpoint
  useEffect(() => { if (!vp.isMobile && drawerOpen) setDrawerOpen(false); }, [vp.isMobile, drawerOpen]);
  const goToContact = () => {
    setDrawerOpen(false);
    const el = document.getElementById('contact');
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <>
      <div style={{
        position: 'sticky', top: 0, zIndex: 50,
        background: 'rgba(10,10,11,0.7)',
        backdropFilter: 'blur(20px)',
        borderBottom: '1px solid var(--nf-line)',
      }}>
        <div className="nf-container" style={{
          paddingTop: 14, paddingBottom: 14,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <NextoflowMark size={vp.isMobile ? 40 : 56} />

          {/* Desktop / tablet cluster */}
          <div className="nf-hide-mobile" style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
            <LdTicker />
            <LangBigToggle />
            <button onClick={goToContact} className="nf-btn nf-btn-primary" style={{ padding: '9px 16px', fontSize: 13 }}>{copy.cta}</button>
          </div>

          {/* Mobile hamburger */}
          <button
            className="nf-show-mobile nf-tap-44"
            aria-label={drawerOpen ? 'Close menu' : 'Open menu'}
            aria-expanded={drawerOpen}
            onClick={() => setDrawerOpen(o => !o)}
            style={{
              background: 'transparent', border: '1px solid var(--nf-ink-20)',
              borderRadius: 8, color: 'var(--nf-ink)', cursor: 'pointer',
              padding: '0 12px', fontSize: 18, lineHeight: 1,
              fontFamily: 'var(--nf-mono)',
            }}
          >{drawerOpen ? '✕' : '☰'}</button>
        </div>
      </div>

      {vp.isMobile && drawerOpen && (
        <div style={{
          position: 'fixed', top: 64, right: 16, zIndex: 60,
          background: 'var(--nf-bg-soft)', border: '1px solid var(--nf-line)',
          borderRadius: 12, padding: 16, minWidth: 200,
          display: 'flex', flexDirection: 'column', gap: 12,
          boxShadow: '0 20px 60px rgba(0,0,0,0.6)',
        }}>
          <LangBigToggle />
          <button
            className="nf-btn nf-btn-primary nf-tap-44"
            onClick={goToContact}
          >{copy.cta}</button>
        </div>
      )}
    </>
  );
}

// Animated workflow diagram as hero
function LdHero({ headline, copy, ctaText, lang }) {
  const vp = useViewport();
  const scrollTo = (id) => () => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };
  return (
    <section className="nf-section" style={{ position: 'relative', minHeight: vp.isMobile ? undefined : 820 }}>
      {/* grid backdrop */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'linear-gradient(var(--nf-ink-06) 1px, transparent 1px), linear-gradient(90deg, var(--nf-ink-06) 1px, transparent 1px)',
        backgroundSize: '56px 56px',
        maskImage: 'radial-gradient(ellipse at center, black 30%, transparent 75%)',
        WebkitMaskImage: 'radial-gradient(ellipse at center, black 30%, transparent 75%)',
      }} />

      <div style={{ position: 'relative', textAlign: 'center', marginTop: vp.isMobile ? 0 : 40, marginBottom: vp.isMobile ? 32 : 60 }}>
        <div className="nf-eyebrow" style={{ marginBottom: 28 }}>{copy.kicker}</div>
        <h1 className="nf-display nf-h1-fluid" style={{
          margin: '0 auto', fontWeight: 500,
          letterSpacing: '-0.04em', maxWidth: 1000,
        }}>
          {headline.map((line, i) => (
            <div key={i} style={{
              color: i === headline.length - 1 ? 'var(--nf-ink-60)' : 'var(--nf-ink)',
              fontStyle: i === headline.length - 1 ? 'italic' : 'normal',
              fontWeight: i === headline.length - 1 ? 400 : 500,
            }}>
              {line.split(/(80|20)/).map((chunk, j) => {
                if (chunk === '80') return <span key={j} style={{ color: 'var(--nf-blue-elec)' }}>80</span>;
                if (chunk === '20') return <span key={j} style={{ color: 'var(--nf-yellow)' }}>20</span>;
                return chunk;
              })}
            </div>
          ))}
        </h1>
        <p style={{
          margin: '32px auto 0', maxWidth: 680,
          fontSize: vp.isMobile ? 16 : 20, lineHeight: 1.45, color: 'var(--nf-ink-60)',
          textWrap: 'pretty', letterSpacing: '-0.01em',
        }}>
          {lang === 'cz'
            ? <>Stavím produkční automatizace <span style={{ color: 'var(--nf-ink)' }}>ve dnech, ne v měsících</span> — protože <span style={{ color: 'var(--nf-blue-elec)' }}>AI dělá práci</span> a <span style={{ color: 'var(--nf-yellow)' }}>já dělám rozhodnutí</span>.</>
            : <>I ship production-grade automations <span style={{ color: 'var(--nf-ink)' }}>in days, not months</span> — because <span style={{ color: 'var(--nf-blue-elec)' }}>AI does the work</span> and <span style={{ color: 'var(--nf-yellow)' }}>I make the calls</span>.</>
          }
        </p>
        <div style={{
          marginTop: 36, display: 'flex', gap: 14, justifyContent: 'center',
          flexDirection: vp.isMobile ? 'column' : 'row',
          alignItems: vp.isMobile ? 'stretch' : 'center',
        }}>
          <button onClick={scrollTo('contact')} className="nf-btn nf-btn-primary nf-tap-44" style={vp.isMobile ? { width: '100%' } : undefined}>{ctaText} →</button>
          <button onClick={scrollTo('diagram')} className="nf-btn nf-btn-ghost nf-tap-44" style={vp.isMobile ? { width: '100%' } : undefined}>{lang === 'cz' ? 'Viz live diagram ↓' : 'See live diagram ↓'}</button>
        </div>
      </div>

      <LiveDiagram lang={lang} />
    </section>
  );
}

// The centerpiece — animated workflow showing AI agents + human
function LiveDiagram({ lang }) {
  const vp = useViewport();
  const isMob = vp.isMobile;
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 1800);
    return () => clearInterval(id);
  }, []);
  const activeAgent = tick % 4;

  // Single coordinate source — connection lines regenerate from these.
  const nodes = isMob
    ? {
        source:    [50, 5],
        extract:   [50, 22],
        transform: [50, 39],
        validate:  [50, 56],
        deliver:   [50, 73],
        output:    [50, 91],
        human:     [85, 9],
      }
    : {
        source:    [8, 50],
        extract:   [20, 50],
        transform: [42, 18],
        validate:  [42, 82],
        deliver:   [65, 50],
        output:    [92, 70],
        human:     [85, 20],
      };

  const agents = [
    { id: 'extract',   label: lang === 'cz' ? 'Přečte fakturu' : 'Reads invoice',           sub: 'claude', pos: nodes.extract },
    { id: 'transform', label: lang === 'cz' ? 'Přeformátuje pro SAP' : 'Reformats for SAP', sub: 'uipath', pos: nodes.transform },
    { id: 'validate',  label: lang === 'cz' ? 'Zkontroluje chyby' : 'Checks errors',        sub: 'claude', pos: nodes.validate },
    { id: 'deliver',   label: lang === 'cz' ? 'Odešle dál' : 'Sends onward',                sub: 'n8n',    pos: nodes.deliver },
  ];

  // Derived from nodes: extract→transform, extract→validate, transform→deliver, validate→deliver, deliver→output
  // Desktop preserves the original off-node terminus (65,50 → 85,50) for visual parity.
  const connections = isMob
    ? [
        [...nodes.extract,   ...nodes.transform],
        [...nodes.extract,   ...nodes.validate],
        [...nodes.transform, ...nodes.deliver],
        [...nodes.validate,  ...nodes.deliver],
        [...nodes.deliver,   ...nodes.output],
      ]
    : [[20, 50, 42, 18], [20, 50, 42, 82], [42, 18, 65, 50], [42, 82, 65, 50], [65, 50, 85, 50]];

  return (
    <div id="diagram" style={{ scrollMarginTop: 80 }}>
    <div style={{
      position: 'relative', margin: '0 auto',
      maxWidth: isMob ? '100%' : 1100,
      height: isMob ? 560 : 460,
    }}>
    <div style={{
      position: 'absolute', inset: 0,
      border: '1px solid var(--nf-line)', borderRadius: 16,
      background: 'radial-gradient(ellipse at center, var(--nf-bg-soft) 0%, var(--nf-bg) 80%)',
      overflow: 'hidden',
      pointerEvents: 'none',
    }}>
      {/* Scanning line */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'linear-gradient(180deg, transparent 48%, rgba(59,130,246,0.08) 50%, transparent 52%)',
        animation: 'nf-scan 4s linear infinite',
      }} />
    </div>

      {/* Connection paths */}
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        {connections.map((c, i) => (
          <line key={i}
            x1={`${c[0]}%`} y1={`${c[1]}%`}
            x2={`${c[2]}%`} y2={`${c[3]}%`}
            stroke="var(--nf-blue-elec)" strokeWidth="1" strokeOpacity="0.5"
            className="nf-flowline"
          />
        ))}
      </svg>

      {/* Source input */}
      <AgentNode x={nodes.source[0]} y={nodes.source[1]} small label={lang === 'cz' ? 'Přijme email' : 'Receives email'} sub="email · sap" icon="▣" />

      {/* Agents — small icons on mobile to fit the vertical stack */}
      {agents.map((a, i) => (
        <AgentNode key={a.id} x={a.pos[0]} y={a.pos[1]} label={a.label} sub={a.sub} active={activeAgent === i} icon="◆" small={isMob} />
      ))}

      {/* Human overseer */}
      <div style={{
        position: 'absolute', left: `${nodes.human[0]}%`, top: `${nodes.human[1]}%`, transform: 'translate(-50%,-50%)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
      }}>
        <div style={{
          width: isMob ? 44 : 60, height: isMob ? 44 : 60, borderRadius: '50%',
          background: 'var(--nf-yellow)', color: '#1a1400',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--nf-display)', fontWeight: 600, fontSize: isMob ? 15 : 20,
          boxShadow: '0 0 40px rgba(247,214,74,0.4)',
          border: '2px solid var(--nf-yellow)',
        }}>TD</div>
        <div className="nf-mono" style={{ fontSize: isMob ? 9 : 10, color: 'var(--nf-yellow)', letterSpacing: '0.1em', whiteSpace: 'nowrap' }}>{lang === 'cz' ? 'ARCHITEKT / 20%' : 'ARCHITECT / 20%'}</div>
        <div className="nf-mono" style={{ fontSize: 9, color: 'var(--nf-ink-40)' }}>{lang === 'cz' ? 'rozhoduje' : 'deciding'}</div>
      </div>

      {/* Output */}
      <AgentNode x={nodes.output[0]} y={nodes.output[1]} small label={lang === 'cz' ? 'Do systému' : 'Into system'} sub="sap · crm" icon="▣" />
    </div>

    {/* Event log ticker — BELOW diagram so it doesn't overlap nodes */}
    <div style={{
      maxWidth: isMob ? '100%' : 1100, margin: '12px auto 0',
      padding: '14px 20px', borderRadius: 10,
      background: 'var(--nf-bg-soft)', border: '1px solid var(--nf-line)',
      fontFamily: 'var(--nf-mono)', fontSize: isMob ? 11 : 12, color: 'var(--nf-ink-60)',
    }}>
      <EventTicker tick={tick} lang={lang} />
    </div>
    </div>
  );
}

function AgentNode({ x, y, label, sub, small, active, icon }) {
  const size = small ? 48 : 84;
  return (
    <div style={{
      position: 'absolute', left: `${x}%`, top: `${y}%`,
      transform: 'translate(-50%,-50%)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
      transition: 'all .3s',
    }}>
      <div style={{
        width: size, height: size, borderRadius: 12,
        background: active ? 'var(--nf-blue-elec)' : 'var(--nf-bg-soft)',
        border: `1px solid ${active ? 'var(--nf-blue-sky)' : 'var(--nf-line)'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: active ? '#fff' : 'var(--nf-blue-elec)',
        fontSize: small ? 18 : 28,
        boxShadow: active ? '0 0 32px var(--nf-blue-glow)' : 'none',
        transition: 'all .3s',
      }}>{icon}</div>
      {label && (
        <>
          <div className="nf-mono" style={{
            fontSize: small ? 9 : 10,
            color: active ? 'var(--nf-ink)' : 'var(--nf-ink-60)',
            letterSpacing: '0.08em', textTransform: 'uppercase',
            whiteSpace: 'nowrap',
            textAlign: 'center',
          }}>{label}</div>
          {sub && <div className="nf-mono" style={{ fontSize: 9, color: 'var(--nf-ink-40)' }}>{sub}</div>}
        </>
      )}
    </div>
  );
}

function EventTicker({ tick, lang }) {
  const events = lang === 'cz' ? [
    '→ Extrakce: 47 řádků z e-mailu #2481',
    '→ Transformace: 47 řádků → formát SAP OK',
    '→ Validace: 2 výjimky nalezeny, přeposlány TD',
    '→ Doručení: 45 záznamů nahráno do SAPu',
  ] : [
    '→ Extract: 47 rows from email #2481',
    '→ Transform: 47 rows → SAP format OK',
    '→ Validate: 2 exceptions found, escalated to TD',
    '→ Deliver: 45 records pushed to SAP',
  ];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <span style={{ color: 'var(--nf-blue-elec)' }}>▸</span>
      <span style={{ color: 'var(--nf-ink)' }}>{events[tick % 4]}</span>
      <span className="nf-hide-mobile" style={{ marginLeft: 'auto', color: 'var(--nf-ink-40)' }}>
        T+{String(tick).padStart(3, '0')}ms · {lang === 'cz' ? 'cyklus' : 'cycle'} #{1428 + tick}
      </span>
    </div>
  );
}

// Big, obvious language switch — pill with both labels visible
function LangBigToggle() {
  const t = useTweaks();
  const set = (lang) => {
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { language: lang } }, '*');
    window.dispatchEvent(new CustomEvent('nf-lang', { detail: lang }));
  };
  const pill = (active) => ({
    padding: '8px 16px', borderRadius: 999, cursor: 'pointer',
    fontFamily: 'var(--nf-body)', fontWeight: 600, fontSize: 13,
    letterSpacing: '0.02em', border: 'none',
    transition: 'all .18s',
    background: active ? 'var(--nf-blue-elec)' : 'transparent',
    color: active ? '#fff' : 'var(--nf-ink-60)',
    boxShadow: active ? '0 0 20px var(--nf-blue-glow)' : 'none',
  });
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 4, padding: 3,
      background: 'var(--nf-bg-soft)', border: '1px solid var(--nf-ink-20)',
      borderRadius: 999,
    }}>
      <button onClick={() => set('cz')} style={pill(t.language === 'cz')}>Česky</button>
      <button onClick={() => set('en')} style={pill(t.language === 'en')}>English</button>
    </div>
  );
}

function LdTicker() {
  const t = useTweaks();
  const lang = t.language;
  return (
    <div className="nf-mono" style={{ fontSize: 11, color: 'var(--nf-ink-60)', letterSpacing: '0.1em', display: 'flex', alignItems: 'center', gap: 8 }}>
      <span className="nf-pulse" style={{ width: 6, height: 6, borderRadius: '50%', background: '#5fce5f', boxShadow: '0 0 6px #5fce5f' }} />
      {lang === 'cz'
        ? `${METRICS.bots} robotů · ${METRICS.hoursSaved.toLocaleString()} hod · ${METRICS.moneySaved} Kč ušetřeno`
        : `${METRICS.bots} bots · ${METRICS.hoursSaved.toLocaleString()} h · $${czkToUsd(METRICS.moneySaved)} saved`}
    </div>
  );
}

Object.assign(window, { LivingDiagram, LdNav, LdHero, LiveDiagram, LangBigToggle, LdTicker });
