function useTypewriter(variants, opts = {}) {
  const { typeMs = 38, deleteMs = 14, holdMs = 2400, gapMs = 400 } = opts;
  const [variantIdx, setVariantIdx] = React.useState(0);
  const [cursor, setCursor] = React.useState(0);    // chars currently visible
  const [phase, setPhase] = React.useState("typing"); // typing | holding | deleting | gap

  const flat = React.useMemo(() => variants[variantIdx].map(s => s.text).join(""), [variants, variantIdx]);

  React.useEffect(() => {
    let t;
    if (phase === "typing") {
      if (cursor < flat.length) t = setTimeout(() => setCursor(cursor + 1), typeMs);
      else t = setTimeout(() => setPhase("holding"), 0);
    } else if (phase === "holding") {
      t = setTimeout(() => setPhase("deleting"), holdMs);
    } else if (phase === "deleting") {
      if (cursor > 0) t = setTimeout(() => setCursor(cursor - 1), deleteMs);
      else t = setTimeout(() => setPhase("gap"), 0);
    } else if (phase === "gap") {
      t = setTimeout(() => {
        setVariantIdx((variantIdx + 1) % variants.length);
        setPhase("typing");
      }, gapMs);
    }
    return () => clearTimeout(t);
  }, [phase, cursor, flat, variantIdx, variants.length, typeMs, deleteMs, holdMs, gapMs]);

  // Render segments up to `cursor` chars total, preserving per-segment styling.
  const rendered = [];
  let remaining = cursor;
  for (let i = 0; i < variants[variantIdx].length; i++) {
    const seg = variants[variantIdx][i];
    if (remaining <= 0) break;
    const take = Math.min(seg.text.length, remaining);
    rendered.push({ ...seg, text: seg.text.slice(0, take) });
    remaining -= take;
  }
  return rendered;
}

function DeployTicker() {
  const all = React.useMemo(() => ([
    { ref: "v2.4.1",        msg: "luminaya.dev/preview built · 12s",     status: "ok" },
    { ref: "feat/billing",  msg: "deploying to preview...",              status: "run" },
    { ref: "feat/billing",  msg: "preview ready · 38s",                  status: "ok" },
    { ref: "fern.health",   msg: "triage workflow · prod · 142s",        status: "ok" },
    { ref: "harbour.fm",    msg: "pricing-v2 · ci passing · 11/11",      status: "ok" },
    { ref: "orbit.dash",    msg: "v2.3.9 · prod · 121s",                 status: "ok" },
    { ref: "lila.gallery",  msg: "image-opt step retrying...",           status: "run" }
  ]), []);
  const [head, setHead] = React.useState(0);
  React.useEffect(() => {
    const i = setInterval(() => setHead(h => (h + 1) % all.length), 2400);
    return () => clearInterval(i);
  }, [all.length]);

  // show 4 visible lines, oldest at top
  const visible = [];
  for (let i = 0; i < 4; i++) {
    visible.push(all[(head + i) % all.length]);
  }

  return (
    <div className="hero-ticker" aria-hidden="true">
      <div className="ticker-bar">
        <i></i><i></i><i></i>
        <span className="ticker-title">~/luminaya — deploy.log</span>
        <span className="ticker-live"><span className="status-dot mint" style={{width:6,height:6}}></span>live</span>
      </div>
      <div className="ticker-body">
        {visible.map((l, i) => (
          <div key={head + "-" + i} className={"ticker-line ticker-" + l.status} style={{ opacity: i === 0 ? 0.45 : i === 3 ? 1 : 0.85 }}>
            <span className="ticker-arrow">{l.status === "run" ? "•" : "→"}</span>
            <span className="ticker-ref">{l.ref}</span>
            <span className="ticker-msg">{l.msg}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function Hero() {
  const variants = React.useMemo(() => ([
    [
      { text: "heavy", strike: true },
      { text: " software,\nfor people who already " },
      { text: "read the docs", accent: true },
      { text: "." }
    ],
    [
      { text: "slow", strike: true },
      { text: " websites,\nfor teams that already " },
      { text: "write the copy", accent: true },
      { text: "." }
    ],
    [
      { text: "fragile", strike: true },
      { text: " internals,\nfor ops that already " },
      { text: "know the workflow", accent: true },
      { text: "." }
    ]
  ]), []);
  const segs = useTypewriter(variants);

  return (
    <section id="top" className="hero">
      <div className="hero-grid-bg"></div>
      <div className="container hero-inner">
        <p className="eyebrow">software development studio · est. 2024</p>

        <h1 className="hero-headline">
          We ship<br/>
          {segs.map((s, i) => {
            const cls = s.strike ? "strike" : s.accent ? "accent" : "";
            // split on newline to preserve line break inside a segment
            const parts = s.text.split("\n");
            return parts.map((p, j) => (
              <React.Fragment key={i + "-" + j}>
                {j > 0 && <br/>}
                <span className={cls}>{p}</span>
              </React.Fragment>
            ));
          })}
          <span className="hero-caret">▌</span>
        </h1>

        <p className="hero-sub">
          Three engineers. Contract work. Web apps, internal tools, mobile apps that don't waste a battery.
        </p>
        <div className="hero-cta">
          <a href="#contact" className="btn btn-primary">Start a project →</a>
          <a href="#services" className="btn btn-ghost">What we do ↓</a>
        </div>

        <div className="hero-meta">
          <span><span className="status-dot"></span> currently booking · jul–sep</span>
          <span>3 engineers</span>
          <span>$8–80k engagements</span>
          <span>remote, EU + east coast</span>
        </div>
      </div>

      <DeployTicker />
    </section>
  );
}
window.Hero = Hero;
