// hero.jsx — three switchable hero variants: centered / split / terminal
const { useState: useStateHero, useEffect: useEffectHero, useRef: useRefHero } = React;

const STACK = [
  "linux", "rust", "python", "typescript", "react",
  "docker", "git", "neovim", "postgresql", "gnubash", "cypress", "obsidian",
];

function StackStrip() {
  const track = [...STACK, ...STACK];
  return (
    <div className="stack-strip">
      <div className="stack-label">// the stack &amp; tools I live in</div>
      <div className="stack-track">
        {track.map((s, i) => (
          <img key={s + i} src={`https://cdn.simpleicons.org/${s}/9B7BE0`} alt={s} title={s} />
        ))}
      </div>
    </div>
  );
}

function HeroCopy({ onGo }) {
  // sharp, randomized glitch-tear bursts on the hero title only
  React.useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const lines = Array.from(document.querySelectorAll(".hero h1 .glitch"));
    if (!lines.length) return;
    const rnd = (a, b) => a + Math.random() * (b - a);
    const timers = [];
    const clearAll = () => { while (timers.length) clearTimeout(timers.pop()); };

    const frame = (line) => {
      // a thin random horizontal tear band that shifts left/right
      const top = rnd(0, 78);
      const h = rnd(5, 24);
      line.style.setProperty("--g-top", top.toFixed(1) + "%");
      line.style.setProperty("--g-bot", Math.max(0, 100 - top - h).toFixed(1) + "%");
      line.style.setProperty("--gx-a", rnd(-7, 7).toFixed(1) + "px");
      line.style.setProperty("--gx-b", rnd(-7, 7).toFixed(1) + "px");
      line.style.setProperty("--gy", rnd(-2, 2).toFixed(1) + "px");
      line.style.setProperty("--gx-base", rnd(-3, 3).toFixed(1) + "px");
    };

    const burst = () => {
      if (document.documentElement.getAttribute("data-calm") === "on" || reduce) { schedule(); return; }
      lines.forEach((l) => l.classList.add("glitching"));
      const steps = Math.floor(rnd(6, 11));
      let n = 0;
      const tick = () => {
        lines.forEach(frame);
        n++;
        if (n < steps) {
          timers.push(setTimeout(tick, rnd(22, 46)));   // fast, sharp frames
        } else {
          lines.forEach((l) => {
            l.classList.remove("glitching");
            ["--g-top", "--g-bot", "--gx-a", "--gx-b", "--gy", "--gx-base"].forEach((p) => l.style.removeProperty(p));
          });
          schedule();
        }
      };
      tick();
    };

    function schedule() { timers.push(setTimeout(burst, rnd(2400, 4600))); }
    timers.push(setTimeout(burst, 900));   // first burst shortly after load
    return clearAll;
  }, []);

  return (
    <React.Fragment>
      <span className="eyebrow">personal hub · QA &amp; systems</span>
      <h1>
        <span className="line glitch" data-text="A nerd turning chaos into">A nerd turning chaos into</span>
        <span className="line accent glitch" data-text="systems that make sense.">systems that make sense.</span>
      </h1>
      <p className="hero-sub">I turn chaos into structure, ideas into systems, and messy work into something humans can actually use.</p>
      <p className="hero-tag"><span className="c">//</span> break the problem into clean steps, then put it back so it makes sense</p>
      <div className="hero-cta">
        <a className="btn btn-primary" href="#projects" onClick={(e) => onGo(e, "projects")}>Projects <i data-lucide="arrow-right"></i></a>
        <a className="btn btn-ghost" href="#notes" onClick={(e) => onGo(e, "notes")}><span className="br">~/</span>notes</a>
        <a className="btn btn-ghost" href="#contact" onClick={(e) => onGo(e, "contact")}><span className="br">$</span> contact</a>
      </div>
      <div className="hero-status" style={{ marginTop: 28 }}>
        <span className="live-dot"></span>
        <span>right now: tuning <strong>&nbsp;SortiiiQ</strong></span>
      </div>
    </React.Fragment>
  );
}

// static whoami panel for the split variant
function WhoamiPanel() {
  return (
    <div className="term" aria-hidden="true">
      <div className="term-bar">
        <span className="term-dot r"></span><span className="term-dot y"></span><span className="term-dot g"></span>
        <span className="term-title">~/sirucka — zsh</span>
      </div>
      <div className="term-body">
        <div className="term-line"><span className="pr">$</span> whoami</div>
        <div className="term-line term-out"><span className="v">qa-engineer</span> · automation · system-builder</div>
        <div className="term-line"><span className="pr">$</span> cat focus.json</div>
        <div className="term-line term-out">{"{"}</div>
        <div className="term-line term-out">{"  quality:  "}<span className="v">"find what breaks first"</span>,</div>
        <div className="term-line term-out">{"  tools:    "}<span className="v">["SortiiiQ", "MyMoney"]</span>,</div>
        <div className="term-line term-out">{"  mind:     "}<span className="v">"sustainable &gt;= heroics"</span></div>
        <div className="term-line term-out">{"}"}</div>
        <div className="term-line"><span className="pr">$</span> status --now</div>
        <div className="term-line term-out"><span className="ok">● online</span> — shipping &amp; curious<span className="term-cursor"></span></div>
      </div>
    </div>
  );
}

// animated typing terminal for the terminal variant
const TERM_SCRIPT = [
  { t: "cmd", text: "whoami" },
  { t: "out", html: <span><span className="v">qa-engineer</span> -&gt; automation -&gt; system-builder</span> },
  { t: "cmd", text: "./run --suite=sirucka.cz" },
  { t: "out", html: <span><span className="ok">✓ 142 passed</span> != 0 flaky &nbsp;(142 &gt;= target)</span> },
  { t: "out", html: <span>{"  "}tools:    <span className="v">["SortiiiQ", "MyMoney"]</span>,</span> },
  { t: "cmd", text: "git log --oneline -1" },
  { t: "out", html: <span><span className="v">a1b2c3d</span> feat: order from chaos</span> },
  { t: "cmd", text: "echo $MOTTO" },
  { t: "out", html: <span>I'm a nerd and I love it.</span> },
];

function TypingTerminal() {
  const [done, setDone] = useStateHero([]);          // completed line objects
  const [typed, setTyped] = useStateHero("");        // currently-typing cmd text
  const [idx, setIdx] = useStateHero(0);
  const timers = useRefHero([]);

  useEffectHero(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) { setDone(TERM_SCRIPT); setIdx(TERM_SCRIPT.length); return; }
    if (idx >= TERM_SCRIPT.length) return;
    const line = TERM_SCRIPT[idx];
    if (line.t === "out") {
      const id = setTimeout(() => { setDone((d) => [...d, line]); setIdx((i) => i + 1); }, 280);
      timers.current.push(id);
      return () => clearTimeout(id);
    }
    // type the command char by char
    let ch = 0;
    const tick = () => {
      ch++;
      setTyped(line.text.slice(0, ch));
      if (ch < line.text.length) {
        const id = setTimeout(tick, 42 + Math.random() * 50);
        timers.current.push(id);
      } else {
        const id = setTimeout(() => { setDone((d) => [...d, line]); setTyped(""); setIdx((i) => i + 1); }, 420);
        timers.current.push(id);
      }
    };
    const start = setTimeout(tick, 220);
    timers.current.push(start);
    return () => clearTimeout(start);
  }, [idx]);

  useEffectHero(() => () => timers.current.forEach(clearTimeout), []);

  const finished = idx >= TERM_SCRIPT.length;
  return (
    <div className="term-wrap">
      <div className="term">
        <div className="term-bar">
          <span className="term-dot r"></span><span className="term-dot y"></span><span className="term-dot g"></span>
          <span className="term-title">~/sirucka — zsh</span>
        </div>
        <div className="term-body">
          {done.map((l, i) => (
            l.t === "cmd"
              ? <div className="term-line" key={i}><span className="pr">$</span> {l.text}</div>
              : <div className="term-line term-out" key={i}>{l.html}</div>
          ))}
          {!finished && idx < TERM_SCRIPT.length && TERM_SCRIPT[idx].t === "cmd" && (
            <div className="term-line"><span className="pr">$</span> {typed}<span className="term-cursor"></span></div>
          )}
          {finished && <div className="term-line"><span className="pr">$</span> <span className="term-cursor"></span></div>}
        </div>
      </div>
    </div>
  );
}

function Hero({ variant, onGo }) {
  if (variant === "split") {
    return (
      <header className="hero wrap" id="top">
        <div className="hero-split">
          <div><HeroCopy onGo={onGo} /></div>
          <WhoamiPanel />
        </div>
        <StackStrip />
      </header>
    );
  }
  if (variant === "terminal") {
    return (
      <header className="hero wrap hero-terminal" id="top">
        <HeroCopy onGo={onGo} />
        <TypingTerminal />
        <StackStrip />
      </header>
    );
  }
  // centered (default)
  return (
    <header className="hero wrap hero-centered" id="top">
      <HeroCopy onGo={onGo} />
      <StackStrip />
    </header>
  );
}

window.Hero = Hero;
