// AI Capabilities showcase — signature animation: AI Workbench
// Typewriter prompt → streaming response, alongside a neural constellation with traveling signals

const { Spark: AISpark, Brain: AIBrain, Bolt: AIBolt, Code: AICode, DB: AIDB } = window.Icons;

// ──────────────────────────────────────────────────────────
// AIWorkbench — typewriter prompt → token-shimmer response
// ──────────────────────────────────────────────────────────
function AIWorkbench() {
  const containerRef = useRef(null);
  const [phase, setPhase] = useState('idle'); // idle | typing | thinking | streaming | done
  const [promptText, setPromptText] = useState('');
  const [tokens, setTokens] = useState([]);
  const [active, setActive] = useState(false);

  const fullPrompt = "Audit our claims pipeline and propose an agent that drafts denial appeals from policy docs.";

  // The streamed response tokens (chunks of varying length, like an LLM)
  const responseTokens = useMemo(() => [
    "Mapped", " 14", " stages", " in", " your", " claims", " pipeline", ".", "\n",
    "Bottleneck", ":", " denial", " appeals", " — ", "avg.", " ", "4.2", " days", ", ", "62%", " manual", ".", "\n\n",
    "Proposed", " agent", ":", "\n",
    " — ", "ingest", " denial", " letter", " ", "+", " claim", " context", "\n",
    " — ", "retrieve", " policy", " clauses", " via", " ", "hybrid", " RAG", "\n",
    " — ", "draft", " appeal", " ", "+", " cite", " evidence", "\n",
    " — ", "route", " to", " adjudicator", " for", " ", "review", "\n\n",
    "Est.", " cycle", " time", ":", " ", "4.2d", " → ", "11h", ". ",
    "Shall", " we", " scope", " a", " ", "two-week", " pilot", "?",
  ], []);

  // Start when scrolled into view
  useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setActive(true);
        if (reduce) {
          setPromptText(fullPrompt);
          setTokens(responseTokens);
          setPhase('done');
        } else {
          setPhase('typing');
        }
        io.disconnect();
      }
    }, { threshold: 0.35 });
    io.observe(el);
    return () => io.disconnect();
  }, [fullPrompt, responseTokens]);

  // Type the prompt
  useEffect(() => {
    if (phase !== 'typing') return;
    let i = 0;
    const id = setInterval(() => {
      i++;
      setPromptText(fullPrompt.slice(0, i));
      if (i >= fullPrompt.length) {
        clearInterval(id);
        setTimeout(() => setPhase('thinking'), 350);
      }
    }, 28);
    return () => clearInterval(id);
  }, [phase, fullPrompt]);

  // Brief thinking pause
  useEffect(() => {
    if (phase !== 'thinking') return;
    const t = setTimeout(() => setPhase('streaming'), 900);
    return () => clearTimeout(t);
  }, [phase]);

  // Stream response tokens
  useEffect(() => {
    if (phase !== 'streaming') return;
    let i = 0;
    const id = setInterval(() => {
      i++;
      setTokens(responseTokens.slice(0, i));
      if (i >= responseTokens.length) {
        clearInterval(id);
        setPhase('done');
      }
    }, 55);
    return () => clearInterval(id);
  }, [phase, responseTokens]);

  // Restart on click for replay
  const restart = () => {
    if (phase !== 'done') return;
    setTokens([]);
    setPromptText('');
    setPhase('typing');
  };

  return (
    <div ref={containerRef} className="workbench p-5 sm:p-6">
      {/* Header chrome */}
      <div className="flex items-center justify-between pb-4 mb-5 border-b" style={{borderColor: 'var(--border)'}}>
        <div className="flex items-center gap-2.5">
          <div className="flex gap-1.5">
            <span className="w-2.5 h-2.5 rounded-full" style={{background: '#FF5F57'}}></span>
            <span className="w-2.5 h-2.5 rounded-full" style={{background: '#FEBC2E'}}></span>
            <span className="w-2.5 h-2.5 rounded-full" style={{background: '#28C840'}}></span>
          </div>
          <span className="font-mono text-[11px] ml-3" style={{color: 'var(--muted)'}}>cardefi · workbench</span>
        </div>
        <div className="flex items-center gap-1.5">
          <span className={`w-1.5 h-1.5 rounded-full ${phase === 'streaming' || phase === 'thinking' ? 'animate-pulse' : ''}`}
                style={{background: phase === 'done' ? 'var(--accent-cyan)' : 'var(--accent-violet)'}}></span>
          <span className="font-mono text-[10px] uppercase tracking-[0.18em]" style={{color: 'var(--muted)'}}>
            {phase === 'idle' && 'ready'}
            {phase === 'typing' && 'composing'}
            {phase === 'thinking' && 'reasoning'}
            {phase === 'streaming' && 'streaming'}
            {phase === 'done' && 'complete'}
          </span>
        </div>
      </div>

      {/* Prompt row */}
      <div className="flex gap-3 mb-5">
        <div className="font-mono text-[11px] pt-1" style={{color: 'var(--dim)'}}>You</div>
        <div className="flex-1 font-mono text-[13px] leading-[1.6] min-h-[36px]" style={{color: 'var(--ink)'}}>
          <span>{promptText}</span>
          {phase === 'typing' && <span className="cursor-blink"></span>}
        </div>
      </div>

      {/* Divider */}
      <div className="h-px mb-5" style={{background: 'var(--border)'}}></div>

      {/* Response */}
      <div className="flex gap-3">
        <div className="font-mono text-[11px] pt-1 flex items-center gap-1.5" style={{color: 'var(--dim)'}}>
          <span className="inline-block w-3 h-3 rounded-sm" style={{background: 'var(--grad)'}}></span>
          AI
        </div>
        <div className="flex-1 font-mono text-[13px] leading-[1.65] min-h-[260px] whitespace-pre-wrap" style={{color: 'var(--ink)'}}>
          {phase === 'thinking' && (
            <span className="inline-flex items-center gap-1.5" style={{color: 'var(--muted)'}}>
              <span className="thinking-dots inline-flex gap-1">
                <span className="w-1 h-1 rounded-full inline-block" style={{background: 'var(--accent-violet)', animation: 'thinkDot 1.2s ease-in-out infinite'}}></span>
                <span className="w-1 h-1 rounded-full inline-block" style={{background: 'var(--accent-violet)', animation: 'thinkDot 1.2s ease-in-out 0.2s infinite'}}></span>
                <span className="w-1 h-1 rounded-full inline-block" style={{background: 'var(--accent-violet)', animation: 'thinkDot 1.2s ease-in-out 0.4s infinite'}}></span>
              </span>
              <span className="ml-2">thinking</span>
            </span>
          )}
          {tokens.map((t, i) => (
            <span key={i} className="token-shimmer" style={{animationDelay: '0ms'}}>{t}</span>
          ))}
          {phase === 'streaming' && <span className="cursor-blink"></span>}
        </div>
      </div>

      {phase === 'done' && (
        <button onClick={restart}
                className="mt-5 inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.18em] hover:text-white transition-colors"
                style={{color: 'var(--muted)'}}>
          <span>↻</span> Replay
        </button>
      )}

      <style>{`
        @keyframes thinkDot {
          0%, 80%, 100% { opacity: 0.3; transform: translateY(0); }
          40% { opacity: 1; transform: translateY(-3px); }
        }
      `}</style>
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Neural constellation — pulsing nodes + traveling signals
// ──────────────────────────────────────────────────────────
function NeuralConstellation() {
  // Three columns (input, hidden, output) — but slightly organic positions
  const nodes = useMemo(() => {
    const cols = [
      { x: 60, count: 5 },
      { x: 200, count: 6 },
      { x: 340, count: 4 },
    ];
    const all = [];
    cols.forEach((c, ci) => {
      for (let i = 0; i < c.count; i++) {
        const y = 40 + (i + 0.5) * ((280 - 40) / c.count);
        all.push({ id: `c${ci}n${i}`, x: c.x, y, col: ci });
      }
    });
    return all;
  }, []);

  const edges = useMemo(() => {
    const e = [];
    const byCol = (c) => nodes.filter(n => n.col === c);
    [0, 1].forEach(c => {
      byCol(c).forEach(a => {
        byCol(c + 1).forEach(b => {
          e.push({ a, b });
        });
      });
    });
    return e;
  }, [nodes]);

  // Pick 8 random edges to animate signals along
  const signalPaths = useMemo(() => {
    const seeds = [0.05, 0.18, 0.27, 0.41, 0.55, 0.68, 0.79, 0.91];
    return seeds.map((s, i) => ({
      idx: Math.floor(s * edges.length),
      delay: i * 0.6,
      duration: 2.2 + (i % 3) * 0.5,
    }));
  }, [edges]);

  return (
    <svg viewBox="0 0 400 320" className="w-full h-full" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
      <defs>
        <linearGradient id="edgeGrad" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor="#3B82F6" stopOpacity="0.35" />
          <stop offset="100%" stopColor="#8B5CF6" stopOpacity="0.35" />
        </linearGradient>
        <radialGradient id="nodeGrad">
          <stop offset="0%" stopColor="#FAFAF7" stopOpacity="1" />
          <stop offset="60%" stopColor="#8B5CF6" stopOpacity="0.9" />
          <stop offset="100%" stopColor="#3B82F6" stopOpacity="0.5" />
        </radialGradient>
        <radialGradient id="signalGrad">
          <stop offset="0%" stopColor="#FAFAF7" stopOpacity="1" />
          <stop offset="100%" stopColor="#22D3EE" stopOpacity="0" />
        </radialGradient>
      </defs>

      {/* Edges */}
      {edges.map((e, i) => (
        <line
          key={i}
          x1={e.a.x} y1={e.a.y} x2={e.b.x} y2={e.b.y}
          stroke="url(#edgeGrad)"
          strokeWidth="0.6"
          opacity="0.5"
        />
      ))}

      {/* Traveling signals */}
      {signalPaths.map((sp, i) => {
        const e = edges[sp.idx];
        if (!e) return null;
        return (
          <circle key={i} r="3" fill="url(#signalGrad)" className="signal">
            <animate attributeName="cx" from={e.a.x} to={e.b.x} dur={`${sp.duration}s`} begin={`${sp.delay}s`} repeatCount="indefinite" />
            <animate attributeName="cy" from={e.a.y} to={e.b.y} dur={`${sp.duration}s`} begin={`${sp.delay}s`} repeatCount="indefinite" />
            <animate attributeName="opacity" values="0;1;1;0" keyTimes="0;0.1;0.85;1" dur={`${sp.duration}s`} begin={`${sp.delay}s`} repeatCount="indefinite" />
          </circle>
        );
      })}

      {/* Nodes */}
      {nodes.map((n, i) => (
        <g key={n.id} className="node" style={{animationDelay: `${(i * 0.13) % 2.5}s`}}>
          <circle cx={n.x} cy={n.y} r="6" fill="url(#nodeGrad)" opacity="0.85" />
          <circle cx={n.x} cy={n.y} r="2.4" fill="#FAFAF7" />
        </g>
      ))}
    </svg>
  );
}

// ──────────────────────────────────────────────────────────
// AI Capabilities section
// ──────────────────────────────────────────────────────────
function AICapabilities() {
  const pillars = [
    { icon: AIBrain, title: 'LLM-powered applications', body: 'Chat, summarization, copilots — engineered around evals, not vibes.' },
    { icon: AIBolt, title: 'Agentic workflows & automation', body: 'Multi-step agents with tool use, memory, and human-in-the-loop control.' },
    { icon: AIDB, title: 'RAG & knowledge systems', body: 'Hybrid retrieval over your documents, schemas, and live business data.' },
    { icon: AICode, title: 'Model fine-tuning & deployment', body: 'Adaptation, distillation, and serving — open-source or frontier APIs.' },
  ];

  return (
    <section id="ai" className="relative py-28 lg:py-36 overflow-hidden">
      {/* Soft ambient glow */}
      <div className="absolute inset-0 pointer-events-none -z-0" aria-hidden="true">
        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[1000px] h-[600px] rounded-full"
             style={{background: 'radial-gradient(ellipse at center, rgba(139,92,246,0.10), transparent 60%)', filter: 'blur(60px)'}}></div>
      </div>

      <div className="relative max-w-[1280px] mx-auto px-6 lg:px-10">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 mb-16">
          <div className="lg:col-span-7">
            <div className="reveal eyebrow mb-5">AI capabilities</div>
            <h2 className="reveal font-display text-[36px] sm:text-[44px] lg:text-[60px] leading-[1.0] tracking-[-0.04em] font-medium" data-delay="80">
              From <span className="serif-em" style={{color: 'var(--ink-warm)'}}>prompt</span> to production.
              <br />
              In one engagement.
            </h2>
          </div>
          <p className="lg:col-span-4 lg:col-start-9 reveal text-[15px] leading-[1.6] self-end" style={{color: 'var(--muted)'}} data-delay="160">
            We build AI systems your operators actually trust — with evaluations, observability,
            and guardrails as first-class concerns, not afterthoughts.
          </p>
        </div>

        {/* Workbench + constellation */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 mb-20">
          <div className="lg:col-span-7 reveal" data-delay="80">
            <AIWorkbench />
          </div>
          <div className="lg:col-span-5 reveal" data-delay="200">
            <div className="workbench h-full p-5 sm:p-6 flex flex-col">
              <div className="flex items-center justify-between pb-4 mb-2 border-b" style={{borderColor: 'var(--border)'}}>
                <span className="font-mono text-[11px]" style={{color: 'var(--muted)'}}>retrieval graph · live</span>
                <span className="font-mono text-[10px] uppercase tracking-[0.18em]" style={{color: 'var(--accent-cyan)'}}>● active</span>
              </div>
              <div className="flex-1 min-h-[280px] flex items-center justify-center">
                <NeuralConstellation />
              </div>
              <div className="grid grid-cols-3 gap-3 pt-4 border-t" style={{borderColor: 'var(--border)'}}>
                <div>
                  <div className="font-mono text-[10px] tracking-[0.16em] uppercase mb-1" style={{color: 'var(--dim)'}}>Recall</div>
                  <div className="font-display text-[18px] font-semibold tracking-tight">94.2%</div>
                </div>
                <div>
                  <div className="font-mono text-[10px] tracking-[0.16em] uppercase mb-1" style={{color: 'var(--dim)'}}>Latency</div>
                  <div className="font-display text-[18px] font-semibold tracking-tight">240ms</div>
                </div>
                <div>
                  <div className="font-mono text-[10px] tracking-[0.16em] uppercase mb-1" style={{color: 'var(--dim)'}}>Hops</div>
                  <div className="font-display text-[18px] font-semibold tracking-tight">3</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Pillars */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5">
          {pillars.map((p, i) => (
            <div key={p.title} className="reveal p-6 rounded-2xl"
                 style={{background: 'var(--surface-1)', border: '1px solid var(--border)'}}
                 data-delay={i * 90}>
              <div className="w-10 h-10 rounded-lg flex items-center justify-center mb-5"
                   style={{background: 'var(--surface-2)', border: '1px solid var(--border)'}}>
                <p.icon size={18} stroke={1.5} />
              </div>
              <h3 className="font-display text-[16px] font-semibold tracking-tight mb-2" style={{color: 'var(--ink)'}}>
                {p.title}
              </h3>
              <p className="text-[13.5px] leading-[1.55]" style={{color: 'var(--muted)'}}>
                {p.body}
              </p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

window.AICapabilities = AICapabilities;
