// AIDD Agents — interactive autonomous-agent orchestra
// Innovative reinterpretation: each agent is a clickable orbit node;
// the center "stage" reveals that agent's live work product;
// connecting arcs animate as the workflow progresses.

const AIDDAgents = () => {
  const agents = [
    {
      n: '01',
      name: 'Requirements',
      role: 'Translates briefs into specs',
      icon: 'Doc',
      color: '#E63329',
      duration: '6m',
      input: 'PRD, SOW, Slack threads',
      output: 'Functional specs, Jira stories',
      tasks: [
        'Analyse PRD/SOW documents',
        'Generate functional specs',
        'Create structured Jira stories',
      ],
      preview: 'requirements',
    },
    {
      n: '02',
      name: 'Architecture',
      role: 'Designs the system',
      icon: 'Layers',
      color: '#F5C518',
      duration: '11m',
      input: 'Functional spec',
      output: 'System diagram, stack, contracts',
      tasks: [
        'Generate system architecture',
        'Select technology stack',
        'Define data models & APIs',
      ],
      preview: 'architecture',
    },
    {
      n: '03',
      name: 'Design',
      role: 'Visualises the product',
      icon: 'Brush',
      color: '#14A04A',
      duration: '14m',
      input: 'Spec + architecture',
      output: 'Wireframes, Figma kit, mockups',
      tasks: [
        'Create UI wireframes & flows',
        'Generate Figma components',
        'Create visual mockups',
      ],
      preview: 'design',
    },
    {
      n: '04',
      name: 'Tech Lead',
      role: 'Sequences the build',
      icon: 'Settings',
      color: '#1B7BD6',
      duration: '4m',
      input: 'Spec, architecture, design',
      output: 'Implementation plan, dependency graph',
      tasks: [
        'Define implementation plan',
        'Technical breakdown per story',
        'Identify dependencies',
      ],
      preview: 'techlead',
    },
    {
      n: '05',
      name: 'Coding',
      role: 'Ships production code',
      icon: 'Code',
      color: '#E63329',
      duration: '38m',
      input: 'Stories + design',
      output: 'Pull requests, unit tests',
      tasks: [
        'Write code via spec/UX/design',
        'Implement Jira requirements',
        'Generate unit tests',
      ],
      preview: 'coding',
    },
    {
      n: '06',
      name: 'Code Review',
      role: 'Guards quality',
      icon: 'Eye',
      color: '#F5C518',
      duration: '5m',
      input: 'Pull request',
      output: 'Review comments, approval',
      tasks: [
        'Review code quality',
        'Check architecture standards',
        'Validate best practices',
      ],
      preview: 'review',
    },
    {
      n: '07',
      name: 'Testing',
      role: 'Verifies behaviour',
      icon: 'Beaker',
      color: '#14A04A',
      duration: '9m',
      input: 'Built artifact',
      output: 'Test report, defect list',
      tasks: [
        'Execute functional tests',
        'Perform regression testing',
        'Report defects & issues',
      ],
      preview: 'testing',
    },
    {
      n: '08',
      name: 'Deployment',
      role: 'Releases to production',
      icon: 'Rocket',
      color: '#1B7BD6',
      duration: '3m',
      input: 'Approved build',
      output: 'Live release, monitoring',
      tasks: [
        'Deploy to target env',
        'Configure monitoring',
        'Update release status',
      ],
      preview: 'deployment',
    },
  ];

  const [active, setActive] = useState(0);
  const [playing, setPlaying] = useState(true);
  const [hover, setHover] = useState(null);

  // Autoplay through agents
  useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => {
      setActive((a) => (a + 1) % agents.length);
    }, 3200);
    return () => clearInterval(id);
  }, [playing, agents.length]);

  const current = agents[active];

  // Geometry helpers
  const N = agents.length;
  const TAU = Math.PI * 2;
  // Start angle: top (-90°)
  const angleFor = (i) => -Math.PI / 2 + (i / N) * TAU;

  // SVG canvas
  const SIZE = 560;
  const C = SIZE / 2;
  const R_OUTER = 220;   // node ring radius
  const R_INNER = 140;   // inner core
  const R_TRACK = 200;   // dashed track radius

  // Total elapsed minutes (cumulative)
  const totalMin = agents.reduce((s, a) => s + parseInt(a.duration), 0);
  const elapsedMin = agents
    .slice(0, active + 1)
    .reduce((s, a) => s + parseInt(a.duration), 0);

  return (
    <Section
      id="aidd-agents"
      eyebrow="AI-Driven Development"
      title={
        <>
          Eight autonomous agents.<br/>
          <span className="text-muted">One outcome — from brief to deploy.</span>
        </>
      }
      sub="An end-to-end agent workflow that takes your requirements from brief to deployed product. Faster, cleaner, with less room for error at every stage. Click any agent to inspect its live output."
      className="border-t border-token"
    >
      <div className="card p-4 md:p-6 lg:p-8 reveal overflow-hidden relative">
        {/* Top status bar */}
        <div className="flex flex-wrap items-center gap-3 mb-6 pb-5 border-b border-token">
          <div className="flex items-center gap-2 px-2.5 py-1 rounded-md font-mono text-[11px] tracking-[0.14em] uppercase border border-token">
            <span className="w-1.5 h-1.5 rounded-full bg-brand-green animate-pulse"/>
            Live · agent {current.n}
          </div>
          <div className="font-mono text-[11px] tracking-[0.14em] uppercase text-muted">
            cycle.t = <span style={{color: 'var(--text)'}}>{elapsedMin}m</span> / {totalMin}m
          </div>
          <div className="flex-1"/>
          <button
            onClick={() => setPlaying(p => !p)}
            className="btn btn-ghost text-[12px]"
            aria-label={playing ? 'Pause autoplay' : 'Resume autoplay'}
          >
            {playing ? <I.Pause size={14}/> : <I.Play size={14}/>}
            <span className="font-mono uppercase tracking-[0.14em]">{playing ? 'Pause' : 'Play'}</span>
          </button>
        </div>

        {/* Main grid: wheel left, stage right */}
        <div className="grid lg:grid-cols-[minmax(0,560px)_1fr] gap-6 lg:gap-10 items-start">
          {/* WHEEL */}
          <div className="relative w-full max-w-[560px] mx-auto" style={{aspectRatio: '1 / 1'}}>
            <svg viewBox={`0 0 ${SIZE} ${SIZE}`} className="w-full h-full">
              <defs>
                <linearGradient id="aidd-arc" x1="0" y1="0" x2="1" y2="1">
                  <stop offset="0%" stopColor="#E63329"/>
                  <stop offset="33%" stopColor="#F5C518"/>
                  <stop offset="66%" stopColor="#14A04A"/>
                  <stop offset="100%" stopColor="#1B7BD6"/>
                </linearGradient>
                <radialGradient id="aidd-core" cx="50%" cy="50%">
                  <stop offset="0%" stopColor={current.color} stopOpacity="0.18"/>
                  <stop offset="60%" stopColor={current.color} stopOpacity="0.04"/>
                  <stop offset="100%" stopColor={current.color} stopOpacity="0"/>
                </radialGradient>
                <filter id="aidd-glow">
                  <feGaussianBlur stdDeviation="3" result="b"/>
                  <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
                </filter>
              </defs>

              {/* Faint background grid rings */}
              {[60, 100, 140, 180, 220].map((r, i) => (
                <circle key={i} cx={C} cy={C} r={r} fill="none"
                        stroke="var(--border)" strokeWidth="1" strokeDasharray="2 4" opacity="0.5"/>
              ))}

              {/* Cross hairlines */}
              <line x1={C} y1={C - 240} x2={C} y2={C + 240} stroke="var(--border)" strokeDasharray="1 4" opacity="0.4"/>
              <line x1={C - 240} y1={C} x2={C + 240} y2={C} stroke="var(--border)" strokeDasharray="1 4" opacity="0.4"/>

              {/* Active sweep arc — from start (top) to current angle */}
              {(() => {
                const startA = -Math.PI / 2;
                const endA = angleFor(active);
                // Build arc path
                const sx = C + R_TRACK * Math.cos(startA);
                const sy = C + R_TRACK * Math.sin(startA);
                const ex = C + R_TRACK * Math.cos(endA);
                const ey = C + R_TRACK * Math.sin(endA);
                const sweep = (endA - startA + TAU) % TAU;
                const large = sweep > Math.PI ? 1 : 0;
                if (active === 0) return null;
                return (
                  <path
                    d={`M ${sx} ${sy} A ${R_TRACK} ${R_TRACK} 0 ${large} 1 ${ex} ${ey}`}
                    fill="none"
                    stroke="url(#aidd-arc)"
                    strokeWidth="2.5"
                    strokeLinecap="round"
                    opacity="0.9"
                  />
                );
              })()}

              {/* Soft core glow */}
              <circle cx={C} cy={C} r={R_INNER + 30} fill="url(#aidd-core)"/>

              {/* Connection lines from center to each agent */}
              {agents.map((a, i) => {
                const ang = angleFor(i);
                const x = C + (R_OUTER - 36) * Math.cos(ang);
                const y = C + (R_OUTER - 36) * Math.sin(ang);
                const isActive = i === active;
                const isPast = i < active;
                return (
                  <line
                    key={`spoke-${i}`}
                    x1={C} y1={C} x2={x} y2={y}
                    stroke={isActive ? a.color : isPast ? a.color : 'var(--border)'}
                    strokeOpacity={isActive ? 0.6 : isPast ? 0.25 : 0.4}
                    strokeWidth={isActive ? 1.5 : 1}
                    strokeDasharray={isActive ? undefined : '2 4'}
                  />
                );
              })}

              {/* Inner core — animated mark */}
              <g transform={`translate(${C} ${C})`}>
                <circle r={R_INNER - 30} fill="var(--surface)" stroke="var(--border)"/>
                <g className="spin-slow" style={{transformOrigin: 'center', transformBox: 'fill-box'}}>
                  <circle r="58" fill="none" stroke={current.color} strokeWidth="1" strokeDasharray="3 6" opacity="0.5"/>
                </g>
                {/* Sparkle mark */}
                <g>
                  <path d="M 0 -22 L 5 -5 L 22 0 L 5 5 L 0 22 L -5 5 L -22 0 L -5 -5 Z"
                        fill={current.color} opacity="0.95"/>
                  <circle r="4" fill="var(--surface)"/>
                </g>
              </g>

              {/* Agent nodes */}
              {agents.map((a, i) => {
                const ang = angleFor(i);
                const x = C + R_OUTER * Math.cos(ang);
                const y = C + R_OUTER * Math.sin(ang);
                const isActive = i === active;
                const isHover = i === hover;
                const isPast = i < active;
                const r = isActive ? 30 : 26;

                return (
                  <g
                    key={`node-${i}`}
                    transform={`translate(${x} ${y})`}
                    style={{cursor: 'pointer'}}
                    onMouseEnter={() => setHover(i)}
                    onMouseLeave={() => setHover(null)}
                    onClick={() => { setActive(i); setPlaying(false); }}
                    role="button"
                    aria-label={`Agent ${a.n}: ${a.name}`}
                  >
                    {/* Pulse ring (active only) */}
                    {isActive && (
                      <>
                        <circle r={r + 8} fill="none" stroke={a.color} strokeOpacity="0.25" strokeWidth="1">
                          <animate attributeName="r" values={`${r + 4};${r + 16}`} dur="2.4s" repeatCount="indefinite"/>
                          <animate attributeName="stroke-opacity" values="0.45;0" dur="2.4s" repeatCount="indefinite"/>
                        </circle>
                        <circle r={r + 4} fill="none" stroke={a.color} strokeOpacity="0.4" strokeWidth="1.5"/>
                      </>
                    )}
                    {/* Node body */}
                    <circle
                      r={r}
                      fill="var(--surface)"
                      stroke={isActive || isHover ? a.color : 'var(--border)'}
                      strokeWidth={isActive ? 2 : 1.4}
                      filter={isActive ? 'url(#aidd-glow)' : undefined}
                      style={{transition: 'all 0.3s ease'}}
                    />
                    {/* Past — colored fill */}
                    {isPast && !isActive && (
                      <circle r={r} fill={a.color} fillOpacity="0.06"/>
                    )}
                    {/* Index badge */}
                    <g transform={`translate(${r - 8} ${-r + 6})`}>
                      <circle r="9" fill={a.color}/>
                      <text textAnchor="middle" y="3" fontSize="9" fontFamily="Geist Mono" fontWeight="600" fill="#fff">
                        {a.n}
                      </text>
                    </g>
                    {/* Icon glyph (foreignObject for React icon) */}
                    <foreignObject x="-12" y="-12" width="24" height="24">
                      <div style={{
                        width: 24, height: 24,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        color: isActive || isHover || isPast ? a.color : 'var(--muted)',
                        transition: 'color 0.2s ease',
                      }}>
                        {(() => {
                          const Cmp = I[a.icon];
                          return Cmp ? <Cmp size={18}/> : null;
                        })()}
                      </div>
                    </foreignObject>

                    {/* Label outside node */}
                    {(() => {
                      // Place labels OUTSIDE each node, away from center
                      const lx = 0;
                      const ly = 0;
                      // direction vector from center to node
                      const dx = Math.cos(ang);
                      const dy = Math.sin(ang);
                      const tx = dx * (r + 16);
                      const ty = dy * (r + 16);
                      const anchor = dx > 0.3 ? 'start' : dx < -0.3 ? 'end' : 'middle';
                      return (
                        <g transform={`translate(${tx} ${ty})`} style={{pointerEvents: 'none'}}>
                          <text
                            textAnchor={anchor}
                            fontSize="13"
                            fontFamily="Geist"
                            fontWeight={isActive ? 700 : 600}
                            fill="var(--text)"
                            opacity={isActive || isHover ? 1 : 0.85}
                          >
                            {a.name}
                          </text>
                          <text
                            textAnchor={anchor}
                            y="14"
                            fontSize="10"
                            fontFamily="Geist Mono"
                            fill="var(--muted)"
                            letterSpacing="0.08em"
                          >
                            {a.duration} · {isPast ? 'DONE' : isActive ? 'RUNNING' : 'QUEUED'}
                          </text>
                        </g>
                      );
                    })()}
                  </g>
                );
              })}
            </svg>
          </div>

          {/* STAGE: live output for the active agent */}
          <div className="min-w-0">
            <div
              key={active}
              className="card overflow-hidden"
              style={{
                borderColor: current.color + '40',
                background: `linear-gradient(180deg, ${current.color}06 0%, transparent 40%)`,
              }}
            >
              {/* Stage header */}
              <div className="flex items-start gap-4 p-5 md:p-6 border-b border-token">
                <div className="w-12 h-12 rounded-xl border flex items-center justify-center flex-shrink-0"
                     style={{borderColor: current.color + '40', background: current.color + '10', color: current.color}}>
                  {(() => {
                    const Cmp = I[current.icon];
                    return Cmp ? <Cmp size={22}/> : null;
                  })()}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 font-mono text-[10px] tracking-[0.18em] uppercase text-muted">
                    Agent {current.n} · runtime {current.duration}
                  </div>
                  <h3 className="display text-[26px] mt-0.5">{current.name} Agent</h3>
                  <p className="text-[13.5px] text-muted mt-1">{current.role}</p>
                </div>
              </div>

              {/* I/O strip */}
              <div className="grid grid-cols-2 border-b border-token">
                <div className="p-4 border-r border-token">
                  <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-1">Input</div>
                  <div className="text-[13px]">{current.input}</div>
                </div>
                <div className="p-4">
                  <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-1">Output</div>
                  <div className="text-[13px]" style={{color: current.color}}>{current.output}</div>
                </div>
              </div>

              {/* Tasks */}
              <div className="p-5 md:p-6 border-b border-token">
                <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-3">Tasks · in progress</div>
                <ul className="space-y-2.5">
                  {current.tasks.map((t, k) => (
                    <li key={k} className="flex items-start gap-3 text-[13.5px]">
                      <span className="mt-1.5 w-1.5 h-1.5 rounded-full flex-shrink-0" style={{background: current.color}}/>
                      <span>{t}</span>
                    </li>
                  ))}
                </ul>
              </div>

              {/* Live preview pane */}
              <div className="p-5 md:p-6">
                <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-3">Live artifact</div>
                <AgentPreview kind={current.preview} color={current.color}/>
              </div>
            </div>

            {/* Stage timeline scrubber */}
            <div className="mt-4 hidden lg:block">
              <div className="flex items-center gap-1">
                {agents.map((a, i) => {
                  const isActive = i === active;
                  const isPast = i < active;
                  return (
                    <button
                      key={i}
                      onClick={() => { setActive(i); setPlaying(false); }}
                      onMouseEnter={() => setHover(i)}
                      onMouseLeave={() => setHover(null)}
                      className="flex-1 group flex flex-col items-start gap-1.5 py-2 px-1 text-left"
                      aria-label={`Jump to ${a.name} agent`}
                    >
                      <div className="w-full h-[3px] rounded-full transition-all"
                           style={{
                             background: isActive || isPast ? a.color : 'var(--border)',
                             opacity: isActive ? 1 : isPast ? 0.5 : 1,
                           }}/>
                      <div className="font-mono text-[9.5px] tracking-[0.14em] uppercase"
                           style={{color: isActive ? a.color : 'var(--muted)'}}>
                        {a.n} · {a.name.split(' ')[0]}
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </div>

        {/* Bottom legend */}
        <div className="mt-8 pt-6 border-t border-token grid sm:grid-cols-3 gap-4">
          <div>
            <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-1">Brief → deploy</div>
            <div className="text-[15px]">{totalMin} min average</div>
          </div>
          <div>
            <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-1">Defects per release</div>
            <div className="text-[15px]"><span className="text-brand-green">−74%</span> vs human-only</div>
          </div>
          <div>
            <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-1">Humans on the loop</div>
            <div className="text-[15px]">2 reviewers, 1 approver</div>
          </div>
        </div>
      </div>
    </Section>
  );
};

window.AIDDAgents = AIDDAgents;
