/* global React */
// CLI / typewriter headline with CRT chromatic + caret.
const { useState, useEffect, useRef } = React;

// Types an array of lines char-by-char, in sequence.
function useTypewriter(script, { startDelay=500, cps=17, linePause=300 }={}){
  const [lines, setLines] = useState(()=> script.map(()=> ""));
  const [active, setActive] = useState(0);
  const [done, setDone] = useState(false);
  useEffect(()=>{
    let cancelled = false;
    const buf = script.map(()=> "");
    let li = 0, ci = 0;
    let timer = null;
    function step(){
      if (cancelled) return;
      if (li >= script.length){ setDone(true); setActive(script.length); return; }
      const full = script[li];
      if (ci < full.length){
        buf[li] = full.slice(0, ci + 1);
        ci++;
        setLines(buf.slice());
        setActive(li);
        const ch = full[ci-1];
        let d = 1000 / cps;
        if (ch === " ") d *= 0.5;
        if (".,&".includes(ch)) d *= 2.2;
        d += Math.random() * 45;
        timer = setTimeout(step, d);
      } else {
        li++; ci = 0;
        timer = setTimeout(step, linePause);
      }
    }
    timer = setTimeout(step, startDelay);
    return ()=>{ cancelled = true; clearTimeout(timer); };
  }, []);
  return { lines, active, done };
}

function CRTTitle(){
  // headline split into 3 lines (solid / hollow / solid-violet), then role lines
  const HEAD = ["ANNIE", "CREATIVE", "OS"];
  const ROLE_CN = "AIGC 创意策略 & 产品运营";
  const ROLE_EN = "CONTENT STRATEGY · CREATIVE PLANNING · SOCIAL OPS";
  const script = [...HEAD, ROLE_CN, ROLE_EN];
  const { lines, active, done } = useTypewriter(script, { startDelay:650, cps:18, linePause:240 });
  const caretAt = done ? 2 : active;   // park the caret on the "OS" line when finished

  return (
    <>
      <div className="namecard">
        <span className="zh">谢安妮</span>
        <span className="en">ANNIE XIE</span>
      </div>
      <div className="kicker">&gt; CREATIVE / AIGC / CONTENT OPS · 2026</div>
      <h1 className="h1">
        <span className="line l1 solid">{lines[0]}{caretAt===0 && <i className="caret"/>}</span>
        <span className="line l2 hollow">{lines[1]}{caretAt===1 && <i className="caret"/>}</span>
        <span className="line l3 solid v">{lines[2]}{caretAt===2 && <i className="caret"/>}</span>
      </h1>
      <div className="sub">
        <span className="role-cn">{lines[3]}{caretAt===3 && <i className="caret thin"/>}</span>
        <span className="role-en">{lines[4]}{caretAt===4 && <i className="caret thin"/>}</span>
      </div>
    </>
  );
}

Object.assign(window, { CRTTitle, useTypewriter });
