// @ts-nocheck
import * as React from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
export function RoadmapPage() {
  const eras = [
    {
      id: 'solo',
      title: 'VOID::NAV — Single-Player Open-World RPG',
      subtitle: 'Build the core adventure game locally. SpacetimeDB runs on the local machine from Phase 0 — there is no localStorage. One browser window, one captain, one procedurally generated galaxy to explore. Every feature is designed to be fun solo first.',
      accent: 'var(--accent)',
      phases: [
        {
          num: '0',
          title: 'Local Skeleton & Star System',
          goal: 'Vite app with local SpacetimeDB instance, rendered star system with station and asteroids. Player can connect and see the void.',
          doneWhen: 'App boots, connects to local SpacetimeDB instance. Shows a star system with a station and 3 asteroids. Ship visible in 3D viewport. Game state persists in SpacetimeDB — no localStorage.',
          status: 'current',
        },
        {
          num: '1',
          title: 'Navigation & Exploration',
          goal: 'Click-to-navigate autopilot with smooth ship movement. Warp-to for distant objects. Explore POIs within a system.',
          doneWhen: 'Click an asteroid, station, or anomaly. Ship plots a course and moves there with smooth interpolation. ETA display updates. Warp-to for distant objects works. Player can freely navigate the star system.',
          status: 'upcoming',
        },
        {
          num: '2',
          title: 'Mining, Inventory & Trade',
          goal: 'Asteroid mining cycle, ore extraction, cargo hold. NPC market for buying/selling goods. Regional price differences between stations.',
          doneWhen: 'Approach asteroid, start mining. Mining cycle shows progress. Ore appears in cargo. Dock at station, sell ore for ISK. Fly to another station — prices are different. Buy low / sell high works.',
          status: 'upcoming',
        },
        {
          num: '3',
          title: 'Combat — FTL Power Allocation',
          goal: 'Auto-engage combat with reactor power management between weapons / shields / engines. Encounter NPC pirates at belts and anomalies.',
          doneWhen: 'Target a hostile NPC at a belt or anomaly. Ship auto-engages. Player shifts reactor power between subsystems (FTL-style). Power allocation visibly changes combat outcome. Ship can be destroyed. NPC pirates drop loot and bounty.',
          status: 'upcoming',
        },
        {
          num: '4',
          title: 'Ship Customization & Upgrades',
          goal: 'Multiple ship classes (scout, hauler, warship). Module fitting with High/Med/Low slots. CPU/PG constraints. Buy new ships at stations.',
          doneWhen: 'Dock at station. Open fitting screen. Equip weapons in high slots, shield booster in mid, cargo expander in low. Fitting affects combat and trade stats. Can buy a new ship class. Invalid fits rejected (insufficient CPU/PG).',
          status: 'upcoming',
        },
        {
          num: '5',
          title: 'Faction Quests & Dynamic World',
          goal: 'NPC agents offer quests (kill, courier, mining, exploration). Faction standing system. Station prosperity responds to player supply. Dynamic world events spawn.',
          doneWhen: 'Talk to NPC agent at station. Accept a quest (deliver cargo, kill pirates, explore anomaly). Complete quest for ISK + standing. Standing unlocks better quests and prices. Supplying a station increases its prosperity. World events spawn in explored systems.',
          status: 'upcoming',
        },
        {
          num: '6',
          title: 'Industry & Economy Depth',
          goal: 'Refining ore into minerals. Manufacturing modules and items. Full NPC market with supply/demand. Price history and regional differences.',
          doneWhen: 'Dock with ore. Refine at station. Minerals appear in hangar. Open manufacturing tab, select a blueprint, queue a job. Job completes. Product appears. Sell on NPC market. Prices react to trades. Different stations have different prices.',
          status: 'upcoming',
        },
        {
          num: '7',
          title: 'Single-Player Polish & Procedural Galaxy',
          goal: 'Procedurally generated multi-system galaxy. Fog of war. Full HUD. Notifications. Tutorial sequence. Ship AI companion (Zora Tier 0). Save/load.',
          doneWhen: 'Full game loop is playable solo: explore → mine → trade → quest → fight → upgrade → explore deeper. Procedural galaxy generates unique systems each campaign. Fog of war reveals as you travel. HUD shows all relevant info. Tutorial guides new players through first 30 minutes. SpacetimeDB persists all state.',
          status: 'future',
        },
      ],
    },
    {
      id: 'multi',
      title: 'Optional — Co-op Servers',
      subtitle: 'Promote local SpacetimeDB to a shared server for small co-op crews. Same adventure, shared with friends. Entirely optional — the core game is complete without this.',
      accent: 'var(--cyan)',
      phases: [
        {
          num: '8',
          title: 'Shared Server Skeleton',
          goal: 'Promote local SpacetimeDB to a shared server. Multiple clients connect and see the same state.',
          doneWhen: 'Two browser windows connect to the same SpacetimeDB instance. Both see the same star system state. One client issues a move command, the other sees it. Connection status indicator works.',
          status: 'future',
        },
        {
          num: '9',
          title: 'Co-op Presence & Movement',
          goal: 'Players see each other in real time. Movement is server-authoritative with client-side interpolation. Small crew exploration.',
          doneWhen: 'Two players in the same system. Each sees the other\'s ship. Click-to-move sends reducer, server validates, all clients interpolate movement. No desync under normal latency.',
          status: 'future',
        },
        {
          num: '10',
          title: 'Shared Market & Trading',
          goal: 'Player-to-player trading. Buy/sell orders between co-op crew members. Shared price discovery.',
          doneWhen: 'Player A places a sell order. Player B sees it in the market table and buys. ISK and items transfer atomically. Order book shows depth. Market history is shared.',
          status: 'future',
        },
        {
          num: '11',
          title: 'Chat & Communication',
          goal: 'Local chat for co-op crew, delayed comms for immersion.',
          doneWhen: 'Players in the same system see chat in real time. PMs arrive with light-speed delay. Crew can coordinate exploration.',
          status: 'future',
        },
        {
          num: '12',
          title: 'Living Galaxy — World Agents + Ship AI Tier 1',
          goal: 'Background agent scheduler (BitCraft model). NPC trade convoys, faction skirmishes, anomaly spawns, migration routes. Ship AI promoted to LLM-assisted dialogue.',
          doneWhen: 'Server spawns world events without player input. Events appear in the galaxy story log. Faction borders shift over time. Anomalies appear and expire. A returning player sees the galaxy has changed. Tier 1 Zora: soul.md as real system prompt, LLM-generated dialogue, comms module enables natural language responses.',
          status: 'future',
        },
        {
          num: '13',
          title: 'Co-op Combat',
          goal: 'Crew members fight together. Multiple ships in an engagement. Coordinate against tough NPCs.',
          doneWhen: 'Two players engage each other. Both manage power allocation. Server resolves combat ticks authoritatively. Both clients see damage applied. Loser\'s ship drops loot (or wreck). Kill log records the event.',
          status: 'future',
        },
        {
          num: '14',
          title: 'Crews & Shared Progress',
          goal: 'Form a persistent crew. Shared wallet, coordinated objectives, crew-level progression.',
          doneWhen: 'Players form a corp. Corp can anchor a structure in a system. Structure provides bonuses (refining yield, market tax). Sovereignty map shows corp-held systems. Rival corps can contest.',
          status: 'future',
        },
        {
          num: '15',
          title: 'Co-op Polish',
          goal: 'Polish pass on co-op features. Error handling, reconnection, scaling tests for small crews.',
          doneWhen: 'Fresh player can create account, complete the tutorial, explore, mine, trade, fight, and customize their ship — all without hitting a dead-end or a crash. Optionally, invite a friend to join the same server for co-op. Server handles a small crew of friends.',
          status: 'future',
        },
      ],
    },
  ];

  function PhaseItem({ phase, isLast }) {
    const statusStyle = phase.status === 'current'
      ? { background: 'var(--accent-bg)', color: 'var(--accent)', border: '1px solid var(--accent-border)' }
      : phase.status === 'upcoming'
        ? { background: 'var(--cyan-bg)', color: 'var(--cyan)', border: '1px solid rgba(34,211,238,0.25)' }
        : { background: 'var(--surface-raised)', color: 'var(--muted)', border: '1px solid var(--border)' };

    return (
      <div className="mb-5 flex gap-4">
        <div className="flex min-w-10 flex-col items-center">
          <div
            className={`size-3 rounded-full ${phase.status === 'future' ? 'bg-border-light shadow-none' : 'bg-accent shadow-[0_0_8px_rgba(240,160,48,0.3)]'}`}
            style={phase.status === 'current' ? {
              background: 'var(--accent)',
              boxShadow: '0 0 12px rgba(240,160,48,0.4)',
              animation: 'pulse 2s infinite',
            } : {}}
          />
          {!isLast && <div className="mt-1 w-0.5 flex-1 bg-border" />}
        </div>
        <div className="flex-1">
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--sp-3)', marginBottom: 'var(--sp-2)' }}>
            <span style={{
              fontFamily: 'var(--font-mono)',
              fontSize: '0.7rem',
              padding: '2px 8px',
              borderRadius: 'var(--radius-pill)',
              ...statusStyle,
            }}>
              PHASE {phase.num}
            </span>
            <h4 style={{ margin: 0 }}>{phase.title}</h4>
            {phase.status === 'current' && <span className="inline-flex items-center gap-1 whitespace-nowrap rounded-full px-2.5 py-0.5 font-mono text-[0.7rem] border border-[rgba(240,160,48,0.25)] bg-[rgba(240,160,48,0.08)] text-accent">IN PROGRESS</span>}
          </div>
          <p style={{ color: 'var(--fg-dim)', fontSize: '0.85rem', margin: '0 0 var(--sp-2) 0' }}>{phase.goal}</p>
          <div style={{ background: 'var(--surface-raised)', borderRadius: 'var(--radius-md)', padding: 'var(--sp-2) var(--sp-3)', fontSize: '0.8rem' }}>
            <span style={{ color: 'var(--muted)', fontFamily: 'var(--font-mono)', fontSize: '0.7rem' }}>DONE WHEN: </span>
            <span style={{ color: 'var(--fg-dim)' }}>{phase.doneWhen}</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-content">
      <h1 style={{ marginBottom: '8px' }}>Development Roadmap</h1>
      <p style={{ color: 'var(--fg-dim)', fontSize: '0.95rem', maxWidth: '720px' }}>
        Two eras, sixteen phases. <strong style={{ color: 'var(--fg)' }}>The core game</strong> is a single-player open-world space RPG
        with a local SpacetimeDB instance — exploration, trading, FTL-style combat, ship customization, and faction quests.
        <strong style={{ color: 'var(--fg)' }}>Optional co-op servers</strong> can be added later by promoting the local SpacetimeDB to a shared server.
        Each phase has a verifiable done-when condition. Integration gates between phase groups ensure every system works together before advancing.
      </p>

      <div className="mb-5 rounded-lg px-5 py-4 text-[0.85rem] leading-[1.5] border border-cyan/20 bg-cyan/8 text-cyan" style={{ marginTop: 'var(--sp-4)', maxWidth: '720px' }}>
        <strong>Why single-player with local SpacetimeDB?</strong> The game is a solo adventure — Windward Horizon in space. Networking is the biggest source of bugs and complexity.
        By validating that exploration, trading, combat, fitting, and faction quests are fun locally — using the <em>same</em> SpacetimeDB
        persistence that would serve co-op — we de-risk the entire project. There is no localStorage; SpacetimeDB is the
        persistence layer from day 1. If co-op is added later, the question is only &quot;how do we share this server?&quot; — not
        &quot;is this game fun?&quot; or &quot;will the persistence migration work?&quot;
      </div>

      <div className="mb-5 flex items-center gap-3 border-b border-border pb-3 max-md:flex-col max-md:items-start max-md:gap-2 max-md:[&_h1]:text-[1.35rem] max-md:[&_h2]:text-[1.35rem]" style={{ marginTop: 'var(--sp-8)' }}>
        <span className="rounded-full bg-[rgba(240,160,48,0.08)] px-2 py-0.5 font-mono text-[0.7rem] text-accent">IG</span>
        <h2 style={{ margin: 0 }}>Integration Gates</h2>
      </div>
      <p style={{ color: 'var(--fg-dim)', fontSize: '0.95rem', maxWidth: '720px', marginBottom: 'var(--sp-4)' }}>
        Between phase groups, an integration gate ensures all systems work together before new ones are added.
        A gate is a focused playtest that exercises every previously-built feature end-to-end.
      </p>
      <div className="grid grid-cols-2 gap-5 max-[900px]:grid-cols-1" style={{ marginBottom: 'var(--sp-6)' }}>
        <div className="mb-6 rounded-xl border border-border bg-surface p-6 max-md:rounded-lg max-md:p-4" style={{ borderLeft: '3px solid var(--accent)' }}>
          <h4 style={{ color: 'var(--accent)' }}>Gate 1 — Exploration & Trade Loop (after Phase 2)</h4>
          <p style={{ color: 'var(--fg-dim)', fontSize: '0.85rem', margin: '0 0 var(--sp-2) 0' }}>
            Navigate to asteroid → mine → fill cargo → dock → sell ore → navigate to another station → discover price difference → trade.
            The complete exploration and trade loop runs in a single session without errors. The galaxy feels alive and explorable.
            SpacetimeDB persists the session — closing the browser and reopening restores state.
          </p>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: '0.72rem', color: 'var(--muted)' }}>Phases covered: 0, 1, 2</div>
        </div>
        <div className="mb-6 rounded-xl border border-border bg-surface p-6 max-md:rounded-lg max-md:p-4" style={{ borderLeft: '3px solid var(--red)' }}>
          <h4 style={{ color: 'var(--red)' }}>Gate 2 — Combat + Customization (after Phase 4)</h4>
          <p style={{ color: 'var(--fg-dim)', fontSize: '0.85rem', margin: '0 0 var(--sp-2) 0' }}>
            Customize a ship at station → undock → encounter NPC pirate → manage FTL power allocation → destroy or be destroyed →
            collect loot → buy upgrades → try a different ship class. Combat and ship customization form a satisfying adventure loop.
          </p>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: '0.72rem', color: 'var(--muted)' }}>Phases covered: 0–4</div>
        </div>
        <div className="mb-6 rounded-xl border border-border bg-surface p-6 max-md:rounded-lg max-md:p-4" style={{ borderLeft: '3px solid var(--green)' }}>
          <h4 style={{ color: 'var(--green)' }}>Gate 3 — Full Adventure Loop (after Phase 6)</h4>
          <p style={{ color: 'var(--fg-dim)', fontSize: '0.85rem', margin: '0 0 var(--sp-2) 0' }}>
            Explore → mine ore → refine → manufacture a module → fit it → fight pirates → accept faction quest → deliver goods →
            earn standing → unlock better missions → sell excess across stations at different prices.
            The complete adventure: exploration, economy, industry, and faction systems work as an integrated whole.
          </p>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: '0.72rem', color: 'var(--muted)' }}>Phases covered: 0–6</div>
        </div>
        <div className="mb-6 rounded-xl border border-border bg-surface p-6 max-md:rounded-lg max-md:p-4" style={{ borderLeft: '3px solid var(--cyan)' }}>
          <h4 style={{ color: 'var(--cyan)' }}>Gate 4 — Core Game Complete (after Phase 7)</h4>
          <p style={{ color: 'var(--fg-dim)', fontSize: '0.85rem', margin: '0 0 var(--sp-2) 0' }}>
            Full solo game with all systems integrated: explore → mine → trade → quest → fight → customize → sail deeper.
            Procedurally generated galaxy. Fog of war. HUD, notifications, Zora Tier 0, world events, tutorial sequence.
            A new player can learn the game in one session and want to keep going. SpacetimeDB state survives restart.
          </p>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: '0.72rem', color: 'var(--muted)' }}>Phases covered: 0–7 (core game)</div>
        </div>
        <div className="mb-6 rounded-xl border border-border bg-surface p-6 max-md:rounded-lg max-md:p-4" style={{ borderLeft: '3px solid var(--purple)' }}>
          <h4 style={{ color: 'var(--purple)' }}>Gate 5 — Co-op Core (after Phase 10)</h4>
          <p style={{ color: 'var(--fg-dim)', fontSize: '0.85rem', margin: '0 0 var(--sp-2) 0' }}>
            Two players on the same server. Both see each other. Both can trade on the shared market. ISK and items
            transfer atomically. Movement is synced. Connection loss and reconnection work. The same solo adventure, shared with a friend.
          </p>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: '0.72rem', color: 'var(--muted)' }}>Phases covered: 8–10</div>
        </div>
        <div className="mb-6 rounded-xl border border-border bg-surface p-6 max-md:rounded-lg max-md:p-4" style={{ borderLeft: '3px solid var(--fg-dim)' }}>
          <h4 style={{ color: 'var(--fg-dim)' }}>Gate 6 — Co-op Ready (after Phase 15)</h4>
          <p style={{ color: 'var(--fg-dim)', fontSize: '0.85rem', margin: '0 0 var(--sp-2) 0' }}>
            Fresh player can: create account, complete tutorial, explore their first system, mine and trade, survive a PvE encounter,
            customize their ship, accept and complete a faction quest — and optionally invite a friend to share the adventure — all without crashes or dead ends.
            Server handles a small crew of friends.
          </p>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: '0.72rem', color: 'var(--muted)' }}>Phases covered: 0–15 (all)</div>
        </div>
      </div>

      <div style={{ marginTop: 'var(--sp-8)' }}>
        {eras.map((era, ei) => (
          <div key={era.id} style={{ marginBottom: ei < eras.length - 1 ? 'var(--sp-8)' : 0 }}>
            {/* Era header */}
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: 'var(--sp-4)',
              marginBottom: 'var(--sp-5)',
              paddingBottom: 'var(--sp-3)',
              borderBottom: `2px solid ${era.accent}`,
            }}>
              <span style={{
                fontFamily: 'var(--font-mono)',
                fontSize: '0.7rem',
                fontWeight: 700,
                letterSpacing: '0.08em',
                padding: '4px 12px',
                borderRadius: 'var(--radius-pill)',
                background: era.accent === 'var(--accent)' ? 'var(--accent-bg)' : 'var(--cyan-bg)',
                color: era.accent,
                border: `1px solid ${era.accent === 'var(--accent)' ? 'var(--accent-border)' : 'rgba(34,211,238,0.3)'}`,
              }}>
                ERA {ei + 1}
              </span>
              <div>
                <h2 style={{ margin: 0, fontSize: '1.1rem' }}>{era.title}</h2>
                <p style={{ color: 'var(--fg-dim)', fontSize: '0.82rem', margin: '4px 0 0 0' }}>{era.subtitle}</p>
              </div>
            </div>

            {/* Phase list */}
            {era.phases.map((phase, pi) => (
              <PhaseItem
                key={phase.num}
                phase={phase}
                isLast={pi === era.phases.length - 1}
              />
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}
