/* BrieflySec marketing — animated hero pipeline (React via Babel CDN). */
(function () {
  const { useState, useEffect, useRef } = React;

  const SOURCES = [
    { id: "thn",   name: "Hacker News",        glyph: "H", bg: "#f97316" },
    { id: "dr",    name: "Dark Reading",       glyph: "D", bg: "#dc2626" },
    { id: "p0",    name: "Project Zero",       glyph: "0", bg: "#0d9488" },
    { id: "talos", name: "Cisco Talos",        glyph: "T", bg: "#1e40af" },
    { id: "mand",  name: "Mandiant",           glyph: "M", bg: "#c2410c" },
    { id: "cs",    name: "CrowdStrike",        glyph: "C", bg: "#dc2626" },
    { id: "msrc",  name: "Microsoft Security", glyph: "M", bg: "#2563eb" },
    { id: "u42",   name: "Unit 42",            glyph: "4", bg: "#ea580c" },
    { id: "cisa",  name: "CISA",               glyph: "★", bg: "#1d4ed8" },
    { id: "cf",    name: "Cloudflare",         glyph: "C", bg: "#f97316" },
    { id: "tob",   name: "Trail of Bits",      glyph: "B", bg: "#be185d" },
    { id: "wtwr",  name: "watchTowr",          glyph: "W", bg: "#7c2d12" },
  ];

  const STORY_POOL = [
    { score: 9.4, src: "The Hacker News",  title: "Critical RCE in OpenSSH Affects 14M Internet-Facing Servers", tags: ["rce", "cve-2024", "tier-1"] },
    { score: 9.1, src: "Project Zero",     title: "Apple Issues Emergency Update for Actively Exploited WebKit 0-day", tags: ["apple", "0day", "webkit"] },
    { score: 8.7, src: "Cloudflare Blog",  title: "Cloudflare Mitigates Largest-Ever 3.8 Tbps DDoS Attack on Record", tags: ["ddos", "cloudflare"] },
    { score: 8.1, src: "MSRC",             title: "Patch Tuesday: 51 CVEs Fixed, 3 Zero-Days Under Active Exploitation", tags: ["patch-tuesday", "0day"] },
    { score: 7.6, src: "Project Zero",     title: "18-Month-Old Samsung Kernel UAF Disclosed After Vendor Inaction", tags: ["android", "kernel"] },
    { score: 7.3, src: "CISA",             title: "CISA Adds Apache HTTP Server Vulnerability to Known Exploited List", tags: ["cisa", "kev"] },
    { score: 6.4, src: "Mandiant",         title: "UNC5174 Campaign Exploits CVE-2024-1709 Against Federal Targets", tags: ["apt", "unc5174"] },
    { score: 5.8, src: "The Record",       title: "Citizen Lab Documents NSO Group Pegasus Targeting Journalists", tags: ["pegasus", "spyware"] },
    { score: 4.2, src: "Securelist",       title: "Operation Triangulation Toolchain Analyzed in Full Technical Detail", tags: ["apt", "ios"] },
    { score: 3.1, src: "NIST",             title: "NIST Updates Cybersecurity Framework to Version 2.0 With Govern Function", tags: ["nist", "framework"] },
  ];

  const severity = (s) => (s >= 9 ? "red" : s >= 7 ? "orange" : s >= 4 ? "green" : "blue");

  function HeroPipeline({ speed = 1 }) {
    const [sourceWindow, setSourceWindow] = useState(() => SOURCES.slice(0, 8));
    const [activeSourceIdx, setActiveSourceIdx] = useState(2);
    const [score, setScore] = useState(8.4);
    const [processed, setProcessed] = useState(91);
    const [stories, setStories] = useState(() => [
      { ...STORY_POOL[0], _k: 1 },
      { ...STORY_POOL[2], _k: 2 },
      { ...STORY_POOL[5], _k: 3 },
    ]);
    const tickRef = useRef(0);
    const storyKeyRef = useRef(4);
    const linesRef = useRef(null);
    const sourceRowRefs = useRef({});
    const rankerRef = useRef(null);
    const stackRef = useRef(null);
    const [linePath, setLinePath] = useState({ a: "", b: "" });

    useEffect(() => {
      const interval = setInterval(() => {
        tickRef.current += 1;
        const t = tickRef.current;
        setActiveSourceIdx(Math.floor(Math.random() * sourceWindow.length));
        setTimeout(() => {
          setStories(prev => {
            const next = { ...STORY_POOL[Math.floor(Math.random() * STORY_POOL.length)], _k: storyKeyRef.current++ };
            return [next, ...prev].slice(0, 3);
          });
          setScore(parseFloat((4 + Math.random() * 5.5).toFixed(1)));
          setProcessed(p => p + (Math.random() < 0.4 ? 1 : 0));
        }, 600 / speed);
        if (t % 5 === 0) {
          setSourceWindow(prev => {
            const next = [...prev];
            const newSrc = SOURCES[Math.floor(Math.random() * SOURCES.length)];
            next[Math.floor(Math.random() * next.length)] = newSrc;
            return next;
          });
        }
      }, 2200 / speed);
      return () => clearInterval(interval);
    }, [speed, sourceWindow.length]);

    useEffect(() => {
      const measure = () => {
        const container = linesRef.current?.parentElement;
        if (!container || !rankerRef.current) return;
        const cb = container.getBoundingClientRect();
        const rb = rankerRef.current.getBoundingClientRect();
        const rx = rb.left + rb.width / 2 - cb.left;
        const ry = rb.top + rb.height / 2 - cb.top;
        const activeKey = sourceWindow[activeSourceIdx]?.id;
        const srcEl = sourceRowRefs.current[activeKey];
        let aPath = "";
        if (srcEl) {
          const sb = srcEl.getBoundingClientRect();
          const sx = sb.right - cb.left;
          const sy = sb.top + sb.height / 2 - cb.top;
          const midX = (sx + rx) / 2;
          aPath = `M ${sx} ${sy} C ${midX} ${sy}, ${midX} ${ry}, ${rx} ${ry}`;
        }
        let bPath = "";
        if (stackRef.current) {
          const fb = stackRef.current.querySelector(".story-card-mini")?.getBoundingClientRect();
          if (fb) {
            const tx = fb.left - cb.left;
            const ty = fb.top + fb.height / 2 - cb.top;
            const midX = (rx + tx) / 2;
            bPath = `M ${rx} ${ry} C ${midX} ${ry}, ${midX} ${ty}, ${tx} ${ty}`;
          }
        }
        setLinePath({ a: aPath, b: bPath });
      };
      measure();
      window.addEventListener("resize", measure);
      return () => window.removeEventListener("resize", measure);
    }, [activeSourceIdx, sourceWindow, stories]);

    const sev = severity(score);

    return (
      <div className="pipeline">
        <div className="pipeline-chrome">
          <div className="left">
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--risk-green)", boxShadow: "0 0 6px var(--risk-green)" }}></span>
            <span>LIVE_INGEST</span>
          </div>
          <div className="right mono">brieflysec.com/feed</div>
        </div>
        <div className="pipeline-stage">
          <svg ref={linesRef} className="pipe-lines">
            <defs>
              <linearGradient id="lineGradA" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0%" stopColor="rgba(129, 207, 255, 0)"/>
                <stop offset="40%" stopColor="rgba(129, 207, 255, 0.5)"/>
                <stop offset="100%" stopColor="rgba(129, 207, 255, 0.9)"/>
              </linearGradient>
              <linearGradient id="lineGradB" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0%" stopColor="rgba(129, 207, 255, 0.9)"/>
                <stop offset="60%" stopColor="rgba(129, 207, 255, 0.4)"/>
                <stop offset="100%" stopColor="rgba(129, 207, 255, 0)"/>
              </linearGradient>
            </defs>
            {linePath.a && (
              <g>
                <path d={linePath.a} fill="none" stroke="rgba(129, 207, 255, 0.15)" strokeWidth="1" strokeDasharray="3 3"/>
                <path d={linePath.a} fill="none" stroke="url(#lineGradA)" strokeWidth="1.5" strokeLinecap="round">
                  <animate attributeName="stroke-dasharray" from="0,200" to="200,0" dur="0.9s" fill="freeze"/>
                </path>
                <circle r="3" fill="var(--primary)" filter="drop-shadow(0 0 5px var(--primary))">
                  <animateMotion dur="0.9s" repeatCount="1" path={linePath.a}/>
                </circle>
              </g>
            )}
            {linePath.b && (
              <g>
                <path d={linePath.b} fill="none" stroke="rgba(129, 207, 255, 0.15)" strokeWidth="1" strokeDasharray="3 3"/>
                <path d={linePath.b} fill="none" stroke="url(#lineGradB)" strokeWidth="1.5" strokeLinecap="round" style={{ animation: "fade-line 1.4s ease both 0.5s" }}/>
                <circle r="3" fill="var(--primary)" filter="drop-shadow(0 0 5px var(--primary))">
                  <animateMotion dur="0.7s" begin="0.6s" repeatCount="1" path={linePath.b}/>
                </circle>
              </g>
            )}
          </svg>
          <div className="pipe-col">
            <div className="pipe-col-label"><span>Sources</span><span className="count">90+</span></div>
            <div className="source-list">
              {sourceWindow.map((s, idx) => (
                <div
                  key={s.id + "-" + idx}
                  ref={el => sourceRowRefs.current[s.id] = el}
                  className={"source-row" + (idx === activeSourceIdx ? " active" : "")}>
                  <div className="fav" style={{ background: s.bg }}>{s.glyph}</div>
                  <div className="name">{s.name}</div>
                  <div className="pulse"></div>
                </div>
              ))}
            </div>
          </div>
          <div className="ranker">
            <div className="ranker-core" ref={rankerRef}>
              <div className="ranker-ring"></div>
              <div className="ranker-ring r2"></div>
              <div className="ranker-ring r3"></div>
              <div className="ranker-inner">
                <span className="label">Signal</span>
                <span className="num" style={{ color: `var(--risk-${sev})` }}>{score.toFixed(1)}</span>
                <span className="sub">/ 10.0</span>
              </div>
            </div>
          </div>
          <div className="pipe-col">
            <div className="pipe-col-label"><span>Ranked Today</span><span className="count mono">{processed.toLocaleString()}</span></div>
            <div className="story-stack" ref={stackRef}>
              {stories.map(st => {
                const sv = severity(st.score);
                return (
                  <div key={st._k} className={"story-card-mini enter " + sv}>
                    <div className="head">
                      <span className={"score-pill " + sv}>{st.score.toFixed(1)}</span>
                      <span className="src">{st.src}</span>
                      <span className="time">2m</span>
                    </div>
                    <div className="title">{st.title}</div>
                    <div className="tags">
                      {st.tags.slice(0, 3).map(t => <span key={t} className="tag-mini">{t}</span>)}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
        <style>{`@keyframes fade-line { 0% { opacity: 0; } 30% { opacity: 1; } 100% { opacity: 0; } }`}</style>
      </div>
    );
  }

  const mountEl = document.getElementById("hero-pipeline");
  if (mountEl) ReactDOM.createRoot(mountEl).render(<HeroPipeline speed={1} />);
})();
