/* eslint-disable */
// Hero — massive type + 3D wireframe sphere + LIVE AI demo

const { useState: _hUS, useEffect: _hUE, useRef: _hUR } = React;

/* Neural network — nodes, dense synaptic connections, firing pulses */
function ParticleField() {
  const ref = _hUR(null);
  _hUE(() => {
    const cvs = ref.current; if (!cvs) return;
    const ctx = cvs.getContext("2d");
    let raf, w, h, dpr;
    let nodes = [];
    let edges = [];
    let pulses = []; // synapse firings
    let waves = []; // resonance waves
    let mouse = { x: -9999, y: -9999, lastFire: 0 };
    let time = 0;
    let lastResonance = 0;

    function rebuild() {
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      w = cvs.clientWidth; h = cvs.clientHeight;
      cvs.width = w * dpr; cvs.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

      // Build node cloud with loose layered structure
      nodes = [];
      const target = Math.min(280, Math.floor((w * h) / 5500));
      for (let i = 0; i < target; i++) {
        // Mix: 65% center-biased, 35% loose layers (left/right)
        let x, y;
        if (Math.random() < 0.65) {
          const r = Math.pow(Math.random(), 0.65) * Math.min(w, h) * 0.55;
          const a = Math.random() * Math.PI * 2;
          x = w / 2 + Math.cos(a) * r;
          y = h / 2 + Math.sin(a) * r * 0.72;
        } else {
          // Loose layer column
          const cols = 5;
          const col = Math.floor(Math.random() * cols);
          x = (col + 0.5 + (Math.random() - 0.5) * 0.7) * (w / cols);
          y = Math.random() * h;
        }
        nodes.push({
          x, y,
          ox: x, oy: y,
          vx: 0, vy: 0,
          z: 0.3 + Math.random() * 0.7,
          phase: Math.random() * Math.PI * 2,
          baseR: 1.0 + Math.random() * 1.8,
          red: Math.random() < 0.12,
          hub: Math.random() < 0.04, // ~4% hub nodes (bigger, more connections)
          activity: 0,
          firing: 0,
        });
      }

      // Build edges — hubs get more connections; regular nodes 5
      const MAX_D = 150;
      edges = [];
      for (let i = 0; i < nodes.length; i++) {
        const cap = nodes[i].hub ? 10 : 5;
        const candidates = [];
        for (let j = 0; j < nodes.length; j++) {
          if (i === j) continue;
          const dx = nodes[i].x - nodes[j].x;
          const dy = nodes[i].y - nodes[j].y;
          const d = Math.hypot(dx, dy);
          if (d < MAX_D) candidates.push({ j, d });
        }
        candidates.sort((a, b) => a.d - b.d);
        for (const c of candidates.slice(0, cap)) {
          if (c.j > i) edges.push({ a: i, b: c.j, d: c.d });
        }
      }
    }
    rebuild();
    window.addEventListener("resize", rebuild);

    function onMove(e) {
      const r = cvs.getBoundingClientRect();
      const nx = e.clientX - r.left, ny = e.clientY - r.top;
      mouse.x = nx; mouse.y = ny;
      // Occasionally fire the nearest node from the cursor
      if (time - mouse.lastFire > 0.12) {
        mouse.lastFire = time;
        let best = -1, bestD = 1e9;
        for (let i = 0; i < nodes.length; i++) {
          const dx = nodes[i].x - nx, dy = nodes[i].y - ny;
          const d = dx * dx + dy * dy;
          if (d < bestD) { bestD = d; best = i; }
        }
        if (best >= 0 && bestD < 28000) {
          nodes[best].activity = 1;
          nodes[best].firing = 1;
          // Fire pulses out from this node along its edges
          const out = edges.filter(e => e.a === best || e.b === best);
          for (const e of out.slice(0, 3)) {
            if (pulses.length < 60) {
              pulses.push({
                edge: e,
                forward: e.a === best,
                progress: 0,
                life: 35 + Math.random() * 20,
                red: true,
              });
            }
          }
        }
      }
    }
    function onLeave() { mouse.x = -9999; mouse.y = -9999; }
    window.addEventListener("mousemove", onMove);
    cvs.addEventListener("mouseleave", onLeave);

    function frame(t) {
      time = t / 1000;
      ctx.clearRect(0, 0, w, h);

      // Soft red ambient glow centered (radial breath)
      const breathPct = 0.5 + 0.5 * Math.sin(time * 0.3);
      const glow = ctx.createRadialGradient(w/2, h/2, 0, w/2, h/2, Math.min(w,h) * (0.7 + breathPct * 0.1));
      glow.addColorStop(0, `rgba(204,12,32,${0.10 + breathPct * 0.06})`);
      glow.addColorStop(0.45, "rgba(204,12,32,0.04)");
      glow.addColorStop(1, "rgba(204,12,32,0)");
      ctx.fillStyle = glow;
      ctx.fillRect(0, 0, w, h);

      // Periodic resonance — whole network flashes
      if (time - lastResonance > 8 + Math.random() * 6) {
        lastResonance = time;
        waves.push({ x: w / 2, y: h / 2, r: 0, life: 1, red: true });
      }
      // Draw + update waves
      waves = waves.filter((wv) => {
        wv.r += 6;
        wv.life -= 0.012;
        if (wv.life <= 0) return false;
        ctx.beginPath();
        ctx.arc(wv.x, wv.y, wv.r, 0, Math.PI * 2);
        ctx.strokeStyle = `rgba(204,12,32,${wv.life * 0.4})`;
        ctx.lineWidth = 1.2;
        ctx.stroke();
        // Activate nodes the wave passes through
        for (const n of nodes) {
          const d = Math.hypot(n.x - wv.x, n.y - wv.y);
          if (Math.abs(d - wv.r) < 8) {
            n.activity = Math.min(1, n.activity + 0.35);
          }
        }
        return true;
      });

      // Update nodes — drift around origin, react to cursor
      for (const n of nodes) {
        const breath = Math.sin(time * 0.6 + n.phase) * 6;
        const tx = n.ox + Math.cos(time * 0.3 + n.phase) * (6 + n.z * 8);
        const ty = n.oy + Math.sin(time * 0.4 + n.phase) * (4 + n.z * 6) + breath * 0.4;

        // Spring back to drift target
        n.vx += (tx - n.x) * 0.012;
        n.vy += (ty - n.y) * 0.012;
        n.vx *= 0.88;
        n.vy *= 0.88;
        n.x += n.vx;
        n.y += n.vy;
        n.activity *= 0.94;
      }

      // Draw edges (synaptic connections) — varied opacity by distance + node depth
      ctx.lineWidth = 0.55;
      for (const e of edges) {
        const a = nodes[e.a], b = nodes[e.b];
        const dx = a.x - b.x, dy = a.y - b.y;
        const d = Math.hypot(dx, dy);
        if (d > 160) continue;
        const baseAlpha = (1 - d / 160) * 0.30 * Math.min(a.z, b.z);
        const activity = Math.max(a.activity, b.activity);
        const isRedish = a.red || b.red;
        if (isRedish || activity > 0.05) {
          ctx.strokeStyle = `rgba(204,12,32,${baseAlpha * 1.6 + activity * 0.6})`;
          ctx.lineWidth = 0.8 + activity * 1.4;
        } else {
          ctx.strokeStyle = `rgba(255,255,255,${baseAlpha})`;
          ctx.lineWidth = 0.55;
        }
        ctx.beginPath();
        ctx.moveTo(a.x, a.y);
        ctx.lineTo(b.x, b.y);
        ctx.stroke();
      }

      // Spawn pulses — more frequent
      if (Math.random() < 0.45 && pulses.length < 50) {
        const startEdge = edges[Math.floor(Math.random() * edges.length)];
        if (startEdge) {
          const forward = Math.random() < 0.5;
          pulses.push({
            edge: startEdge,
            forward,
            progress: 0,
            life: 40 + Math.random() * 30,
            red: nodes[startEdge.a].red || nodes[startEdge.b].red || Math.random() < 0.55,
          });
        }
      }

      // Advance pulses — leave a glowing trail behind
      pulses = pulses.filter((p) => {
        p.progress += 1 / p.life;
        if (p.progress >= 1) {
          const dest = p.forward ? nodes[p.edge.b] : nodes[p.edge.a];
          dest.activity = Math.min(1, dest.activity + 0.7);
          dest.firing = 1;
          // Higher chain rate for chained firing
          if (Math.random() < 0.55) {
            const next = edges.filter(e =>
              (e.a === (p.forward ? p.edge.b : p.edge.a)
              || e.b === (p.forward ? p.edge.b : p.edge.a))
              && e !== p.edge
            );
            if (next.length && pulses.length < 60) {
              const ne = next[Math.floor(Math.random() * next.length)];
              const fwd = ne.a === (p.forward ? p.edge.b : p.edge.a);
              pulses.push({
                edge: ne,
                forward: fwd,
                progress: 0,
                life: 40 + Math.random() * 25,
                red: p.red || Math.random() < 0.45,
              });
            }
          }
          return false;
        }
        const a = p.forward ? nodes[p.edge.a] : nodes[p.edge.b];
        const b = p.forward ? nodes[p.edge.b] : nodes[p.edge.a];
        // Draw a short trail of fading dots behind the head
        const TAIL = 5;
        for (let k = 0; k < TAIL; k++) {
          const tp = p.progress - k * 0.04;
          if (tp < 0) continue;
          const x = a.x + (b.x - a.x) * tp;
          const y = a.y + (b.y - a.y) * tp;
          const fade = Math.sin(p.progress * Math.PI) * (1 - k / TAIL);
          const sz = (2.6 - k * 0.3) * fade + 0.4;
          ctx.beginPath();
          ctx.arc(x, y, Math.max(0.2, sz), 0, Math.PI * 2);
          if (p.red) {
            ctx.fillStyle = `rgba(204,12,32,${fade})`;
            ctx.shadowColor = "rgba(204,12,32,0.95)";
            ctx.shadowBlur = 14 * fade;
          } else {
            ctx.fillStyle = `rgba(255,255,255,${fade})`;
            ctx.shadowColor = "rgba(255,255,255,0.6)";
            ctx.shadowBlur = 10 * fade;
          }
          ctx.fill();
        }
        ctx.shadowBlur = 0;
        return true;
      });

      // Draw nodes on top — hubs get halo rings, firing nodes flash
      for (const n of nodes) {
        const breath = 0.7 + 0.3 * Math.sin(time * 1.4 + n.phase);
        const sz = n.baseR * (n.hub ? 1.8 : 1) * (0.7 + n.z * 1.1) * breath + n.activity * 2.2;
        const alpha = (0.35 + n.z * 0.55) * breath + n.activity * 0.3;

        // Firing flash — bright ring expanding
        if (n.firing > 0.05) {
          const ringSz = sz + (1 - n.firing) * 16;
          ctx.beginPath();
          ctx.arc(n.x, n.y, ringSz, 0, Math.PI * 2);
          ctx.strokeStyle = `rgba(204,12,32,${n.firing * 0.6})`;
          ctx.lineWidth = 1.2;
          ctx.stroke();
          n.firing *= 0.88;
        }

        // Hub halo
        if (n.hub) {
          ctx.beginPath();
          ctx.arc(n.x, n.y, sz + 5, 0, Math.PI * 2);
          ctx.strokeStyle = `rgba(204,12,32,${0.25 + n.activity * 0.3})`;
          ctx.lineWidth = 0.8;
          ctx.stroke();
        }

        // Node itself
        if (n.red || n.hub || n.activity > 0.15) {
          ctx.fillStyle = `rgba(204,12,32,${Math.min(1, alpha + n.activity * 0.4)})`;
          ctx.shadowColor = "rgba(204,12,32,0.95)";
          ctx.shadowBlur = sz * 4 * ((n.red || n.hub) ? 1 : n.activity);
        } else {
          ctx.fillStyle = `rgba(255,255,255,${alpha * 0.9})`;
          ctx.shadowBlur = 0;
        }
        ctx.beginPath();
        ctx.arc(n.x, n.y, sz, 0, Math.PI * 2);
        ctx.fill();
        ctx.shadowBlur = 0;
      }

      // Floating data fragments — random tiny binary/hex labels
      const FRAG_COUNT = 18;
      for (let k = 0; k < FRAG_COUNT; k++) {
        const seed = Math.sin(k * 21.3) * 10000;
        const px = ((seed % w) + w) % w;
        const py = (((seed * 2.7) % h) + h) % h;
        const t2 = (time * 0.3 + k * 0.5) % 6;
        const fade = Math.max(0, Math.sin(t2 * Math.PI / 6)) * 0.35;
        if (fade < 0.05) continue;
        ctx.font = "10px 'JetBrains Mono', monospace";
        ctx.fillStyle = `rgba(204,12,32,${fade})`;
        const chars = ["0x4F", "1.01", "NN", "AI/F", "0xCC", "net", "01101", "σ", "∂"];
        ctx.fillText(chars[k % chars.length], px, py);
      }

      // Decay node activity
      for (const n of nodes) {
        n.activity *= 0.94;
      }

      raf = requestAnimationFrame(frame);
    }
    raf = requestAnimationFrame(frame);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", rebuild);
      window.removeEventListener("mousemove", onMove);
      cvs.removeEventListener("mouseleave", onLeave);
    };
  }, []);
  return <canvas id="hero-canvas" ref={ref} />;
}

/* The killer interaction — live AI consultation */
function LiveDemo() {
  const [input, setInput] = _hUS("");
  const [loading, setLoading] = _hUS(false);
  const [response, setResponse] = _hUS("");
  const [error, setError] = _hUS("");

  const PROMPTS = [
    "a 12-truck plumbing company",
    "a roofing GC after a storm",
    "a 4-location dental practice",
    "a manufacturing shop with 60 employees",
  ];

  async function run(prompt) {
    const business = (prompt || input).trim();
    if (!business || loading) return;
    setLoading(true);
    setResponse("");
    setError("");
    try {
      const sys = `You are an AI integration consultant. The user describes their business in a sentence. In 3-4 short sentences (max 80 words), tell them the SINGLE highest-leverage AI integration you would build first, what it would replace, and the rough business impact. Be concrete, plainspoken, no buzzwords. Format key phrases by wrapping them in **double asterisks**. No preamble.`;
      const text = await window.claude.complete({
        messages: [
          { role: "user", content: `${sys}\n\nBusiness: ${business}` }
        ]
      });
      setResponse(text);
    } catch (e) {
      setError("AI couldn't load right now. Try a real consultation — book a call below.");
    } finally {
      setLoading(false);
    }
  }

  function renderResponse(t) {
    const parts = t.split(/(\*\*[^*]+\*\*)/g);
    return parts.map((p, i) => {
      if (p.startsWith("**") && p.endsWith("**")) {
        return <strong key={i}>{p.slice(2, -2)}</strong>;
      }
      return <React.Fragment key={i}>{p}</React.Fragment>;
    });
  }

  return (
    <div className="demo">
      <div className="demo-head">
        <span>▌Live AI Consultation</span>
        <span className="live">Real model · real-time</span>
      </div>

      <form className="demo-input" onSubmit={(e) => { e.preventDefault(); run(); }}>
        <input
          type="text"
          placeholder="Describe your business in one sentence…"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          disabled={loading} />
        <button type="submit" disabled={loading || !input.trim()}>
          {loading ? "…" : "See what we'd build"}
          {!loading && <span>→</span>}
        </button>
      </form>

      <div className="demo-chips">
        {PROMPTS.map((p, i) => (
          <button className="demo-chip" key={i} onClick={() => { setInput(p); run(p); }} disabled={loading}>
            {p}
          </button>
        ))}
      </div>

      {(loading || response || error) && (
        <div className="demo-response">
          {loading && (
            <div className="demo-thinking">
              <i></i><i></i><i></i>
              <span>Analyzing your operation</span>
            </div>
          )}
          {response && !loading && (
            <>
              <div className="label">▌Our take</div>
              <div className="body">{renderResponse(response)}</div>
            </>
          )}
          {error && !loading && (
            <>
              <div className="label">▌Note</div>
              <div className="body">{error}</div>
            </>
          )}
        </div>
      )}
    </div>
  );
}

function Hero() {
  return (
    <section className="hero" id="top">
      <ParticleField />

      {/* Engineered corner brackets */}
      <div className="hero-bracket tl"></div>
      <div className="hero-bracket tr"></div>
      <div className="hero-bracket bl"></div>
      <div className="hero-bracket br"></div>

      {/* Vertical side rails */}
      <div className="hero-rail left">
        <span className="dot"></span>
        <span>AI / F · NODE 014 · LIVE</span>
        <span style={{color:"var(--dim)"}}>· · · ·</span>
      </div>
      <div className="hero-rail right">
        <span>v1.0 · BOOKING JUNE</span>
        <span style={{color:"var(--dim)"}}>· · · ·</span>
        <span className="dot"></span>
      </div>

      {/* Floating UI badges around the hero */}
      <div className="hero-badge b1">
        <span className="blip"></span>
        <span className="l">Avg. response</span>
        <span className="v">12s</span>
      </div>
      <div className="hero-badge b2">
        <span className="blip"></span>
        <span className="l">Recovered</span>
        <span className="v">$184K</span>
      </div>
      <div className="hero-badge b3">
        <span className="blip"></span>
        <span className="l">Hours back</span>
        <span className="v">6h / wk</span>
      </div>
      <div className="hero-badge b4">
        <span className="blip"></span>
        <span className="l">Calls auto</span>
        <span className="v">84%</span>
      </div>

      <div className="container hero-inner">
        <Reveal>
          <div className="hero-pill">
            <span className="blip"></span>
            <span>The AI revolution isn't waiting</span>
          </div>
        </Reveal>

        <Reveal delay={80}>
          <h1 className="hero-title">
            <span className="glitch">Don't get left</span><br/>
            <span className="mark">behind.</span>
          </h1>
        </Reveal>

        <Reveal delay={160}>
          <p className="hero-sub">
            We walk into your business and <strong>integrate AI into every part of how you operate</strong> —
            website, phones, software, documents, workflows, people. One connected system. Try our consultant below.
          </p>
        </Reveal>

        <Reveal delay={220}>
          <div className="hero-ctas">
            <a href="#contact" className="btn">Book a consultation <span className="arrow">→</span></a>
            <a href="#how" className="btn btn-ghost">See how we work</a>
          </div>
        </Reveal>

        <Reveal delay={300}>
          <LiveDemo />
        </Reveal>
      </div>

      <div className="hero-scroll">
        <span>Scroll</span>
      </div>
    </section>
  );
}

window.Hero = Hero;
