// =====================================================
// TACTICAL OPS PORTFOLIO — sections 01–07
// =====================================================

const { useState, useEffect, useRef, useCallback, useMemo } = React;
const OPERATOR_IMAGE_SRC = 'assets/operator-photo.png';

// ============== DATA ==============
const STACK_ROWS = [
  { name: 'Java · Spring Boot',       pct: 95, color: 'gold' },
  { name: 'Kafka · Microservices',    pct: 88, color: 'gold' },
  { name: 'PostgreSQL · Redis',       pct: 92, color: 'blue' },
  { name: 'ClickHouse · MongoDB',     pct: 78, color: 'blue' },
  { name: 'AWS · GCP · Docker',       pct: 72, color: 'green' },
  { name: 'C++ · Python',             pct: 62, color: 'orange' },
];

const EXPERIENCE = [
  {
    cls: 'current', dotCls: 'green', period: 'MAY 2025 — PRESENT',
    company: 'QuilrAI', role: 'Senior Software Engineer · Remote, New Delhi',
    desc: [
      'Redesigned security findings & events ingestion from scheduled batch to real-time Kafka streams — 120x latency improvement.',
      'Refactored data ingestion from per-tenant-per-fabric to fabric-level multi-threaded architecture — reduced pod count by 80% while maintaining throughput.',
      'Executed Neo4j → PostgreSQL/ClickHouse migration — eliminated $36K+ annual licensing, improved query performance by 66%.',
      'Engineered Redis caching for high-frequency security APIs — eliminated 80% of DB hits, achieved 10x P95 improvement.',
    ],
    tags: ['Java', 'Spring Boot', 'Kafka', 'PostgreSQL', 'ClickHouse', 'Redis', 'Neo4j'],
    stat: '120x latency · −$36K/yr · −80% pods · −80% DB hits',
  },
  {
    cls: 'past', dotCls: 'blue', period: 'MAR 2024 — MAY 2025',
    company: 'DP World', role: 'Software Development Engineer I · Gurugram',
    desc: [
      'Developed Bulk Upload Feature supporting 10K+ declarations in <2s — 400% time efficiency improvement.',
      'Migrated 12 templates from Carbone.io to Jaspersoft for invoices with up to 2000 items — 66.67% performance gain.',
      'Executed SOAP → REST architecture migration with full service refactorization — +40% interoperability, −1/3 costs.',
      'Spearheaded Sandboxing and Profile Scheduling using Camunda BPMN + Quartz — reduced processing time by 80%.',
    ],
    tags: ['Java', 'Spring Boot', 'Camunda', 'Quartz', 'Jaspersoft', 'PostgreSQL'],
    stat: '400% efficiency · +40% interop · −80% processing time',
  },
  {
    cls: 'past', dotCls: 'orange', period: 'JUL 2022 — FEB 2024',
    company: 'DP World', role: 'Software Development Engineer · Gurugram',
    desc: [
      'Revamped email sending by migrating to Thymeleaf + SendGrid — 30% improvement in delivery rates.',
      'Resolved 200+ bug fixes and improved system performance — 10% increase in user satisfaction scores.',
      'Implemented Multi-Tenant Design Architecture supporting declaration submission for 25 countries.',
    ],
    tags: ['Java', 'Spring Boot', 'Thymeleaf', 'SendGrid', 'PostgreSQL', 'MongoDB'],
    stat: '+30% delivery · 200+ fixes · 25 countries · 10% UX gain',
  },
];

const COURSEWORK = ['Algorithms', 'Data Structures', 'Networks', 'Operating Systems', 'System Design', 'Embedded Systems'];
const CP_ROWS = [
  { ico: '◆', term: 'LeetCode',  desc: 'Max 1774 · Rank 1280/35490 (95%ile) Weekly 442' },
  { ico: '★', term: 'CodeChef',  desc: 'Max 1776 · Global Rank 367 (Top 1%) Starters 140' },
  { ico: '⚙', term: 'Java',      desc: 'Primary competitive programming language' },
];
const RANKS = [
  { ico: '◈', term: 'KUDOS Award ×2',      desc: 'Employee of the Quarter · DP World Customs' },
  { ico: '◇', term: 'HackPossible 2024',   desc: 'Finalist · Top 5 across India' },
];

function SkillIcon({ slug, equipped, goldSrc, brandSrc }) {
  if (!slug && !goldSrc) return <span style={{ fontSize: '16px', lineHeight: 1 }}>⬡</span>;
  const src = equipped
    ? (brandSrc || `https://cdn.simpleicons.org/${slug}`)
    : (goldSrc || `https://cdn.simpleicons.org/${slug}/d4a843`);
  return (
    <img
      src={src}
      width="24"
      height="24"
      alt=""
      draggable="false"
      style={{ display: 'block' }}
    />
  );
}

const SKILLS = [
  { cat: 'Backend',      name: 'Spring Boot',   prof: 5, cost: 800, slug: 'springboot' },
  { cat: 'Backend',      name: 'Kafka',         prof: 5, cost: 700, slug: 'apachekafka' },
  { cat: 'Backend',      name: 'Microservices', prof: 4, cost: 500, slug: null },
  { cat: 'Backend',      name: 'Hibernate',     prof: 4, cost: 350, slug: 'hibernate' },
  { cat: 'Backend',      name: 'RunDeck',       prof: 3, cost: 280, slug: 'rundeck' },
  { cat: 'Backend',      name: 'Camunda BPMN',  prof: 3, cost: 320, slug: 'camunda' },
  { cat: 'Data / DB',    name: 'PostgreSQL',    prof: 5, cost: 500, slug: 'postgresql' },
  { cat: 'Data / DB',    name: 'Redis',         prof: 5, cost: 450, slug: 'redis' },
  { cat: 'Data / DB',    name: 'ClickHouse',    prof: 4, cost: 600, slug: 'clickhouse' },
  { cat: 'Data / DB',    name: 'MongoDB',       prof: 3, cost: 300, slug: 'mongodb' },
  { cat: 'Data / DB',    name: 'Neo4j',         prof: 3, cost: 280, slug: 'neo4j' },
  { cat: 'Data / DB',    name: 'SQL',           prof: 5, cost: 150, slug: 'sqlite' },
  { cat: 'Infra',        name: 'Docker',        prof: 4, cost: 300, slug: 'docker' },
  { cat: 'Infra',        name: 'Kubernetes',    prof: 3, cost: 550, slug: 'kubernetes' },
  { cat: 'Infra',        name: 'AWS',           prof: 3, cost: 480, slug: null, goldSrc: 'https://api.iconify.design/mdi/aws.svg?color=%23d4a843', brandSrc: 'https://api.iconify.design/mdi/aws.svg?color=%23ff9900' },
  { cat: 'Infra',        name: 'GCP',           prof: 3, cost: 400, slug: 'googlecloud' },
  { cat: 'Infra',        name: 'Jenkins',       prof: 3, cost: 220, slug: 'jenkins' },
  { cat: 'Infra',        name: 'New Relic',     prof: 3, cost: 200, slug: 'newrelic' },
  { cat: 'Languages',    name: 'Java',          prof: 5, cost: 200, slug: 'openjdk' },
  { cat: 'Languages',    name: 'C++',           prof: 3, cost: 220, slug: 'cplusplus' },
  { cat: 'Languages',    name: 'Python',        prof: 3, cost: 180, slug: 'python' },
  { cat: 'Languages',    name: 'Cypher',        prof: 3, cost: 160, slug: 'neo4j' },
];
const SKILL_CATS = ['All loadouts', 'Backend', 'Data / DB', 'Infra', 'Languages'];

const PROJECTS = [
  {
    codename: 'PROJECT  SPECTRE',
    type: 'backend', typeLabel: 'CLI TOOL',
    difficulty: 4,
    hook: 'Git push → Obsidian wiki — LLM writes structured specs from every diff, zero friction.',
    detail: 'Global pre-push hook fires on every repo automatically. Agentic tool-use loop: search vault → read context → write structured spec → update index. 5 pluggable backends: Claude, Ollama, Gemini, GitHub Models, Groq.',
    tags: ['Python', 'Claude API', 'Ollama', 'Gemini', 'PyPI', 'Obsidian'],
    status: 'live', statusLabel: '⧗ LIVE',
    hasLive: false,
    github: 'https://github.com/visheshchaitanya/spec-agent',
    statsUrl: 'https://pypistats.org/packages/spec-agent',
  },
  {
    codename: 'PROJECT  VITALS',
    type: 'backend', typeLabel: 'MOBILE APP',
    difficulty: 3,
    hook: 'Warfarin INR tracker — photo your lab report, OCR extracts readings. No manual entry.',
    detail: 'Expo + TypeScript mobile app for warfarin patients. OCR pipeline parses unstructured lab report photos/PDFs — extracts INR value + date across wildly varying hospital formats. Supabase auth + row-level security for personal health data isolation. Zustand + Expo Router v3 for fast offline-capable UX.',
    tags: ['React Native', 'Expo', 'TypeScript', 'Supabase', 'Zustand'],
    status: 'shipped', statusLabel: '✓ SHIPPED',
    hasLive: false,
    github: 'https://github.com/visheshchaitanya/inr-tracker',
  },
];

const ACHIEVEMENTS = [
  { mvp: true,  rank: 'MVP', ach: 'Kafka Real-time Ingestion',      impact: '120x latency',   scale: 'Real-time',   stack: 'Kafka·Java',  status: 'shipped', statusLabel: '✓ SHIPPED' },
  { mvp: false, rank: '02',  ach: 'Redis Caching Infrastructure',   impact: '−80% DB hits',   scale: '10x P95',     stack: 'Redis',       status: 'shipped', statusLabel: '✓ SHIPPED' },
  { mvp: false, rank: '03',  ach: 'Neo4j → PG/CH Migration',        impact: '−$36K/yr',       scale: 'Full prod',   stack: 'PG·CH',       status: 'shipped', statusLabel: '✓ SHIPPED' },
  { mvp: false, rank: '04',  ach: 'Bulk Upload Engine',             impact: '400% efficiency', scale: '10K+ decl.',  stack: 'Java·PG',     status: 'shipped', statusLabel: '✓ SHIPPED' },
  { mvp: false, rank: '05',  ach: 'SOAP → REST Migration',          impact: '+40% interop',   scale: '−1/3 costs',  stack: 'Spring·Java', status: 'shipped', statusLabel: '✓ SHIPPED' },
  { mvp: false, rank: '06',  ach: 'Multi-Tenant Architecture',      impact: '25 countries',   scale: 'Full prod',   stack: 'Java·PG',     status: 'live',    statusLabel: '⧗ LIVE' },
];

const FEED = [
  { time: 'now',        chip: 'wip',       chipLbl: 'WIP',
    parts: [{t: 'Refactoring ingestion to '}, {t: 'fabric-level multi-threaded', cls: 'gold'}, {t: ' architecture — targeting '}, {t: '−80% pod count', cls: 'blue'}, {t: '.'}] },
  { time: '2h ago',     chip: 'commit',    chipLbl: 'COMMIT',
    parts: [{t: 'Redis caching for security APIs — '}, {t: '80% DB hits eliminated', cls: 'gold'}, {t: ', '}, {t: '10x P95 improvement', cls: 'green'}, {t: '. Shipped.'}] },
  { time: 'yesterday',  chip: 'commit',    chipLbl: 'COMMIT',
    parts: [{t: 'Neo4j → PostgreSQL/ClickHouse migration complete — '}, {t: '$36K+ annual cost', cls: 'gold'}, {t: ' eliminated. '}, {t: 'Shipped.', cls: 'green'}] },
  { time: '3d ago',     chip: 'planned',   chipLbl: 'PLANNED',
    parts: [{t: 'Scoping '}, {t: 'ClickHouse materialized views', cls: 'blue'}, {t: ' for real-time security event severity aggregation.'}] },
  { time: '1w ago',     chip: 'research',  chipLbl: 'RESEARCH',
    parts: [{t: 'Evaluating '}, {t: 'KEDA autoscaling patterns', cls: 'blue'}, {t: ' for Kafka consumer group dynamic scaling.'}] },
];

const EXPLORING = [
  { name: 'AI Agents & LLMs',        desc: 'Tool-use pipelines · Claude Code',    pct: 65 },
  { name: 'ClickHouse Deep-Dive',    desc: 'Materialized views · MergeTree',      pct: 55 },
  { name: 'Distributed Systems',     desc: 'RAFT consensus · CRDTs',              pct: 45 },
  { name: 'Performance Engineering', desc: 'JVM tuning · async profiling',        pct: 40 },
];

// ============== SHARED HOOK: in-view ==============
function useInView(threshold = 0.25) {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) setInView(true); },
      { threshold }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return [ref, inView];
}

// ============== DOSSIER DATA ==============
const DOSSIER_LEVELS = [
  { level: '01', type: 'training', status: 'unlocked',
    period: 'APR 2017 — APR 2018', title: 'CLASS XII · SCIENCE (PCM)',
    org: 'NK Bagrodia Public School · New Delhi',
    detail: '90% aggregate · Physics, Chemistry, Mathematics',
    tags: ['Physics', 'Chemistry', 'Mathematics'], xp: 250 },
  { level: '02', type: 'training', status: 'unlocked',
    period: 'AUG 2018 — MAY 2022', title: 'B.E. ELECTRONICS & COMMUNICATION',
    org: 'NSIT · New Delhi',
    detail: '82% aggregate · Algorithms, Data Structures, Networks, OS, System Design',
    tags: ['C++', 'Java', 'DSA', 'Networks', 'OS'], xp: 1500 },
  { level: '03', type: 'deployment', status: 'unlocked',
    period: 'JUL 2022 — FEB 2024', title: 'SDE · DP WORLD CUSTOMS',
    org: 'DP World · Gurugram',
    detail: 'Email migration +30% delivery · 200+ bug fixes · Multi-tenant 25 countries',
    tags: ['Java', 'Spring Boot', 'SendGrid', 'PostgreSQL', 'MongoDB'], xp: 3000 },
  { level: '04', type: 'deployment', status: 'unlocked',
    period: 'MAR 2024 — MAY 2025', title: 'SDE I · DP WORLD CUSTOMS',
    org: 'DP World · Gurugram',
    detail: 'Bulk Upload 10K+ decl · SOAP→REST +40% interop · Camunda BPMN scheduling −80% time',
    tags: ['Java', 'Camunda', 'Quartz', 'Jaspersoft', 'PostgreSQL'], xp: 6000 },
  { level: '05', type: 'active', status: 'active',
    period: 'MAY 2025 — PRESENT', title: 'SENIOR SWE · QUILR AI',
    org: 'QuilrAI · Remote, New Delhi',
    detail: 'Kafka 120x latency · Neo4j→PG/CH −$36K/yr · Redis −80% DB hits',
    tags: ['Java', 'Kafka', 'PostgreSQL', 'Redis', 'ClickHouse'], xp: null },
  { level: '06', type: 'locked', status: 'locked',
    period: '???', title: 'NEXT DEPLOYMENT',
    org: 'CLASSIFIED', detail: 'Clearance pending...', tags: [], xp: null },
];

function DossierModal({ open, onClose }) {
  const [revealed, setRevealed] = useState(0);

  useEffect(() => {
    if (!open) { setRevealed(0); return; }
    let i = 0;
    const unlockedCount = DOSSIER_LEVELS.filter(l => l.status !== 'locked').length;
    const id = setInterval(() => {
      i++;
      setRevealed(i);
      if (i >= unlockedCount) clearInterval(id);
    }, 180);
    return () => clearInterval(id);
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div className="dossier-overlay" onClick={onClose}>
      <div className="dossier-modal" onClick={e => e.stopPropagation()}>
        <div className="dossier-header">
          <span className="dossier-tag">[ OPERATOR INFORMATION ]</span>
          <span className="dossier-clearance">CLEARANCE: SENIOR · V1.0</span>
          <button className="dossier-close" onClick={onClose}>✕ CLOSE</button>
        </div>
        <div className="dossier-body">
          <div className="dossier-left">
            <div className="dossier-avatar">
              <img
                className="dossier-avatar-photo"
                src={OPERATOR_IMAGE_SRC}
                alt="Vishesh Chaitanya"
                loading="lazy"
                draggable="false"
              />
              <span className="c-bl" /><span className="c-br" />
            </div>
            <div className="dossier-callsign">[ CALLSIGN: V1SHESH ]</div>
            <div className="dossier-name">VISHESH CHAITANYA</div>
            <div className="dossier-role">SENIOR SWE · BACKEND</div>
            <div className="dossier-divider" />
            <div className="dossier-stat-row"><span>STATUS</span><span className="d-green">● DEPLOYED</span></div>
            <div className="dossier-stat-row"><span>YRS ACTIVE</span><span>4+</span></div>
            <div className="dossier-stat-row"><span>LOCATION</span><span>DELHI/NCR</span></div>
            <div className="dossier-stat-row"><span>CLEARANCE</span><span className="d-gold">SENIOR</span></div>
            <div className="dossier-stat-row"><span>STACK</span><span>JAVA · KAFKA</span></div>
            <div className="dossier-divider" />
            <div className="dossier-total-xp">
              <div className="dossier-xp-label">TOTAL XP EARNED</div>
              <div className="dossier-xp-val">10,750 XP</div>
            </div>
          </div>
          <div className="dossier-right">
            <div className="dossier-timeline-hdr">MISSION HISTORY · CHRONOLOGICAL ORDER</div>
            {DOSSIER_LEVELS.map((lvl, i) => {
              const isRevealed = lvl.status === 'locked' || i < revealed;
              return (
                <div key={i} className={`dossier-level ${lvl.status} ${isRevealed ? 'revealed' : ''}`}>
                  <div className="dossier-level-left">
                    <div className="dossier-lvl-badge">{lvl.status === 'locked' ? '⚿' : `LVL ${lvl.level}`}</div>
                    {i < DOSSIER_LEVELS.length - 1 && <div className="dossier-connector" />}
                  </div>
                  <div className="dossier-level-card">
                    <div className="dossier-card-top">
                      <span className="dossier-period">{lvl.period}</span>
                      <span className={`dossier-status-chip ${lvl.status}`}>
                        {lvl.status === 'unlocked' ? '✓ UNLOCKED' : lvl.status === 'active' ? '◉ ACTIVE' : '⚿ LOCKED'}
                      </span>
                    </div>
                    <div className="dossier-lvl-title">{lvl.title}</div>
                    <div className="dossier-lvl-org">{lvl.org}</div>
                    {lvl.status !== 'locked' && (
                      <div className="dossier-lvl-detail">{lvl.detail}</div>
                    )}
                    {lvl.tags.length > 0 && (
                      <div className="dossier-lvl-tags">
                        {lvl.tags.map(t => <span className="tag" key={t}>{t}</span>)}
                      </div>
                    )}
                    {lvl.xp !== null && (
                      <div className="dossier-xp-gained">+{lvl.xp.toLocaleString()} XP</div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ============== TARGET ANALYSIS HERO ==============

function TypeWriter({ text, play, speed = 28 }) {
  const [count, setCount] = useState(0);
  useEffect(() => {
    if (!play) { setCount(0); return; }
    if (count >= text.length) return;
    const t = setTimeout(() => setCount(c => c + 1), speed);
    return () => clearTimeout(t);
  }, [play, count, text, speed]);
  return (
    <span>
      {text.substring(0, count)}
      {play && count < text.length && <span className="tw-cursor">█</span>}
    </span>
  );
}

const ANALYSIS_FIELDS = [
  { id: 'callsign',  label: 'CALLSIGN',     value: 'V1SHESH',                  accent: 'gold',  delay: 500  },
  { id: 'name',      label: 'OPERATOR',     value: 'VISHESH CHAITANYA',        accent: null,    delay: 900  },
  { id: 'role',      label: 'DESIGNATION',  value: 'SENIOR SOFTWARE ENGINEER', accent: null,    delay: 1300 },
  { id: 'status',    label: 'STATUS',       value: '● DEPLOYED',               accent: 'green', delay: 1700 },
  { id: 'location',  label: 'LOCATION',     value: 'DELHI/NCR · INDIA',        accent: null,    delay: 2000 },
  { id: 'exp',       label: 'EXPERIENCE',   value: '4+ YEARS ACTIVE',          accent: null,    delay: 2200 },
  { id: 'clearance', label: 'CLEARANCE',    value: 'SENIOR',                   accent: 'gold',  delay: 2500 },
];

const HERO_STACK = [
  { name: 'Java · Spring Boot',    pct: 95, color: 'gold' },
  { name: 'Kafka · Microservices', pct: 88, color: 'gold' },
  { name: 'PostgreSQL · Redis',    pct: 92, color: 'blue' },
];

const HERO_METRICS = [
  { val: '4+',   lbl: 'YRS ACTIVE' },
  { val: '120x', lbl: 'LATENCY GAIN' },
  { val: '$36K', lbl: 'SAVED/YR' },
  { val: '10M+', lbl: 'EVENTS/DAY' },
];

function TargetAnalysis({ onOpenDossier }) {
  const [vis, setVis] = useState(new Set());
  const [avatarBroken, setAvatarBroken] = useState(false);
  const [glassShards, setGlassShards] = useState([]);

  useEffect(() => {
    const TIMINGS = [
      ['header',  0],
      ['avatar',  600],
      ...ANALYSIS_FIELDS.map(f => [f.id, f.delay]),
      ['match',   2800],
      ['stack',   3100],
      ['metrics', 3800],
      ['cta',     4400],
    ];
    const timers = TIMINGS.map(([id, delay]) =>
      setTimeout(() => setVis(prev => new Set([...prev, id])), delay)
    );
    return () => timers.forEach(clearTimeout);
  }, []);

  const show = id => vis.has(id);
  const scanning = show('avatar') && !show('match');
  const matched  = show('match');
  const avatarVisible = show('avatar');

  const shatterAvatar = useCallback(() => {
    if (!avatarVisible || avatarBroken) return;
    const shards = Array.from({ length: 18 }, () => {
      const x = 14 + Math.random() * 136;
      const y = 14 + Math.random() * 136;
      const size = 10 + Math.random() * 18;
      const shardHeight = Math.max(8, size - 3);
      return {
        id: `${Date.now()}-${Math.random()}`,
        x,
        y,
        tx: -22 + Math.random() * 44,
        ty: Math.max(8, 160 - y - shardHeight),
        rot: -70 + Math.random() * 140,
        dur: 520 + Math.random() * 260,
        delay: Math.random() * 140,
        size,
      };
    });
    setGlassShards(shards);
    setAvatarBroken(true);
  }, [avatarBroken, avatarVisible]);

  useEffect(() => {
    if (!glassShards.length) return;
    const t = setTimeout(() => setGlassShards([]), 2300);
    return () => clearTimeout(t);
  }, [glassShards]);

  return (
    <div className="ta-wrap">

      <div className={`ta-header${show('header') ? ' visible' : ''}`}>
        <span className="ta-header-icon">◈</span>
        <span className="ta-header-text">INITIATING TARGET ANALYSIS...</span>
        <div className={`ta-progress${show('header') ? ' filling' : ''}`}>
          <div className="ta-progress-fill" />
        </div>
        <span className="ta-header-pct">100%</span>
      </div>

      <div className="ta-body">
        <div className={`ta-left${avatarVisible ? ' visible' : ''}`}>
          <div
            className={`ta-avatar-box${scanning ? ' scanning' : ''}${matched ? ' matched' : ''}${avatarBroken ? ' broken' : ''}`}
            onClick={shatterAvatar}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                shatterAvatar();
              }
            }}
            aria-label="Shoot to reveal operator photo"
          >
            <span className="ta-corner tl" /><span className="ta-corner tr" />
            <span className="ta-corner bl" /><span className="ta-corner br" />
            {scanning && <div className="ta-scan-line" />}
            <img
              className={`ta-avatar-photo${avatarBroken ? ' visible' : ''}`}
              src={OPERATOR_IMAGE_SRC}
              alt="Vishesh Chaitanya portrait"
              loading="lazy"
              draggable="false"
            />
            <div className={`ta-avatar-initials${avatarBroken ? ' hidden' : ''}`}>
              {avatarVisible && <TypeWriter text="VC" play speed={90} />}
            </div>
            <div className="ta-avatar-grid" />
            <div className={`ta-glass-overlay${avatarBroken ? ' shatter' : ''}`} />
            <div className={`ta-shoot-hint${avatarBroken ? ' revealed' : ''}`}>
              {!avatarBroken ? 'SHOOT TO REVEAL' : ''}
            </div>
            {glassShards.map((shard) => (
              <span
                key={shard.id}
                className="ta-glass-shard"
                style={{
                  left: `${shard.x}px`,
                  top: `${shard.y}px`,
                  width: `${shard.size}px`,
                  height: `${Math.max(8, shard.size - 3)}px`,
                  '--tx': `${shard.tx}px`,
                  '--ty': `${shard.ty}px`,
                  '--rot': `${shard.rot}deg`,
                  '--dur': `${shard.dur}ms`,
                  '--delay': `${shard.delay}ms`,
                }}
              />
            ))}
          </div>
          <div className={`ta-match-badge${matched ? ' visible' : ''}`}>
            <span className="ta-match-dot" />IDENTITY VERIFIED
          </div>
          <div className="ta-sig-row">
            {[1,2,3,4,5].map(i => (
              <div key={i} className={`ta-sig-bar h${i}${matched ? ' on' : ''}`} />
            ))}
            <span className="ta-sig-label">{matched ? 'SIGNAL: 5/5' : 'SIGNAL: --'}</span>
          </div>
        </div>

        <div className="ta-right">
          {ANALYSIS_FIELDS.map(f => (
            <div key={f.id} className={`ta-field${show(f.id) ? ' visible' : ''}`}>
              <span className="ta-field-label">{f.label}</span>
              <span className="ta-field-sep">▸</span>
              <span className={`ta-field-value${f.accent ? ` ta-accent-${f.accent}` : ''}`}>
                {show(f.id) && <TypeWriter text={f.value} play speed={22} />}
              </span>
            </div>
          ))}
        </div>
      </div>

      <div className={`ta-section${show('stack') ? ' visible' : ''}`}>
        <div className="ta-section-hdr">
          <span>PRIMARY STACK</span>
          <span className="ta-section-line" />
        </div>
        {HERO_STACK.map((r, i) => (
          <div key={i} className="ta-srow">
            <span className="ta-srow-name">{r.name}</span>
            <div className="ta-srow-bar">
              <div
                className={`ta-srow-fill ${r.color}`}
                style={{ width: show('stack') ? `${r.pct}%` : '0%', transitionDelay: `${i * 130}ms` }}
              />
            </div>
            <span className="ta-srow-pct">{r.pct}%</span>
          </div>
        ))}
      </div>

      <div className={`ta-metrics${show('metrics') ? ' visible' : ''}`}>
        {HERO_METRICS.map((m, i) => (
          <div key={i} className="ta-metric" style={{ animationDelay: `${i * 90}ms` }}>
            <div className="ta-metric-val">{m.val}</div>
            <div className="ta-metric-lbl">{m.lbl}</div>
          </div>
        ))}
      </div>

      <div className={`ta-cta-wrap${show('cta') ? ' visible' : ''}`}>
        <button className="ta-cta" onClick={onOpenDossier}>
          <span className="ta-cta-chevron">▶▶</span>
          ACCESS FULL OPERATOR INFORMATION
          <span className="ta-cta-dash" />
        </button>
      </div>

    </div>
  );
}

// ============== SECTION 01 — BIO ==============
function SectionBio() {
  const [dossierOpen, setDossierOpen] = useState(false);
  return (
    <>
      <section
        className="section"
        id="sec-bio"
        data-screen-label="01 Profile"
        style={{ minHeight: 'calc(100vh - 76px)', justifyContent: 'space-between' }}
      >
        <TargetAnalysis onOpenDossier={() => setDossierOpen(true)} />
      </section>
      <DossierModal open={dossierOpen} onClose={() => setDossierOpen(false)} />
    </>
  );
}

// ============== SECTION 02 — EXPERIENCE ==============
function SectionExp() {
  return (
    <section className="section" id="sec-exp" data-screen-label="02 Deployment">
      <Header tag="02" title="Deployment" accent="History" meta="// 3 confirmed deployments" />
      <div className="section-rule" />
      <div className="exp-grid">
        {EXPERIENCE.map((e, i) => (
          <div className={`exp-card brackets ${e.cls}`} key={i}>
            <span className="br-bl" /><span className="br-br" />
            <div className={`exp-period ${e.dotCls}`}><span className="dot" />● {e.period}</div>
            <div className="exp-company">{e.company}</div>
            <div className="exp-role">{e.role}</div>
            <ul className="exp-desc">
              {e.desc.map((pt, j) => <li key={j}>{pt}</li>)}
            </ul>
            <div className="exp-tags">
              {e.tags.map(t => <span className="tag" key={t}>{t}</span>)}
            </div>
            <div className="exp-stat">↗ {e.stat}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============== SECTION 03 — EDUCATION ==============
function SectionEdu() {
  const [ref, inView] = useInView(0.25);
  return (
    <section className="section" id="sec-edu" data-screen-label="03 Training" ref={ref}>
      <Header tag="03" title="Training" accent="Ground" meta="// XP earned · honourable discharge" />
      <div className="section-rule" />
      <div className="edu-grid">
        <div className="edu-card brackets">
          <span className="br-bl" /><span className="br-br" />
          <div className="deg">B.E. — ELECTRONICS AND COMMUNICATION ENGINEERING</div>
          <div className="inst">// Netaji Subhash Institute of Technology · New Delhi</div>
          <div className="yr">Aug 2018 – May 2022</div>
          <div className="xp-row">
            <div className="xp-label"><span>Academic XP</span><span className="pct">82%</span></div>
            <div className="xp-bar"><div className="xp-fill" style={{ width: inView ? '82%' : '0%' }} /></div>
          </div>
          <div className="course-tags">
            {COURSEWORK.map(c => <span className="tag orange" key={c}>{c}</span>)}
          </div>

          <div className="edu-divider" />

          <div className="deg" style={{ fontSize: 11 }}>CLASS XII — SCIENCE (PCM)</div>
          <div className="inst">// NK Bagrodia Public School · New Delhi</div>
          <div className="yr">Apr 2017 – Apr 2018</div>
          <div className="xp-row">
            <div className="xp-label"><span>Academic XP</span><span className="pct">93%</span></div>
            <div className="xp-bar"><div className="xp-fill" style={{ width: inView ? '93%' : '0%', transitionDelay: '80ms' }} /></div>
          </div>
        </div>
        <div className="edu-side">
          <div className="edu-box brackets">
            <span className="br-bl" /><span className="br-br" />
            <div className="h">Competitive Programming</div>
            {CP_ROWS.map(r => (
              <div className="edu-row" key={r.term}>
                <span className="ico" style={{ color: 'var(--gold)' }}>{r.ico}</span>
                <span className="term">{r.term}</span>
                <span className="desc">{r.desc}</span>
              </div>
            ))}
          </div>
          <div className="edu-box brackets">
            <span className="br-bl" /><span className="br-br" />
            <div className="h">Field Ranks</div>
            {RANKS.map(r => (
              <div className="edu-row" key={r.term}>
                <span className="ico" style={{ color: 'var(--gold)' }}>{r.ico}</span>
                <span className="term">{r.term}</span>
                <span className="desc">{r.desc}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== SECTION 04 — ARSENAL ==============
function SectionArsenal() {
  const [cat, setCat] = useState('All loadouts');
  const [equipped, setEquipped] = useState(new Set());
  const filtered = cat === 'All loadouts' ? SKILLS : SKILLS.filter(s => s.cat === cat);

  const total = useMemo(() => {
    let sum = 0;
    SKILLS.forEach(s => { if (equipped.has(s.name)) sum += s.cost; });
    return sum;
  }, [equipped]);

  const toggle = (name) => {
    setEquipped(prev => {
      const next = new Set(prev);
      if (next.has(name)) next.delete(name); else next.add(name);
      return next;
    });
  };

  useEffect(() => {
    SKILLS.forEach(s => {
      const gold = s.goldSrc || (s.slug ? `https://cdn.simpleicons.org/${s.slug}/d4a843` : null);
      const brand = s.brandSrc || (s.slug ? `https://cdn.simpleicons.org/${s.slug}` : null);
      [gold, brand].forEach(url => { if (url) { const img = new Image(); img.src = url; } });
    });
  }, []);

  const countFor = (c) => c === 'All loadouts' ? SKILLS.length : SKILLS.filter(s => s.cat === c).length;

  return (
    <section className="section" id="sec-arsenal" data-screen-label="04 Arsenal">
      <Header tag="04" title="Arsenal" accent="Loadout" meta="// click to equip · hover to inspect" />
      <div className="section-rule" />
      <div className="arsenal" style={{ gridTemplateRows: '1fr auto' }}>
        <div className="arsenal-cats">
          {SKILL_CATS.map(c => (
            <button key={c} className={`arsenal-cat ${c === cat ? 'active' : ''}`} onClick={() => setCat(c)}>
              {c}<span className="count">{countFor(c)}</span>
            </button>
          ))}
        </div>
        <div className="arsenal-grid">
          {filtered.map(s => (
            <button
              key={s.name}
              className={`weapon ${equipped.has(s.name) ? 'equipped' : ''}`}
              onClick={() => toggle(s.name)}
            >
              <span className="ico"><SkillIcon slug={s.slug} equipped={equipped.has(s.name)} goldSrc={s.goldSrc} brandSrc={s.brandSrc} /></span>
              <span className="nm">{s.name}</span>
              <span className="pips">
                {[1,2,3,4,5].map(i => (
                  <span key={i} className={`pip ${i <= s.prof ? 'on' : ''}`} />
                ))}
              </span>
              <span className="cost">${s.cost}</span>
            </button>
          ))}
        </div>
        <div className="arsenal-foot">
          <span>[CLICK] equip · [HOVER] inspect</span>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginLeft: 'auto' }}>
            {equipped.size > 0 && (
              <button
                onClick={() => setEquipped(new Set())}
                style={{
                  background: 'none', border: '1px solid var(--text-dim)', color: 'var(--text-dim)',
                  padding: '2px 8px', fontSize: 10, letterSpacing: '0.08em', cursor: 'pointer',
                  fontFamily: 'inherit',
                }}
              >
                RESET
              </button>
            )}
            <span className="total">EQUIPPED<span className="num">${total}</span></span>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== SECTION 05 — MISSION BRIEFING ==============
function SectionProjects() {
  return (
    <section className="section" id="sec-projects" data-screen-label="05 Missions">
      <Header tag="05" title="Mission" accent="Briefing" meta="// hover to declassify" />
      <div className="section-subtag">
        <span>MISSION COUNT: <b>{PROJECTS.length}</b></span>
        <span>CLEARANCE: <b>SENIOR</b></span>
        <span>OPERATIVES DEPLOYED: <b>01</b></span>
      </div>
      <div className="section-rule" />
      <div className="proj-grid">
        {PROJECTS.map((p, i) => (
          <div key={i} className={`proj-card brackets ${p.type}`}>
            <span className="br-bl" /><span className="br-br" />
            <div className="proj-classified">CLASSIFIED</div>
            <div className="proj-content">
              <div className="proj-top">
                <span className={`proj-type ${p.type}`}>[ {p.typeLabel} ]</span>
                <span className="proj-difficulty">
                  {'★'.repeat(p.difficulty)}<span style={{ color: 'var(--text-dim)' }}>{'★'.repeat(5 - p.difficulty)}</span>
                </span>
              </div>
              <div className="proj-name">{p.codename}</div>
              <div className="proj-hook">{p.hook}</div>
              <div className="proj-detail">{p.detail}</div>
              <div className="proj-tags">
                {p.tags.map(t => <span className="tag" key={t}>{t}</span>)}
              </div>
              <div className="proj-foot">
                <div className="proj-links">
                  <a className="proj-link" href={p.github || '#'} target="_blank" rel="noopener noreferrer">⌥ GitHub</a>
                  {p.statsUrl && <a className="proj-link" href={p.statsUrl} target="_blank" rel="noopener noreferrer">⌥ Stats</a>}
                  {p.hasLive
                    ? <a className="proj-link" href="#">⌥ Live</a>
                    : <span className="proj-link classified">CLASSIFIED</span>}
                </div>
                <span className={`proj-status ${p.status}`}>{p.statusLabel}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============== SECTION 06 — OPERATION REPORT ==============
function SectionReport() {
  const [ref, inView] = useInView(0.3);
  const [score, setScore] = useState({ w: 0, l: 0 });

  useEffect(() => {
    if (!inView) return;
    let w = 0;
    const id = setInterval(() => {
      w += 1;
      setScore({ w, l: 0 });
      if (w >= 5) clearInterval(id);
    }, 220);
    return () => clearInterval(id);
  }, [inView]);

  return (
    <section className="section" id="sec-report" data-screen-label="06 Report" ref={ref}>
      <Header tag="06" title="Operation" accent="Report" meta="// round over · mvp highlights" />
      <div className="section-rule" />
      <div className="score-top brackets">
        <span className="br-bl" /><span className="br-br" />
        <div className="score-map"><span className="pre">MAP</span>ops_backend_systems</div>
        <div className="score-display">
          <span className="win">{score.w}</span>
          <span className="colon">:</span>
          <span className="lose">{score.l}</span>
        </div>
        <div className="score-side"><span className="accent">ROUND OVER</span> · MVP HIGHLIGHTS</div>
      </div>
      <div className="score-table brackets">
        <span className="br-bl" /><span className="br-br" />
        <div className="score-row header">
          <span>RANK</span><span>ACHIEVEMENT</span><span>IMPACT</span><span>SCALE</span><span>STACK</span><span>STATUS</span>
        </div>
        {ACHIEVEMENTS.map((a, i) => (
          <div key={i} className={`score-row data ${a.mvp ? 'mvp' : ''}`}>
            <span className="rank">{a.mvp ? <span className="rank-badge">MVP</span> : a.rank}</span>
            <span className="ach">{a.ach}</span>
            <span className="impact">{a.impact}</span>
            <span className="scale">{a.scale}</span>
            <span className="stack">{a.stack}</span>
            <span className="status"><span className={`chip ${a.status}`}>{a.statusLabel}</span></span>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============== SECTION 07 — LIVE ==============
function SectionLive() {
  const [ref, inView] = useInView(0.25);
  const [elapsed, setElapsed] = useState(0);
  useEffect(() => {
    const start = Date.now();
    const id = setInterval(() => setElapsed(Math.floor((Date.now() - start) / 1000)), 1000);
    return () => clearInterval(id);
  }, []);
  const fmt = (s) => {
    const h = Math.floor(s / 3600).toString().padStart(2, '0');
    const m = Math.floor((s % 3600) / 60).toString().padStart(2, '0');
    const sec = (s % 60).toString().padStart(2, '0');
    return `${h}:${m}:${sec}`;
  };

  return (
    <section className="section" id="sec-live" data-screen-label="07 Live" ref={ref}>
      <Header tag="07" title="Live" accent="Feed" meta="// active build · realtime" />
      <div className="section-rule" />
      <div className="live-grid">
        <div className="live-panel brackets">
          <span className="br-bl" /><span className="br-br" />
          <div className="live-head">
            <span className="live-badge"><span className="dot" />LIVE</span>
            <span className="live-title">ACTIVE BUILD · SECURITY PLATFORM</span>
            <span className="live-timer">SESSION {fmt(elapsed)}</span>
          </div>
          {FEED.map((f, i) => (
            <div className="feed-row" key={i}>
              <span className="feed-time">{f.time}</span>
              <span className="feed-desc">
                {f.parts.map((p, j) => p.cls
                  ? <span key={j} className={p.cls}>{p.t}</span>
                  : <React.Fragment key={j}>{p.t}</React.Fragment>
                )}
              </span>
              <span className={`feed-chip ${f.chip}`}>{f.chipLbl}</span>
            </div>
          ))}
        </div>
        <div className="explore-card brackets">
          <span className="br-bl" /><span className="br-br" />
          <div className="h">Currently Exploring</div>
          <div className="sub">// next deployment vectors</div>
          {EXPLORING.map((e, i) => (
            <div className="explore-item" key={i}>
              <div className="top">
                <span className="nm">{e.name}</span>
                <span className="pct">{e.pct}%</span>
              </div>
              <div className="desc">{e.desc}</div>
              <div className="bar"><div className="bar-fill" style={{ width: inView ? `${e.pct}%` : '0%', transitionDelay: `${i * 100}ms` }} /></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============== HEADER HELPER ==============
function Header({ tag, title, accent, meta }) {
  return (
    <div className="section-header">
      <span className="section-tag">[ {tag} ]</span>
      <h2 className="section-title">{title} <span className="accent">{accent}</span></h2>
      <span className="section-meta">{meta}</span>
    </div>
  );
}

Object.assign(window, {
  SectionBio, SectionExp, SectionEdu, SectionArsenal, SectionProjects, SectionReport, SectionLive
});
