// Hero section — includes the terminal-style display
const { useState, useEffect, useRef } = React;

function Hero() {
  const [heroMode, setHeroMode] = useState(window.__TWEAKS.hero || "terminal");

  useEffect(() => {
    const fn = (e) => setHeroMode(e.detail);
    window.addEventListener("tweak-hero", fn);
    return () => window.removeEventListener("tweak-hero", fn);
  }, []);

  return (
    <section className="hero">
      <div className="hero-left">
        <div>
          <div className="section-tag">studio.debug // v4.2.0 // mundo — remoto</div>
          <h1 className="hero-title">
            <span className="line">um studio</span>
            <span className="line">de <em>devs</em></span>
            <span className="line"><span className="glitch" data-text="loucos">loucos</span>.</span>
          </h1>
          <p className="hero-sub">
            <span className="accent">{">"}</span> Somos um <span className="hl">laboratório de desenvolvimento científico</span>.{" "}
            Construímos sistemas que não existiam — mercados de previsão, ferramentas de pesquisa,{" "}
            produtos digitais com <span className="hl">viés de experimento</span>.{" "}
            <br/><br/>
            <span className="accent">{">"}</span> Testamos hipóteses. Publicamos resultados. Quebramos coisa com intenção.{" "}
            <span className="hl">Não prometemos “solução”</span>; prometemos rigor, velocidade e um pouco de humor.
          </p>
        </div>

        <div className="hero-meta">
          <div className="hero-meta-cell"><strong>08</strong>devs no laboratório</div>
          <div className="hero-meta-cell"><strong>87</strong>projetos publicados</div>
          <div className="hero-meta-cell"><strong>14y</strong>stack experiment.</div>
          <div className="hero-meta-cell"><strong>2026</strong>ano fiscal atual</div>
        </div>
      </div>

      <div className="hero-right">
        {heroMode === "terminal" && <HeroTerminal />}
        {heroMode === "ascii" && <HeroAscii />}
        {heroMode === "matrix" && <HeroMatrix />}
      </div>
    </section>
  );
}

function HeroTerminal() {
  const [lines, setLines] = useState([]);
  const [input, setInput] = useState("");
  const bodyRef = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => {
    const boot = [
      { t: "muted", c: "studio.debug terminal — v4.2.0 (caffeine build)" },
      { t: "muted", c: "Copyright 2026 studio.debug lab. PRs welcome, egos aren't." },
      { t: "muted", c: "Type `help` to discover. Or don't. We respect both." },
      { t: "plain", c: "" },
      { t: "prompt", c: "$ whoami" },
      { t: "ok", c: "> guest@curious (sessão iniciada às "+ new Date().toTimeString().slice(0,8) +")" },
      { t: "plain", c: "" },
      { t: "prompt", c: "$ ./studio --status" },
      { t: "ok", c: "[ ok ] caffeine .................. 94%" },
      { t: "ok", c: "[ ok ] bug-density ............... low-ish" },
      { t: "warn",c: "[warn] meme-channel .............. overflowing" },
      { t: "ok", c: "[ ok ] deploys (last 24h) ........ 23" },
      { t: "pink",c: "[ ok ] existential-dread ......... nominal" },
      { t: "plain", c: "" },
      { t: "prompt", c: "$ cat manifesto.txt" },
      { t: "user", c: "  \"código é hipótese; produto é experimento;" },
      { t: "user", c: "   bug é uma verdade que ninguém quis ouvir.\"" },
      { t: "plain", c: "" },
      { t: "muted", c: "Ready. Digite algo abaixo — tente `ls`, `projects`, `hire`, `sudo`." },
    ];
    // type them in
    let i = 0;
    const interval = setInterval(() => {
      if (i >= boot.length) { clearInterval(interval); return; }
      const item = boot[i];
      i++;
      if (item) setLines(prev => [...prev, item]);
    }, 55);
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [lines]);

  const commands = {
    help: () => [
      "Available commands:",
      "  ls          – listar pastas do estúdio",
      "  projects    – últimos builds públicos",
      "  team        – quem está no laboratório",
      "  hire        – vagas abertas",
      "  contact     – fale com a gente",
      "  coffee      – status do café",
      "  sudo        – não",
      "  clear       – limpar tela",
    ],
    ls: () => ["./services/  ./projects/  ./team/  ./process/  ./notes/  ./careers/  ./contact/"],
    projects: () => [
      "001  Oráculo               Prediction Market    2025",
      "002  Kernel                Fintech stealth      2025",
      "003  Sinapse               Instituto pesquisa   2024",
      "...  mais em ./work/",
    ],
    team: () => ["08 humanos + 2 gatos + 1 planta que todo mundo esquece de regar."],
    hire: () => [
      "Vagas abertas:",
      "  - Senior Design Engineer  (remoto)",
      "  - Systems Engineer        (SP híbrido)",
      "  - Research: Prediction    (6m)",
      "  Scroll até ./careers.",
    ],
    contact: () => ["contato@studiodebug.dev  ·  +55 11 9####-####  ·  @studiodebug"],
    coffee: () => ["☕  cafeteira: on. nível: 82%. humor do barista: instável."],
    sudo: () => ["[sudo] senha para guest: nice try 😏"],
    clear: () => "CLEAR",
    whoami: () => ["guest@curious"],
  };

  const handle = (e) => {
    if (e.key !== "Enter") return;
    const cmd = input.trim();
    if (!cmd) return;
    const echo = { t: "prompt", c: "$ " + cmd };
    let out;
    const fn = commands[cmd.toLowerCase().split(" ")[0]];
    if (fn) {
      const r = fn();
      if (r === "CLEAR") { setLines([]); setInput(""); return; }
      out = r.map(s => ({ t: "user", c: s }));
    } else {
      out = [{ t: "err", c: "debug: command not found: " + cmd + ". try `help`." }];
    }
    setLines(prev => [...prev, echo, ...out, { t: "plain", c: "" }]);
    setInput("");
  };

  return (
    <div className="terminal-window" onClick={() => inputRef.current?.focus()}>
      <div className="terminal-bar">
        <div className="term-dots"><span/><span/><span/></div>
        <div className="terminal-title">~/studio/debug — zsh — 120×36</div>
        <div style={{width:40,textAlign:"right",color:"var(--accent)"}} className="blink">●</div>
      </div>
      <div className="terminal-body" ref={bodyRef}>
        {lines.map((l, i) => (
          <div key={i} className={"term-line term-" + (l.t || "plain")}>{l.c || "\u00A0"}</div>
        ))}
        <div className="term-input-line">
          <span className="term-prompt">$</span>
          <input
            ref={inputRef}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handle}
            spellCheck={false}
            autoComplete="off"
            aria-label="terminal input"
          />
          <span className="term-cursor"/>
        </div>
      </div>
    </div>
  );
}

function HeroAscii() {
  // Big STUDIO/DEBUG ASCII
  const art = `
  ███████╗████████╗██╗   ██╗██████╗ ██╗ ██████╗
  ██╔════╝╚══██╔══╝██║   ██║██╔══██╗██║██╔═══██╗
  ███████╗   ██║   ██║   ██║██║  ██║██║██║   ██║
  ╚════██║   ██║   ██║   ██║██║  ██║██║██║   ██║
  ███████║   ██║   ╚██████╔╝██████╔╝██║╚██████╔╝
  ╚══════╝   ╚═╝    ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝
  ██████╗ ███████╗██████╗ ██╗   ██╗ ██████╗ 
  ██╔══██╗██╔════╝██╔══██╗██║   ██║██╔════╝
  ██║  ██║█████╗  ██████╔╝██║   ██║██║  ███╗
  ██║  ██║██╔══╝  ██╔══██╗██║   ██║██║   ██║
  ██████╔╝███████╗██████╔╝╚██████╔╝╚██████╔╝
  ╚═════╝ ╚══════╝╚═════╝  ╚═════╝  ╚═════╝
`;
  return (
    <div className="terminal-window">
      <div className="terminal-bar">
        <div className="term-dots"><span/><span/><span/></div>
        <div className="terminal-title">ascii-render — studio.debug</div>
        <div style={{width:40}}></div>
      </div>
      <div className="ascii-canvas">{art}</div>
    </div>
  );
}

function HeroMatrix() {
  const canvasRef = useRef(null);
  useEffect(() => {
    const c = canvasRef.current;
    const ctx = c.getContext("2d");
    const resize = () => {
      c.width = c.offsetWidth * devicePixelRatio;
      c.height = c.offsetHeight * devicePixelRatio;
    };
    resize();
    window.addEventListener("resize", resize);
    const chars = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミ01{}[]<>();$#@~/\\";
    const cols = Math.floor(c.width / 16);
    const ys = Array(cols).fill(0).map(() => Math.random() * c.height);
    let raf;
    const draw = () => {
      ctx.fillStyle = "rgba(0,0,0,0.12)";
      ctx.fillRect(0,0,c.width,c.height);
      ctx.font = "16px JetBrains Mono, monospace";
      for (let i = 0; i < cols; i++) {
        const ch = chars[Math.floor(Math.random()*chars.length)];
        ctx.fillStyle = Math.random() < 0.02 ? "#ff3ea5" : "#00ff88";
        ctx.fillText(ch, i*16, ys[i]);
        ys[i] += 16;
        if (ys[i] > c.height && Math.random() > 0.975) ys[i] = 0;
      }
      raf = requestAnimationFrame(draw);
    };
    draw();
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", resize); };
  }, []);
  return (
    <div className="terminal-window">
      <div className="terminal-bar">
        <div className="term-dots"><span/><span/><span/></div>
        <div className="terminal-title">matrix.exe — ctrl+c pra parar (não para)</div>
        <div style={{width:40}}></div>
      </div>
      <canvas ref={canvasRef} className="matrix-canvas"/>
    </div>
  );
}

function Marquee() {
  const items = [
    { t: "laboratório de devs loucos", cls: "" },
    { t: "✦", cls: "pop" },
    { t: "prediction markets", cls: "mute" },
    { t: "/", cls: "pop" },
    { t: "design systems", cls: "mute" },
    { t: "/", cls: "pop" },
    { t: "AI plumbing", cls: "mute" },
    { t: "/", cls: "pop" },
    { t: "experimentos científicos", cls: "mute" },
    { t: "✦", cls: "pop" },
    { t: "desde 2012", cls: "" },
  ];
  const loop = [...items, ...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {loop.map((it, i) => (
          <span key={i} className={it.cls}>{it.t}</span>
        ))}
      </div>
    </div>
  );
}

window.Hero = Hero;
window.Marquee = Marquee;
