/* Hero — animated bypass diagram + live terminal */

const { useState, useEffect, useRef } = React;

/* ---------- animated bypass diagram ---------- */
function BypassDiagram() {
  // Phase cycle (0..3) drives the packet animation:
  //   0 → request leaving app          → step 1 active
  //   1 → unblocker pulses, hand-off   → step 2 active
  //   2 → unblocker fires through wall → step 2 active
  //   3 → response returns to app      → step 3 active
  const [phase, setPhase] = useState(0);
  const [paused, setPaused] = useState(false);

  useEffect(() => {
    if (paused) return;
    const id = setInterval(() => setPhase((p) => (p + 1) % 4), 1400);
    return () => clearInterval(id);
  }, [paused]);

  const activeStep = phase === 0 ? 1 : phase === 3 ? 3 : 2;

  return (
    <div
      className="diagram-wrap"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      <div className="diagram" aria-hidden="true">
        {/* APP card top-left */}
        <div className="diagram-card dg-app">
          <span className="step-badge">1</span>
          <div className="head">
            <span className="tl"><span></span><span></span><span></span></span>
            <span>your_app.ts</span>
          </div>
          <div className="body">
            <div className="req">
              <span className="k">await</span> unblocker.<span className="k">get</span>(<br />
              &nbsp;&nbsp;<span className="s">"azure.microsoft.com/…"</span><br />
              )
            </div>
          </div>
        </div>

        {/* WALL right side */}
        <div className="diagram-card dg-wall">
          <span className="step-badge danger">2</span>
          <div className="wall-label">⛔ Anti-bot layer</div>
          <div className="waf-stack">
            <div className="waf-row"><span className="badge">CF</span> Cloudflare <span className="x">×</span></div>
            <div className="waf-row"><span className="badge">DD</span> DataDome <span className="x">×</span></div>
            <div className="waf-row"><span className="badge">AK</span> Akamai <span className="x">×</span></div>
            <div className="waf-row"><span className="badge">KS</span> Kasada <span className="x">×</span></div>
          </div>
          <div style={{
            fontFamily: "var(--font-mono)", fontSize: 9, color: "#ff7777",
            letterSpacing: "0.08em", textTransform: "uppercase", textAlign: "right"
          }}>
            target site
          </div>
        </div>

        {/* RESPONSE card bottom-left */}
        <div className="diagram-card dg-response">
          <span className="step-badge ok">3</span>
          <div className="head">
            <span className="tl"><span></span><span></span><span></span></span>
            <span>response.json</span>
          </div>
          <div className="body">
            <div className="resp-line">
              <span>200 OK</span><span className="ok">✓</span>
            </div>
            <div className="resp-line">
              <span>1.18s · 178 KB</span><span className="ok">✓</span>
            </div>
            <div className="resp-line">
              <span style={{ color: "var(--text-dim)" }}>html: &lt;!DOCTYPE…</span>
            </div>
          </div>
        </div>

        {/* CENTER node — Unblocker */}
        <div className="dg-unblocker" style={{
          boxShadow: phase === 1
            ? "0 0 0 6px rgba(56,120,255,0.16), 0 0 0 16px rgba(56,120,255,0.08), 0 0 80px rgba(56,120,255,0.6)"
            : "0 0 0 6px rgba(56,120,255,0.08), 0 0 0 14px rgba(56,120,255,0.04), 0 0 60px var(--accent-glow)",
          transition: "box-shadow .35s ease"
        }}>
          <div className="ub-inner">
            <span className="glyph">Unblocker</span>
            bypass · live
          </div>
        </div>

        {/* WIRES + packets */}
        <svg className="dg-wires" viewBox="0 0 600 580" preserveAspectRatio="none">
          <defs>
            <linearGradient id="wireGrad" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0%" stopColor="#3878ff" stopOpacity="0" />
              <stop offset="50%" stopColor="#3878ff" stopOpacity="0.6" />
              <stop offset="100%" stopColor="#3878ff" stopOpacity="0" />
            </linearGradient>
            <linearGradient id="wireOk" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#28c267" stopOpacity="0.7" />
              <stop offset="100%" stopColor="#28c267" stopOpacity="0" />
            </linearGradient>
          </defs>

          <path d="M 200 90 Q 240 130 290 250" stroke="#2a3444" strokeWidth="1.5" strokeDasharray="4 4" fill="none" />
          <path d="M 370 280 Q 430 280 470 280" stroke="#2a3444" strokeWidth="1.5" strokeDasharray="4 4" fill="none" />
          <path d="M 470 320 Q 430 340 370 320" stroke="rgba(40,194,103,0.4)" strokeWidth="1.5" strokeDasharray="4 4" fill="none" />
          <path d="M 280 320 Q 240 400 200 470" stroke="rgba(40,194,103,0.4)" strokeWidth="1.5" strokeDasharray="4 4" fill="none" />

          {/* Packet 1: app → unblocker */}
          <g style={{ opacity: phase === 0 && !paused ? 1 : 0, transition: "opacity .15s ease" }}>
            <circle r="5" className="packet">
              <animateMotion dur="1.4s" repeatCount="indefinite" keyPoints="0;1" keyTimes="0;1"
                path="M 200 90 Q 240 130 290 250" />
            </circle>
          </g>
          {/* Packet 2: unblocker → wall */}
          <g style={{ opacity: phase === 2 && !paused ? 1 : 0, transition: "opacity .15s ease" }}>
            <circle r="5" className="packet">
              <animateMotion dur="1.4s" repeatCount="indefinite" keyPoints="0;1" keyTimes="0;1"
                path="M 370 280 Q 430 280 580 280" />
            </circle>
          </g>
          {/* Packet 3: response back from wall → unblocker → response.json */}
          <g style={{ opacity: phase === 3 && !paused ? 1 : 0, transition: "opacity .15s ease" }}>
            <circle r="5" fill="#28c267" style={{ filter: "drop-shadow(0 0 6px #28c267)" }}>
              <animateMotion dur="1.4s" repeatCount="indefinite" keyPoints="0;0.45;0.55;1" keyTimes="0;0.45;0.55;1"
                path="M 580 320 Q 430 340 290 320 L 280 320 Q 240 400 200 470" />
            </circle>
          </g>
        </svg>

        {paused && <span className="diagram-pause-tip mono">paused · move cursor away to resume</span>}
      </div>

      <div className="diagram-steps">
        <span className={"step-pill" + (activeStep === 1 ? " is-active" : "")}>
          <span className="num">01</span>
          <span>Request</span>
        </span>
        <span className="step-arrow">→</span>
        <span className={"step-pill" + (activeStep === 2 ? " is-active" : "")}>
          <span className="num">02</span>
          <span>Bypass</span>
        </span>
        <span className="step-arrow">→</span>
        <span className={"step-pill" + (activeStep === 3 ? " is-active" : "")}>
          <span className="num">03</span>
          <span>Clean HTML</span>
        </span>
      </div>
    </div>
  );
}

/* ---------- live terminal ---------- */
const CODE_SAMPLES = {
  js: [
    { t: "// 1 — call Unblocker, get any URL", cls: "c-c" },
    { t: "const ", cls: "c-k" }, { t: "res", cls: "c-p" }, { t: " = " }, { t: "await ", cls: "c-k" },
    { t: "makeStringUnblockerRequest", cls: "c-f" }, { t: "({" },
    { t: "\n  url: ", cls: "" }, { t: '"https://azure.microsoft.com/api/v3/pricing/…"', cls: "c-s" },
    { t: "\n});" },
    { t: "\n\n// 2 — done. that's it.", cls: "c-c" },
    { t: "\nconsole.", cls: "" }, { t: "log", cls: "c-f" }, { t: "(", cls: "" }, { t: "res", cls: "c-p" }, { t: ".", cls: "" }, { t: "html", cls: "c-n" }, { t: ");" }
  ],
  py: [
    { t: "# 1 — same endpoint, just python", cls: "c-c" },
    { t: "\nimport ", cls: "c-k" }, { t: "unblocker", cls: "c-p" },
    { t: "\n\nres ", cls: "" }, { t: "= ", cls: "c-k" }, { t: "unblocker.", cls: "" }, { t: "get", cls: "c-f" }, { t: "(", cls: "" },
    { t: '\n    url=' }, { t: '"https://walmart.com/ip/…"', cls: "c-s" },
    { t: "\n)" },
    { t: "\n\nprint", cls: "c-f" }, { t: "(res.", cls: "" }, { t: "html", cls: "c-n" }, { t: ")" }
  ],
  curl: [
    { t: "# straight HTTP, anywhere", cls: "c-c" },
    { t: "\ncurl ", cls: "c-f" }, { t: "https://api.usestring.ai/v1/unblock", cls: "c-s" },
    { t: "\n  -H ", cls: "" }, { t: '"Authorization: Bearer $STRING_KEY"', cls: "c-s" },
    { t: "\n  -d ", cls: "" }, { t: '\'{"url":"https://indeed.com/jobs?q=…"}\'', cls: "c-s" }
  ]
};

const OUTPUT_LINES = [
  { t: "→", cls: "c-dim" }, { t: " POST /v1/unblock", cls: "" }, { t: "\n← ", cls: "c-dim" },
  { t: "200 OK", cls: "c-ok" }, { t: "  ", cls: "" }, { t: "1.18s", cls: "c-dim" }, { t: "  ", cls: "" }, { t: "178 KB", cls: "c-dim" },
  { t: "\n  status: ", cls: "c-dim" }, { t: '"unblocked"', cls: "c-s" },
  { t: "\n  defense: ", cls: "c-dim" }, { t: '"datadome"', cls: "c-s" }, { t: " ", cls: "" }, { t: "✓ bypassed", cls: "c-ok" },
  { t: "\n  html: ", cls: "c-dim" }, { t: '"<!DOCTYPE html><html lang=\\"en\\">…"', cls: "c-s" }
];

function CodeTerminal() {
  const [lang, setLang] = useState("js");
  const [typed, setTyped] = useState(0);
  const [showOutput, setShowOutput] = useState(false);
  const [outputTyped, setOutputTyped] = useState(0);

  // Compute total chars for current sample
  const sample = CODE_SAMPLES[lang];
  const fullText = sample.map(s => s.t).join("");
  const outputFull = OUTPUT_LINES.map(s => s.t).join("");

  useEffect(() => {
    setTyped(0);
    setShowOutput(false);
    setOutputTyped(0);
  }, [lang]);

  useEffect(() => {
    if (typed >= fullText.length) {
      const t = setTimeout(() => setShowOutput(true), 500);
      return () => clearTimeout(t);
    }
    const id = setTimeout(() => setTyped((n) => n + 1), 18);
    return () => clearTimeout(id);
  }, [typed, fullText.length]);

  useEffect(() => {
    if (!showOutput) return;
    if (outputTyped >= outputFull.length) {
      // restart after delay
      const t = setTimeout(() => {
        setTyped(0); setShowOutput(false); setOutputTyped(0);
      }, 3500);
      return () => clearTimeout(t);
    }
    const id = setTimeout(() => setOutputTyped((n) => n + 1), 8);
    return () => clearTimeout(id);
  }, [showOutput, outputTyped, outputFull.length]);

  // Render typed slice across segments
  const renderTyped = (segments, limit) => {
    let used = 0;
    return segments.map((seg, i) => {
      if (used >= limit) return null;
      const remaining = limit - used;
      const chunk = seg.t.slice(0, remaining);
      used += chunk.length;
      return <span key={i} className={seg.cls || ""}>{chunk}</span>;
    });
  };

  return (
    <div className="code-card">
      <div className="code-head">
        <span className="lights"><span className="r"></span><span className="y"></span><span className="g"></span></span>
        <span className="tab">scrape.{lang === "py" ? "py" : lang === "curl" ? "sh" : "ts"}</span>
        <span className="status">
          {showOutput ? <span style={{ color: "var(--success)" }}>● live</span> : <span style={{ color: "var(--accent-2)" }}>● ready</span>}
        </span>
      </div>
      <div className="lang-tabs">
        {["js", "py", "curl"].map((k) => (
          <button key={k} className={"lang-tab" + (lang === k ? " active" : "")} onClick={() => setLang(k)}>
            {k === "js" ? "JavaScript" : k === "py" ? "Python" : "cURL"}
          </button>
        ))}
      </div>
      <div className="code-body">
        {renderTyped(sample, typed)}
        {typed < fullText.length && <span className="cursor-blink" />}
        {showOutput && (
          <>
            {"\n\n"}
            <span className="c-dim">────────  output  ────────</span>
            {"\n"}
            {renderTyped(OUTPUT_LINES, outputTyped)}
            {outputTyped < outputFull.length && <span className="cursor-blink" />}
          </>
        )}
      </div>
    </div>
  );
}

/* ---------- the section ---------- */
function HeroSection() {
  return (
    <section className="hero" data-screen-label="Hero">
      <div className="bg-glow" />
      <div className="bg-dots" />
      <div className="container">
        <div className="hero-grid">
          <div className="hero-copy">
            <div className="eyebrow">
              <span className="dot"></span>
              Q2 2026 benchmark · 97.1% success
            </div>
            <h1>
              Any page.<br />
              No matter who's <span className="grad-text">guarding it.</span>
            </h1>
            <p className="lead lg">
              String Unblocker bypasses Cloudflare, DataDome, Akamai &amp; Kasada with one HTTP call.
              Pay only when we return content — no captchas, no false charges, no headless browser to babysit.
            </p>
            <div className="hero-actions">
              <a className="btn primary lg" href="https://portal.usestring.ai/unblocker">
                Try now for free <span className="arr">→</span>
              </a>
              <a className="btn lg" href="#benchmark">
                See the benchmark
              </a>
            </div>
            <div className="hero-trust">
              <span className="chip success"><span className="dot"></span>Pay per success</span>
              <span className="chip"><span className="dot"></span>Universal HTTP</span>
              <span className="chip"><span className="dot"></span>Native AI inference</span>
            </div>
          </div>
          <BypassDiagram />
        </div>

        {/* Sub-hero: terminal */}
        <div style={{ marginTop: 64, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32, alignItems: "center" }} className="hero-terminal">
          <div>
            <span className="eyebrow"><span className="dot"></span>The whole API</span>
            <h2 style={{ marginTop: 16, fontSize: 38 }}>One call. Then your scraper just&nbsp;works.</h2>
            <p className="lead" style={{ marginTop: 16 }}>
              The endpoint takes a URL and returns rendered HTML. Drop it in wherever you fetch.
              No proxy rotation, no browser farm, no anti-bot research.
            </p>
            <ul style={{ marginTop: 18, paddingLeft: 0, listStyle: "none", display: "grid", gap: 10 }}>
              <li style={{ display: "flex", gap: 10, color: "var(--text-dim)" }}>
                <span style={{ color: "var(--accent-2)" }}>→</span> Same shape as the providers you already use — drop-in switch.
              </li>
              <li style={{ display: "flex", gap: 10, color: "var(--text-dim)" }}>
                <span style={{ color: "var(--accent-2)" }}>→</span> Returns full rendered HTML, JS-executed.
              </li>
              <li style={{ display: "flex", gap: 10, color: "var(--text-dim)" }}>
                <span style={{ color: "var(--accent-2)" }}>→</span> Optional structured-data extraction in-flight.
              </li>
            </ul>
          </div>
          <CodeTerminal />
        </div>
      </div>

      <style>{`
        @media (max-width: 960px) {
          .hero-terminal { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

window.HeroSection = HeroSection;
window.BypassDiagram = BypassDiagram;
window.CodeTerminal = CodeTerminal;
