// Main App: navigation portal + category page + experiment routing

function App() {
  const [nav, setNav] = useState({ catKey: null, expId: null });

  const goHome = () => setNav({ catKey: null, expId: null });
  const goCategory = (catKey) => setNav({ catKey, expId: null });
  const openExp = (catKey, expId) => setNav({ catKey, expId });

  // Random experiment
  const goRandom = () => {
    const keys = Object.keys(CATEGORIES);
    const catKey = keys[Math.floor(Math.random() * keys.length)];
    const exps = CATEGORIES[catKey].experiments;
    const expId = exps[Math.floor(Math.random() * exps.length)].id;
    setNav({ catKey, expId });
  };

  // Scroll to categories
  const scrollToCategories = () => {
    const el = document.getElementById('categories-section');
    if (el) el.scrollIntoView({ behavior: 'smooth' });
  };

  // Experiment page
  if (nav.expId) {
    const cat = CATEGORIES[nav.catKey];
    return (
      <div className="app">
        <div className="app-header">
          <div className="app-title" style={{ cursor: 'pointer' }} onClick={goHome}>
            <div className="app-title-icon">
              <Icons.Atom />
            </div>
            <span>物探 Lab</span>
            <div className="breadcrumb">
              <span className="bc-link" onClick={goHome}>首页</span>
              <span className="bc-sep">/</span>
              <span className="bc-link" onClick={() => goCategory(nav.catKey)}>{cat.name}</span>
              <span className="bc-sep">/</span>
              <span className="bc-current">实验</span>
            </div>
          </div>
          <div className="app-header-actions">
            <button className="back-btn" onClick={() => goCategory(nav.catKey)}>
              <Icons.ArrowLeft />
              <span>返回实验列表</span>
            </button>
          </div>
        </div>
        <ExperimentView catKey={nav.catKey} expId={nav.expId} />
      </div>
    );
  }

  // Category listing page
  if (nav.catKey) {
    const cat = CATEGORIES[nav.catKey];
    const IconComp = Icons[cat.icon];
    return (
      <div className="app">
        <div className="app-header">
          <div className="app-title" style={{ cursor: 'pointer' }} onClick={goHome}>
            <div className="app-title-icon">
              <Icons.Atom />
            </div>
            <span>物探 Lab</span>
            <div className="breadcrumb">
              <span className="bc-link" onClick={goHome}>首页</span>
              <span className="bc-sep">/</span>
              <span className="bc-current">{cat.name}</span>
            </div>
          </div>
          <div className="app-header-actions">
            <button className="back-btn" onClick={goHome}>
              <Icons.ArrowLeft />
              <span>返回首页</span>
            </button>
          </div>
        </div>
        <CategoryPage catKey={nav.catKey} onBack={goHome} onOpenExp={(id) => openExp(nav.catKey, id)} />
      </div>
    );
  }

  // Home / portal page
  return (
    <div className="app">
      <div className="app-header">
        <div className="app-title" style={{ cursor: 'pointer' }} onClick={goHome}>
          <div className="app-title-icon">
            <Icons.Atom />
          </div>
          <span>物探 Lab</span>
        </div>
        <div className="nav-links">
          {Object.entries(CATEGORIES).map(([key, cat]) => (
            <span key={key} className="nav-link" onClick={() => goCategory(key)}>
              {cat.name}
            </span>
          ))}
        </div>
        <div className="app-header-actions">
          <button className="btn-cta" onClick={scrollToCategories}>
            <span className="btn-icon"><Icons.Play /></span>
            <span>开始实验</span>
          </button>
        </div>
      </div>
      <Portal onEnterCategory={goCategory} onRandom={goRandom} onBrowse={scrollToCategories} />
    </div>
  );
}

// ========== Home Portal ==========
function Portal({ onEnterCategory, onRandom, onBrowse }) {
  const totalExps = Object.values(CATEGORIES).reduce((s, c) => s + c.experiments.length, 0);
  const totalCats = Object.keys(CATEGORIES).length;

  return (
    <div className="portal portal-home">
      {/* Hero Section */}
      <section className="hero-section">
        <div className="hero-bg-pattern"></div>
        <div className="hero-grid">
          <div className="hero-left">
            <div className="hero-badge">
              <Icons.Atom style={{ width: 14, height: 14 }} />
              <span>初中物理 · 互动仿真实验台</span>
            </div>
            <h1 className="hero-title">
              把课本里的物理实验<br/>
              变成<span className="highlight">可操作</span>的动态仿真
            </h1>
            <p className="hero-desc">
              覆盖声学、光学、热学、力学、电学、电磁学六大门类共 {totalExps} 个经典实验。
              实时公式计算、可调参数、可读仪表，打开浏览器就能用，无需安装。
            </p>
            <div className="hero-buttons">
              <button className="hero-btn-primary" onClick={onBrowse}>
                <Icons.Grid3x3 style={{ width: 16, height: 16 }} />
                <span>浏览六大实验</span>
              </button>
              <button className="hero-btn-secondary" onClick={onRandom}>
                <Icons.Shuffle style={{ width: 15, height: 15 }} />
                <span>随机进入一个</span>
              </button>
            </div>
            <div className="hero-features">
              <div className="hero-feature">
                <Icons.Check />
                <span>{totalCats} 大门类 / {totalExps} 个实验</span>
              </div>
              <div className="hero-feature">
                <Icons.Check />
                <span>公式实时计算</span>
              </div>
              <div className="hero-feature">
                <Icons.Check />
                <span>参数可调</span>
              </div>
              <div className="hero-feature">
                <Icons.Check />
                <span>打开即用，无需登录</span>
              </div>
            </div>
          </div>

          <div className="hero-right">
            <HeroPreviewCard />
          </div>
        </div>
      </section>

      {/* Categories Section */}
      <section id="categories-section" className="categories-section">
        <FormulaBackground />
        <div className="categories-header">
          <div className="section-eyebrow">六大实验门类</div>
          <h2 className="section-title">按你的学习任务，直接进入</h2>
          <p className="section-desc">
            从声学波动到电磁感应，每个实验都有独立的交互界面与原理讲解，
            对应人教版初中物理教材的全部核心实验。
          </p>
        </div>
        <div className="categories-grid">
          {Object.entries(CATEGORIES).map(([key, cat]) => {
            const IconComp = Icons[cat.icon];
            return (
              <div key={key} className="category-card"
                style={{ ['--cat-color']: cat.color }}
                onClick={() => onEnterCategory(key)}>
                <div className="category-icon-wrap">
                  {IconComp && <IconComp />}
                </div>
                <div className="category-name">{cat.name}</div>
                <div className="category-english">{cat.subtitle}</div>
                <div className="category-count">
                  {cat.experiments.length} 个实验
                  <Icons.ArrowRight />
                </div>
              </div>
            );
          })}
        </div>
      </section>
    </div>
  );
}

// ========== Hero Preview Card (browser window with experiment preview) ==========
function HeroPreviewCard() {
  // A stylized preview of a convex lens experiment to showcase the product
  return (
    <div className="hero-preview-stack">
      {/* back card for depth */}
      <div className="hero-preview-card back">
        <div className="preview-header">
          <div className="preview-dots">
            <span className="preview-dot red"></span>
            <span className="preview-dot yellow"></span>
            <span className="preview-dot green"></span>
          </div>
          <span className="preview-title">物探 Lab · 欧姆定律</span>
        </div>
        <div className="preview-body">
          <svg viewBox="0 0 560 340" xmlns="http://www.w3.org/2000/svg">
            <rect width="560" height="340" fill="#fafafa"/>
            {/* Circuit diagram simplified */}
            <rect x="40" y="60" width="480" height="220" rx="8" fill="#fff" stroke="#e3e3e5" strokeWidth="1"/>
            <text x="60" y="90" fill="#111114" fontSize="13" fontWeight="600">电路示意图</text>
            {/* battery */}
            <line x1="80" y1="200" x2="80" y2="240" stroke="#111114" strokeWidth="2"/>
            <line x1="70" y1="200" x2="90" y2="200" stroke="#111114" strokeWidth="2.5"/>
            <line x1="75" y1="240" x2="85" y2="240" stroke="#111114" strokeWidth="1.5"/>
            {/* resistor */}
            <path d="M 200 220 L 210 210 L 220 230 L 230 210 L 240 230 L 250 210 L 260 220"
              fill="none" stroke="#111114" strokeWidth="1.5"/>
            {/* ammeter */}
            <circle cx="330" cy="220" r="14" fill="#fff" stroke="#111114" strokeWidth="1.5"/>
            <text x="330" y="225" textAnchor="middle" fill="#111114" fontSize="11" fontWeight="600">A</text>
            {/* voltmeter */}
            <circle cx="170" cy="150" r="14" fill="#fff" stroke="#52525b" strokeWidth="1.5"/>
            <text x="170" y="155" textAnchor="middle" fill="#52525b" fontSize="11" fontWeight="600">V</text>
            {/* wires */}
            <path d="M 80 200 L 80 120 L 156 120" fill="none" stroke="#111114" strokeWidth="1.5"/>
            <path d="M 184 120 L 330 120 L 330 206" fill="none" stroke="#111114" strokeWidth="1.5"/>
            <path d="M 80 240 L 80 260 L 500 260 L 500 220 L 344 220" fill="none" stroke="#111114" strokeWidth="1.5"/>
            {/* data cards */}
            <rect x="380" y="80" width="120" height="48" rx="6" fill="#f4f4f5" stroke="#d4d4d8"/>
            <text x="392" y="100" fill="#6b6b72" fontSize="10">电压 U</text>
            <text x="392" y="120" fill="#111114" fontSize="16" fontWeight="700">6.0 V</text>
            <rect x="380" y="140" width="120" height="48" rx="6" fill="#f4f4f5" stroke="#d4d4d8"/>
            <text x="392" y="160" fill="#6b6b72" fontSize="10">电流 I</text>
            <text x="392" y="180" fill="#52525b" fontSize="16" fontWeight="700">0.5 A</text>
          </svg>
        </div>
      </div>

      {/* front card */}
      <div className="hero-preview-card">
        <div className="preview-header">
          <div className="preview-dots">
            <span className="preview-dot red"></span>
            <span className="preview-dot yellow"></span>
            <span className="preview-dot green"></span>
          </div>
          <span className="preview-title">物探 Lab · 凸透镜成像</span>
        </div>
        <div className="preview-body">
          <svg viewBox="0 0 560 320" xmlns="http://www.w3.org/2000/svg">
            <rect width="560" height="320" fill="#ffffff"/>
            {/* optical axis */}
            <line x1="20" y1="160" x2="540" y2="160" stroke="#d4d4d8" strokeWidth="1" strokeDasharray="4,4"/>
            {/* lens */}
            <ellipse cx="280" cy="160" rx="8" ry="110" fill="rgba(0,0,0,0.08)" stroke="#111114" strokeWidth="1.5"/>
            <line x1="276" y1="50" x2="280" y2="46" stroke="#111114" strokeWidth="1.5"/>
            <line x1="284" y1="50" x2="280" y2="46" stroke="#111114" strokeWidth="1.5"/>
            <line x1="276" y1="270" x2="280" y2="274" stroke="#111114" strokeWidth="1.5"/>
            <line x1="284" y1="270" x2="280" y2="274" stroke="#111114" strokeWidth="1.5"/>
            {/* focal points */}
            <circle cx="190" cy="160" r="3" fill="#71717a"/>
            <circle cx="370" cy="160" r="3" fill="#71717a"/>
            <text x="190" y="176" textAnchor="middle" fill="#71717a" fontSize="9" fontWeight="600">F</text>
            <text x="370" y="176" textAnchor="middle" fill="#71717a" fontSize="9" fontWeight="600">F'</text>
            {/* object (arrow) */}
            <line x1="100" y1="160" x2="100" y2="105" stroke="#111114" strokeWidth="2.5"/>
            <polygon points="100,95 94,109 106,109" fill="#111114"/>
            <text x="100" y="195" textAnchor="middle" fill="#111114" fontSize="10" fontWeight="600">物</text>
            {/* image (arrow) */}
            <line x1="445" y1="160" x2="445" y2="188" stroke="#52525b" strokeWidth="2.5"/>
            <polygon points="445,198 439,184 451,184" fill="#52525b"/>
            <text x="445" y="218" textAnchor="middle" fill="#52525b" fontSize="10" fontWeight="600">实像</text>
            {/* rays */}
            <line x1="100" y1="105" x2="280" y2="105" stroke="#a1a1aa" strokeWidth="1" opacity="0.8"/>
            <line x1="280" y1="105" x2="445" y2="188" stroke="#a1a1aa" strokeWidth="1" opacity="0.8"/>
            <line x1="100" y1="105" x2="445" y2="188" stroke="#71717a" strokeWidth="1" opacity="0.7"/>
            {/* data label */}
            <rect x="30" y="30" width="140" height="44" rx="6" fill="#f4f4f5" stroke="#d4d4d8"/>
            <text x="42" y="48" fill="#6b6b72" fontSize="9">物距 u = 180 mm</text>
            <text x="42" y="64" fill="#111114" fontSize="11" fontWeight="600">倒立缩小实像</text>
          </svg>
        </div>
      </div>
    </div>
  );
}

// ========== Category Page ==========
function CategoryPage({ catKey, onBack, onOpenExp }) {
  const cat = CATEGORIES[catKey];
  const IconComp = Icons[cat.icon];

  return (
    <div className="portal category-page">
      <FormulaBackground />
      <div className="cat-hero" style={{ ['--cat-color']: cat.color }}>
        <div className="cat-hero-icon">
          {IconComp && <IconComp />}
        </div>
        <div className="cat-hero-text">
          <div className="cat-hero-name">{cat.name}</div>
          <div className="cat-hero-english">{cat.subtitle}</div>
          <div className="cat-hero-desc">共 {cat.experiments.length} 个经典实验 · 点击卡片进入操作界面</div>
        </div>
      </div>

      <div className="exp-cards-grid">
        {cat.experiments.map((exp, i) => (
          <div key={exp.id} className="exp-card"
            onClick={() => onOpenExp(exp.id)}
            style={{ ['--cat-color']: cat.color }}>
            <div className="exp-card-num">{String(i+1).padStart(2, '0')}</div>
            <div className="exp-card-name">{exp.name}</div>
            <div className="exp-card-arrow">
              <Icons.ArrowRight />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ========== Experiment View ==========
function ExperimentView({ catKey, expId }) {
  const cat = CATEGORIES[catKey];
  const exp = cat.experiments.find(e => e.id === expId);
  const Comp = EXPERIMENT_COMPONENTS[`${catKey}:${expId}`];

  if (!Comp) {
    return (
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-tertiary)' }}>
        实验「{exp?.name || expId}」正在开发中…
      </div>
    );
  }

  return <Comp category={cat.name} name={exp.name} catColor={cat.color} />;
}

// Registry of all experiment components (populated by each exp-*.jsx file via window)
const EXPERIMENT_COMPONENTS = {};

function registerExp(catKey, expId, Comp) {
  EXPERIMENT_COMPONENTS[`${catKey}:${expId}`] = Comp;
}

// Acoustics
registerExp('acoustics', 'sound-propagation', SoundPropagationExp);
registerExp('acoustics', 'pitch-frequency', PitchFrequencyExp);
registerExp('acoustics', 'loudness-amplitude', LoudnessAmplitudeExp);

// Optics
registerExp('optics', 'pinhole', PinholeExp);
registerExp('optics', 'reflection', ReflectionExp);
registerExp('optics', 'refraction', RefractionExp);
registerExp('optics', 'convex-lens', ConvexLensExp);
registerExp('optics', 'dispersion', DispersionExp);

// Thermal
registerExp('thermal', 'thermometer', ThermometerExp);
registerExp('thermal', 'melting', MeltingExp);
registerExp('thermal', 'boiling', BoilingExp);
registerExp('thermal', 'specific-heat', SpecificHeatExp);

// Mechanics
registerExp('mechanics', 'measurement', MeasurementExp);
registerExp('mechanics', 'gravity', GravityExp);
registerExp('mechanics', 'friction', FrictionExp);
registerExp('mechanics', 'inertia', InertiaExp);
registerExp('mechanics', 'buoyancy', BuoyancyExp);
registerExp('mechanics', 'liquid-pressure', LiquidPressureExp);
registerExp('mechanics', 'lever', LeverExp);
registerExp('mechanics', 'pulley', PulleyExp);

// Electricity
registerExp('electricity', 'simple-circuit', SimpleCircuitExp);
registerExp('electricity', 'ohms-law', OhmsLawExp);
registerExp('electricity', 'series-parallel', SeriesParallelExp);
registerExp('electricity', 'rheostat', RheostatExp);
registerExp('electricity', 'electric-power', ElectricPowerExp);

// Electromagnetism
registerExp('electromagnetism', 'magnetic-field', MagneticFieldExp);
registerExp('electromagnetism', 'oersted', OerstedExp);
registerExp('electromagnetism', 'electromagnet', ElectromagnetExp);
registerExp('electromagnetism', 'motor', MotorExp);
registerExp('electromagnetism', 'induction', InductionExp);

// Mount app
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
