/* SKOPIA Helios — AI section, anchored at #ai
 * Introduces Helios with real outputs from the live HeliosPanel.
 */

const H = {
  bg:           '#0A0B1A',
  surface:      '#0F1029',
  surfaceHigh:  '#141530',
  surfaceActive:'#1A1D40',
  border:       'rgba(74,111,232,0.2)',
  borderSubtle: 'rgba(255,255,255,0.06)',
  text:         '#CBD5E1',
  textBright:   '#E2E8F0',
  muted:        '#475569',
  mutedMid:     '#64748B',
  cyan:         '#1EC8D4',
  peri:         '#4A6FE8',
  warn:         '#D97706',
  fail:         '#DC2626',
  online:       '#22C55E',
};

const HELIOS_MODES = [
  {
    id: 'health',
    label: 'Health Insights',
    icon: '◈',
    iconGrad: 'linear-gradient(135deg,#1EC8D4,#4A6FE8,#2A4DCC)',
    accent: H.cyan,
    pillTone: 'cyan',
    prompt: 'Rank top schedule risks from health check data, float distribution, and critical path.',
    blurb: 'AI ranks risks across constraints, float, logic and pulls the top items to act on.',
    generatedAt: '19 May 2026, 11:40 am',
    blocks: [
      {
        h: 'Zero float across all incomplete activities',
        p: '97 incomplete activities all carry 0 days of float, meaning every task sits on or drives the critical path. This complete absence of schedule buffer creates extreme vulnerability — any delay to any activity will immediately push the May 8, 2027 completion date. The 308-day critical path offers no flexibility for weather delays, material delivery issues, or design changes typical in residential construction.',
      },
      {
        h: 'Subcontract packaging bottleneck threatens downstream procurement',
        p: '"Prepare Subcontract Packages" registers the highest bottleneck score (16) with 0 days float, indicating it feeds multiple downstream critical activities. This pre-construction task likely gates trades procurement, permit coordination, and construction mobilisation. A slip here cascades through foundation, framing, MEP rough-ins, and finishes — compressing an already tight schedule with no recovery margin.',
      },
    ],
  },
  {
    id: 'baseline',
    label: 'Baseline Variance',
    icon: '⇄',
    iconGrad: 'linear-gradient(135deg,#4A6FE8,#2A4DCC)',
    accent: H.peri,
    pillTone: 'peri',
    prompt: 'Compare current schedule against baseline — finish date movement, float erosion, and critical path changes.',
    blurb: 'Auto-drafted variance analysis with logic, float impact, and supporting evidence.',
    generatedAt: '19 May 2026, 11:42 am',
    blocks: [
      {
        h: 'Critical path stability confirmed',
        p: 'Zero activities have joined or left the critical path since baseline establishment. The driving sequence of work remains unchanged, with no new constraints or dependencies emerging. Activity durations, logic ties, and resource loading have not materially shifted, preserving the critical path integrity originally modelled.',
      },
      {
        h: 'Float reserves unchanged',
        p: 'Mean and median float values show **+0.0 days** variance between baseline and current schedules. No erosion of schedule margin has occurred across the 136-activity network. Activities retain their original buffer capacity, suggesting that interim milestones have been met on time and no cascading delays have consumed downstream float.',
      },
    ],
  },
  {
    id: 'forensic',
    label: 'Forensic Analysis',
    icon: '⚑',
    iconGrad: 'linear-gradient(135deg,#DC2626,#D97706)',
    accent: H.fail,
    pillTone: 'fail',
    prompt: 'Forensic examination — float distribution, near-critical exposure, ranked risks, and actionable recommendations. Modelled on EPC/EPCM standards.',
    blurb: 'Structured forensic examination modelled on EPC/EPCM planning standards.',
    generatedAt: '19 May 2026, 11:43 am',
    blocks: [
      {
        h: 'Float distribution assessment',
        p: 'All 97 incomplete activities have zero float. This is not a schedule — it is a single-thread deterministic chain with no buffering, no alternative paths, and no absorption capacity. Every activity is critical. Any delay to any task directly extends project completion. The schedule has zero resilience and cannot accommodate real-world variation in productivity, weather, material delivery, or subcontractor performance.',
      },
      {
        h: 'Near-critical path exposure',
        p: 'The concept of "near-critical" is irrelevant. There are no activities with float between 0 and 10 days because every activity has exactly 0 days float. The entire project is a 308-working-day critical path from RHB.PL.TP.0010 (Project Kickoff) to the May 2027 finish. All activities — design, procurement, construction, inspections — drive project completion with equal force.',
      },
    ],
  },
];

// Render a paragraph, turning **bold** into <strong> and activity IDs like
// RHB.PL.TP.0010 into cyan code chips.
const ID_RE = /\b([A-Z]{2,}(?:\.[A-Z0-9]+){2,}|[A-Z]{1,5}[\d]{3,})\b/g;
const renderInsightLine = (text) => {
  const boldParts = text.split(/(\*\*[^*]+\*\*)/);
  return boldParts.map((bp, bi) => {
    if (/^\*\*(.+)\*\*$/.test(bp)) {
      return <strong key={bi} style={{ color: '#fff', fontWeight: 600 }}>{chipify(bp.replace(/\*\*/g, ''))}</strong>;
    }
    return <React.Fragment key={bi}>{chipify(bp)}</React.Fragment>;
  });
};
const chipify = (text) => {
  const out = [];
  let last = 0; let m;
  ID_RE.lastIndex = 0;
  while ((m = ID_RE.exec(text)) !== null) {
    if (m.index > last) out.push(text.slice(last, m.index));
    out.push(
      <code key={out.length} style={{
        fontFamily: 'var(--font-mono)', fontSize: 11,
        background: 'rgba(30,200,212,0.15)', color: H.cyan,
        border: '1px solid rgba(30,200,212,0.3)',
        borderRadius: 3, padding: '0 5px',
        whiteSpace: 'nowrap',
      }}>{m[0]}</code>
    );
    last = ID_RE.lastIndex;
  }
  if (last < text.length) out.push(text.slice(last));
  return out;
};

const HeliosAvatar = ({ size = 80, animated = false, glow = true }) => (
  <span style={{
    position: 'relative', display: 'inline-block',
    width: size, height: size, flexShrink: 0,
  }}>
    {glow && (
      <span aria-hidden="true" style={{
        position: 'absolute',
        /* Centered on the face (slightly above geometric centre, where eyes/mouth sit).
           Sized smaller than the orb so it never bleeds past the outside edges. */
        left: '50%', top: '48%',
        width: size * 0.62, height: size * 0.62,
        transform: 'translate(-50%, -50%)',
        background: 'radial-gradient(closest-side, rgba(255,255,255,0.85), rgba(255,255,255,0) 72%)',
        filter: 'blur(' + (size * 0.08) + 'px)',
        animation: 'helios-face-glow 4s ease-in-out infinite',
        pointerEvents: 'none',
      }} />
    )}
    <img
      src="assets/helios-static.png"
      alt="Helios" draggable={false}
      className={animated ? 'helios-anim' : ''}
      style={{
        position: 'relative', width: '100%', height: '100%',
        objectFit: 'contain',
        userSelect: 'none',
        transformOrigin: '50% 55%',
      }}
    />
  </span>
);

const HeliosSection = () => {
  const [active, setActive] = useState(0);
  const [paused, setPaused] = useState(false);
  const [generating, setGenerating] = useState(false);
  const sectionRef = useRef(null);
  const [inView, setInView] = useState(false);

  useEffect(() => {
    const el = sectionRef.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { threshold: 0.2 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Auto-cycle modes when in view; show a brief "generating" state on each switch
  useEffect(() => {
    if (!inView || paused) return;
    let t1, t2;
    t1 = setTimeout(() => {
      setGenerating(true);
      t2 = setTimeout(() => {
        setActive((a) => (a + 1) % HELIOS_MODES.length);
        setGenerating(false);
      }, 1100);
    }, 7000);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [active, inView, paused]);

  const switchTo = (i) => {
    if (i === active) return;
    setPaused(true);
    setGenerating(true);
    setTimeout(() => {
      setActive(i);
      setGenerating(false);
    }, 700);
  };

  const mode = HELIOS_MODES[active];

  return (
    <section
      id="ai"
      ref={sectionRef}
      className="section-pad"
      style={{
        background: H.bg,
        color: H.text,
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      {/* Ambient orbs */}
      <div className="orb-bg" style={{ width: 600, height: 600, top: -120, left: '-10%', background: 'radial-gradient(closest-side, rgba(30,200,212,0.28), transparent 70%)', opacity: 0.6 }} />
      <div className="orb-bg" style={{ width: 700, height: 700, bottom: -200, right: '-15%', background: 'radial-gradient(closest-side, rgba(106,63,204,0.32), transparent 70%)', opacity: 0.6, animation: 'drift 20s ease-in-out infinite' }} />
      <div className="orb-bg" style={{ width: 500, height: 500, top: '40%', left: '60%', background: 'radial-gradient(closest-side, rgba(74,111,232,0.25), transparent 70%)', opacity: 0.5 }} />

      <div className="container" style={{ position: 'relative', zIndex: 2 }}>
        {/* Intro */}
        <Reveal>
          <div style={{ textAlign: 'center', maxWidth: 780, margin: '0 auto' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 26 }}>
              <HeliosAvatar size={120} animated={true} />
            </div>
            <div className="eyebrow" style={{ color: H.cyan, justifyContent: 'center', marginBottom: 22 }}>Meet Helios · the SKOPIA AI Agent</div>
            <h2 className="h-section" style={{ color: '#fff', marginBottom: 22, textWrap: 'balance' }}>
              Schedule intelligence,{' '}
              <span className="grad-text">on demand.</span>
            </h2>
            <p className="lede" style={{ color: 'rgba(255,255,255,0.66)', margin: '0 auto', textAlign: 'center' }}>
              Helios reads your schedule artefacts and produces defensible commentary — health insights, baseline variance, and EPC-grade forensic analysis. Not a chatbot. A planning analyst who never sleeps.
            </p>
          </div>
        </Reveal>

        {/* The three modes — selectable mode cards */}
        <Reveal delay={120}>
          <div style={{
            marginTop: 56,
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: 14,
          }} className="helios-modes">
            {HELIOS_MODES.map((m, i) => {
              const isActive = i === active;
              return (
                <button
                  key={m.id}
                  onClick={() => switchTo(i)}
                  style={{
                    display: 'flex', alignItems: 'flex-start', gap: 14,
                    padding: '18px 18px',
                    textAlign: 'left', cursor: 'pointer',
                    background: isActive ? H.surfaceActive : H.surfaceHigh,
                    border: `1px solid ${isActive ? m.accent + '55' : H.borderSubtle}`,
                    borderLeft: isActive ? `3px solid ${m.accent}` : `3px solid transparent`,
                    borderRadius: 6,
                    fontFamily: 'inherit',
                    transition: 'background .15s, border-color .15s, transform .15s',
                  }}
                  onMouseEnter={(e) => { if (!isActive) e.currentTarget.style.background = '#1C2045'; }}
                  onMouseLeave={(e) => { if (!isActive) e.currentTarget.style.background = H.surfaceHigh; }}
                >
                  <span style={{
                    width: 40, height: 40, borderRadius: 5,
                    background: m.iconGrad,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 17, color: '#fff', flexShrink: 0,
                    boxShadow: isActive ? `0 4px 18px ${m.accent}55` : 'none',
                  }}>{m.icon}</span>
                  <div style={{ minWidth: 0 }}>
                    <div style={{
                      fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 14,
                      color: isActive ? m.accent : '#fff', marginBottom: 6,
                      display: 'flex', alignItems: 'center', gap: 8,
                    }}>
                      {m.label}
                      {isActive && <span style={{ width: 6, height: 6, borderRadius: '50%', background: m.accent }}></span>}
                    </div>
                    <div style={{
                      fontFamily: 'var(--font-body)', fontSize: 13,
                      color: isActive ? H.text : H.mutedMid, lineHeight: 1.55,
                    }}>{m.blurb}</div>
                  </div>
                </button>
              );
            })}
          </div>
        </Reveal>

        {/* The Helios Panel — replica showing real outputs */}
        <Reveal delay={180}>
          <div style={{
            marginTop: 32,
            background: H.bg,
            border: `1px solid ${H.border}`,
            borderRadius: 10,
            boxShadow: '0 30px 80px rgba(0,0,0,0.5), 0 0 0 1px rgba(74,111,232,0.10)',
            overflow: 'hidden',
          }}>
            {/* Top gradient strip */}
            <div style={{ height: 3, background: 'var(--color-grad)' }} />

            {/* Header */}
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '13px 18px',
              borderBottom: `1px solid ${H.border}`,
            }}>
              <HeliosAvatar size={34} animated={false} glow={false} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontFamily: 'var(--font-mono)', fontSize: 9, fontWeight: 500,
                  letterSpacing: '0.12em', textTransform: 'uppercase',
                  color: H.muted, lineHeight: 1, marginBottom: 4,
                }}>SKOPIA · Helios</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: H.mutedMid }}>
                  Residential House Build
                </div>
              </div>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{
                  width: 7, height: 7, borderRadius: '50%',
                  background: generating ? H.cyan : H.online,
                  animation: generating ? 'helios-pulse 1.2s ease-in-out infinite' : 'none',
                }}></span>
                <span style={{
                  fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.08em',
                  color: generating ? H.cyan : H.online,
                }}>{generating ? 'generating' : 'online'}</span>
              </span>
            </div>

            {/* Tab bar */}
            <div style={{
              display: 'flex', borderBottom: `1px solid ${H.border}`,
              background: H.bg, padding: '0 2px',
            }}>
              {HELIOS_MODES.map((m, i) => {
                const isActive = i === active;
                return (
                  <button key={m.id} onClick={() => switchTo(i)} style={{
                    flex: 1, fontFamily: 'var(--font-mono)', fontWeight: 500,
                    fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase',
                    padding: '12px 6px 11px',
                    background: 'transparent', border: 'none',
                    borderBottom: isActive ? `2px solid ${m.accent}` : '2px solid transparent',
                    color: isActive ? m.accent : H.mutedMid,
                    cursor: 'pointer',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    gap: 7, whiteSpace: 'nowrap',
                    transition: 'color .15s, border-color .15s',
                  }}>
                    <span style={{ fontSize: 13 }}>{m.icon}</span>
                    <span>{m.label}</span>
                  </button>
                );
              })}
            </div>

            {/* Body */}
            <div className="helios-body" style={{
              display: 'grid', gridTemplateColumns: '300px 1fr',
              minHeight: 380,
            }}>
              {/* LEFT — terminal prompt */}
              <aside style={{
                borderRight: `1px solid ${H.border}`,
                padding: 18, display: 'flex', flexDirection: 'column', gap: 12,
              }}>
                <div style={{
                  display: 'flex', alignItems: 'flex-start', gap: 8,
                  padding: '10px 12px',
                  background: H.surfaceHigh, border: `1px solid ${H.borderSubtle}`, borderRadius: 4,
                }}>
                  <span style={{
                    fontFamily: 'var(--font-mono)', fontSize: 12, color: mode.accent,
                    marginTop: 1, userSelect: 'none',
                  }}>&gt;</span>
                  <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: H.mutedMid, lineHeight: 1.55 }}>
                    {mode.prompt}
                  </span>
                </div>

                {generating && (
                  <div style={{
                    padding: '14px 12px',
                    background: H.surface, border: `1px solid ${H.borderSubtle}`, borderRadius: 4,
                    display: 'flex', alignItems: 'center', gap: 8,
                    fontFamily: 'var(--font-mono)', fontSize: 12, color: H.mutedMid,
                  }}>
                    <span style={{ width: 7, height: 7, borderRadius: '50%', background: H.cyan, animation: 'helios-pulse 1.2s ease-in-out infinite' }}></span>
                    SKOPIA · {mode.id === 'forensic' ? 'auditing' : 'analysing'}
                    <span className="helios-dots" aria-hidden="true">
                      <span style={{ animationDelay: '0ms' }}>.</span>
                      <span style={{ animationDelay: '200ms' }}>.</span>
                      <span style={{ animationDelay: '400ms' }}>.</span>
                    </span>
                  </div>
                )}

                <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'var(--font-mono)', fontSize: 10, color: H.muted, letterSpacing: '0.03em' }}>
                  <span style={{ color: '#16A34A', fontSize: 11 }}>✓</span>
                  indexed · will appear in next export
                </div>
              </aside>

              {/* RIGHT — insight card */}
              <div style={{ padding: 18, position: 'relative' }}>
                <div key={mode.id + (generating ? '-g' : '-r')} style={{
                  background: H.surface,
                  border: `1px solid ${H.borderSubtle}`,
                  borderLeft: `3px solid ${mode.accent}`,
                  borderRadius: 4,
                  padding: 16,
                  opacity: generating ? 0.25 : 1,
                  transition: 'opacity .35s ease',
                  animation: !generating ? 'helios-fadein .45s ease-out' : 'none',
                }}>
                  <div style={{
                    fontFamily: 'var(--font-mono)', fontSize: 9, color: H.muted,
                    marginBottom: 14, letterSpacing: '0.04em',
                  }}>── generated {mode.generatedAt} ──</div>

                  <div style={{
                    fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 11,
                    color: mode.accent, marginBottom: 14, letterSpacing: '0.10em', textTransform: 'uppercase',
                  }}>## Schedule {mode.id === 'health' ? 'Health' : mode.id === 'baseline' ? 'Baseline' : 'Forensic'} {mode.id === 'forensic' ? 'Analysis' : 'Insights'}</div>

                  {mode.blocks.map((b, i) => (
                    <div key={i} style={{ marginTop: i ? 18 : 0 }}>
                      <div style={{
                        fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 11,
                        color: mode.accent, marginBottom: 8,
                        letterSpacing: '0.08em', textTransform: 'uppercase',
                      }}>{b.h}</div>
                      <p style={{
                        fontFamily: 'var(--font-body)', fontSize: 13.5, lineHeight: 1.75,
                        color: H.text,
                      }}>{renderInsightLine(b.p)}</p>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Footer button */}
            <div style={{
              padding: '12px 18px 14px',
              borderTop: `1px solid ${H.border}`,
              background: H.bg,
            }}>
              <button
                onClick={() => {
                  setGenerating(true);
                  setTimeout(() => setGenerating(false), 1100);
                }}
                style={{
                  width: '100%',
                  fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 12,
                  letterSpacing: '0.05em',
                  padding: '12px 0', borderRadius: 4,
                  background: mode.accent + '14',
                  border: `1px solid ${mode.accent}55`,
                  color: mode.id === 'forensic' ? '#FCA5A5' : mode.accent,
                  cursor: 'pointer',
                  transition: 'background .15s',
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = mode.accent + '22'}
                onMouseLeave={(e) => e.currentTarget.style.background = mode.accent + '14'}
              >
                ↺&nbsp;&nbsp;Rerun {mode.id === 'forensic' ? 'Audit' : 'Analysis'}
              </button>
            </div>
          </div>
        </Reveal>

        {/* Capabilities row */}
        <Reveal delay={240}>
          <div style={{
            marginTop: 48,
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',
            gap: 12,
          }}>
            {[
              { k: 'No retraining', v: 'Works on your Schedule as-is — no labelling, no data prep.' },
              { k: 'Defensible', v: 'Every claim cites the activity ID it came from. Insert with one click.' },
              { k: 'EPC-aligned', v: 'Forensic mode is modelled on EPC/EPCM planning standards.' },
              { k: 'In every export', v: 'Indexed automatically into your next PDF or report.' },
            ].map((c) => (
              <div key={c.k} style={{
                padding: '18px 18px',
                background: 'rgba(255,255,255,0.03)',
                border: `1px solid ${H.borderSubtle}`,
                borderRadius: 6,
              }}>
                <div style={{ fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 13, color: '#fff', marginBottom: 6 }}>{c.k}</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'rgba(255,255,255,0.55)', lineHeight: 1.55 }}>{c.v}</div>
              </div>
            ))}
          </div>
        </Reveal>
      </div>

      <style>{`
        @keyframes helios-pulse {
          0%, 100% { opacity: 1;   transform: scale(1);    }
          50%      { opacity: 0.4; transform: scale(0.75); }
        }
        @keyframes helios-fadein {
          from { opacity: 0; transform: translateY(6px); }
          to   { opacity: 1; transform: translateY(0);   }
        }
        @keyframes helios-face-glow {
          0%, 100% { opacity: 0.85; transform: translate(-50%, -50%) scale(1); }
          50%      { opacity: 1;    transform: translate(-50%, -50%) scale(1.06); }
        }
        /* Idle "alive" animation — gentle bob + breath + tiny sway,
           mimicking the GIF without the baked-in black background. */
        @keyframes helios-bob {
          0%, 100% { transform: translateY(0) scale(1)        rotate(-1.2deg); }
          25%      { transform: translateY(-3%) scale(1.018)  rotate(0deg);    }
          50%      { transform: translateY(-1%) scale(1.012)  rotate(1.2deg);  }
          75%      { transform: translateY(-4%) scale(1.022)  rotate(0deg);    }
        }
        .helios-anim {
          animation: helios-bob 5.4s ease-in-out infinite;
          will-change: transform;
        }
        .helios-dots span {
          opacity: 0;
          animation: helios-dot-appear 1.2s ease-in-out infinite;
        }
        @keyframes helios-dot-appear {
          0%, 60%, 100% { opacity: 0; }
          20%, 40%      { opacity: 1; }
        }
        @media (max-width: 880px) {
          #ai .helios-modes { grid-template-columns: 1fr !important; }
          #ai .helios-body  { grid-template-columns: 1fr !important; }
          #ai .helios-body > aside {
            border-right: none !important;
            border-bottom: 1px solid ${H.border};
          }
        }
      `}</style>
    </section>
  );
};

Object.assign(window, { HeliosSection });
