// terminal-section.jsx — terminal que se escribe sola cuando está en view

const TERMINAL_LINES = [
  { type: 'cmd',    text: 'git clone git@github.com:irontec-comms/nexus.git' },
  { type: 'out',    text: 'Cloning into \u0027nexus\u0027… done.' },
  { type: 'cmd',    text: 'pnpm install' },
  { type: 'out',    text: '+ 1247 packages installed · 18.3s' },
  { type: 'cmd',    text: 'pnpm --filter server payload migrate' },
  { type: 'out',    text: '✓ migrations applied · Postgres schema ready' },
  { type: 'cmd',    text: 'pnpm dev' },
  { type: 'out',    text: '▲ Next.js 16 · ready on http://localhost:3000' },
  { type: 'out',    text: '● Payload admin → /admin' },
  { type: 'out',    text: '● MCP proxy → /api/search/mcp' },
  { type: 'out',    text: '● Keycloak OIDC → ready' },
  { type: 'ok',     text: 'Nexus is live.' },
];

const Terminal = ({ active }) => {
  const [charCount, setCharCount] = React.useState(0);

  // Build flat character stream with per-line markers
  const stream = React.useMemo(() => {
    const out = [];
    TERMINAL_LINES.forEach((line, i) => {
      const prefix = line.type === 'cmd' ? '$ ' : line.type === 'ok' ? '✓ ' : '  ';
      const full = prefix + line.text;
      for (let c = 0; c < full.length; c++) {
        out.push({ ch: full[c], line: i, type: line.type });
      }
      out.push({ ch: '\n', line: i, type: line.type, newline: true });
    });
    return out;
  }, []);

  React.useEffect(() => {
    if (!active) return;
    let idx = 0;
    setCharCount(0);
    let cancelled = false;
    const tick = () => {
      if (cancelled) return;
      idx++;
      setCharCount(idx);
      if (idx < stream.length) {
        const ch = stream[idx - 1]?.ch;
        const delay = ch === '\n' ? 180 : (ch === ' ' ? 18 : 22);
        setTimeout(tick, delay);
      }
    };
    const start = setTimeout(tick, 400);
    return () => { cancelled = true; clearTimeout(start); };
  }, [active, stream]);

  const visible = stream.slice(0, charCount);
  const lines = [];
  let current = { parts: [], type: 'out', key: 0 };
  visible.forEach((c, i) => {
    if (c.newline) {
      lines.push(current);
      current = { parts: [], type: 'out', key: lines.length };
    } else {
      current.parts.push(c.ch);
      current.type = c.type;
    }
  });
  if (current.parts.length > 0) lines.push(current);

  const caretVisible = charCount < stream.length ? true : (Math.floor(Date.now() / 500) % 2 === 0);

  return (
    <div style={{
      background: '#0d0d0d',
      border: '1px solid rgba(161,247,94,0.22)',
      boxShadow: '0 40px 80px -20px rgba(13,13,13,0.6), 0 0 0 1px rgba(161,247,94,0.06)',
      maxWidth: 760, width: '100%',
      fontFamily: "'JetBrains Mono', ui-monospace, monospace",
      fontSize: 14,
      lineHeight: 1.7,
      color: '#f9f9f9',
    }}>
      {/* Window chrome */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '10px 16px',
        borderBottom: '1px solid rgba(255,255,255,0.06)',
      }}>
        <span style={{ width: 10, height: 10, background: '#ff5f57' }} />
        <span style={{ width: 10, height: 10, background: '#febc2e' }} />
        <span style={{ width: 10, height: 10, background: '#28c840' }} />
        <span style={{
          marginLeft: 18, fontSize: 11, letterSpacing: '0.1em',
          color: 'rgba(255,255,255,0.4)', textTransform: 'uppercase',
        }}>
          ~/nexus · zsh
        </span>
      </div>

      <div style={{ padding: '24px 24px 28px', minHeight: 380 }}>
        {lines.map((line, i) => {
          const text = line.parts.join('');
          const color = line.type === 'cmd' ? '#f9f9f9'
                      : line.type === 'ok'  ? '#a1f75e'
                      : 'rgba(249,249,249,0.55)';
          const weight = line.type === 'cmd' ? 600 : 400;
          const isLast = i === lines.length - 1;
          return (
            <div key={i} style={{ color, fontWeight: weight, whiteSpace: 'pre-wrap' }}>
              {text}
              {isLast && caretVisible && (
                <span style={{
                  display: 'inline-block', width: 8, height: 16,
                  background: '#a1f75e', marginLeft: 2, verticalAlign: 'text-bottom',
                }}/>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

const TerminalSection = () => {
  const ref = React.useRef(null);
  const inView = useInView(ref, { threshold: 0.35, once: true });

  return (
    <section
      ref={ref}
      data-screen-label="03 Terminal"
      style={{
        position: 'relative',
        padding: 'clamp(96px, 12vw, 160px) clamp(24px, 5vw, 60px)',
        background: '#0d0d0d',
        color: '#f9f9f9',
        overflow: 'hidden',
      }}
    >
      {/* Background grid */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px)',
        backgroundSize: '60px 60px',
        maskImage: 'radial-gradient(ellipse at center, #000 40%, transparent 80%)',
      }}/>

      <div style={{
        position: 'relative',
        maxWidth: 1400, margin: '0 auto',
        display: 'grid',
        gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.1fr)',
        gap: 'clamp(40px, 6vw, 96px)',
        alignItems: 'center',
      }} className="nx-terminal-grid">
        <div>
          <Reveal>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 10,
              fontSize: 12, letterSpacing: '0.2em', textTransform: 'uppercase',
              fontWeight: 600, marginBottom: 24, color: '#a1f75e',
            }}>
              <span style={{ width: 9, height: 9, background: '#a1f75e', display: 'inline-block' }} />
              02 · Arranque
            </div>
          </Reveal>
          <Reveal delay={150}>
            <h2 style={{
              fontSize: 'clamp(36px, 5vw, 68px)',
              fontWeight: 600,
              lineHeight: 1.02,
              letterSpacing: '-0.02em',
              margin: 0,
            }}>
              De cero a producción<br/>
              en <span style={{ color: '#a1f75e' }}>cuatro comandos</span>.
            </h2>
          </Reveal>
          <Reveal delay={300}>
            <p style={{
              marginTop: 28, fontSize: 'clamp(15px, 1.2vw, 18px)',
              maxWidth: '44ch', lineHeight: 1.6,
              color: 'rgba(249,249,249,0.7)',
            }}>
              Monorepo TypeScript, Payload CMS, Keycloak, Postgres, Typesense y MCP
              configurados y cableados. Helm charts, ArgoCD y Talos listos en <code style={{
                color: '#a1f75e',
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              }}>deploy/</code>.
            </p>
          </Reveal>
          <Reveal delay={450}>
            <div style={{
              marginTop: 40, display: 'grid', gap: 10,
              fontSize: 13, color: 'rgba(249,249,249,0.6)',
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            }}>
              {['TypeScript · pnpm · Turborepo', 'Next.js 16 + Payload CMS 3', 'better-auth + Keycloak OIDC', 'Typesense hybrid search + RAG'].map(s => (
                <div key={s} style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                  <span style={{ color: '#a1f75e' }}>▸</span>{s}
                </div>
              ))}
            </div>
          </Reveal>
        </div>

        <Reveal delay={200} y={32}>
          <Terminal active={inView} />
        </Reveal>
      </div>
    </section>
  );
};

Object.assign(window, { TerminalSection });
