/* global React, RobotCar, HLIcon */
// All page sections except the form

const { useState, useEffect, useRef, useMemo } = React;

// Tiny robot icons for the field legend — match the field-diagram MiniRobot symbols
function RobotLegend({ type }) {
  return (
    <svg width="20" height="20" viewBox="-14 -14 28 28" style={{ flexShrink: 0 }}>
      <rect x="-14" y="-14" width="28" height="28" fill="#0B0B0E" stroke="#0B0B0E" strokeWidth="1.5" rx="6" />
      {type === 'shooter' ? (
        <g>
          <circle cx="0" cy="0" r="9" fill="none" stroke="#fff" strokeWidth="2" />
          <circle cx="0" cy="0" r="3" fill="#fff" />
        </g>
      ) : (
        <path
          d="M 0 -10 L 2.6 -2.6 L 10 0 L 2.6 2.6 L 0 10 L -2.6 2.6 L -10 0 L -2.6 -2.6 Z"
          fill="#fff"
        />
      )}
    </svg>
  );
}

// ─── Nav ────────────────────────────────────────────────
function Nav({ daysLeft, onJump }) {
  return (
    <nav className="nav">
      <div className="container nav-inner">
        <a href="#top" className="brand" onClick={(e) => {e.preventDefault();onJump('top');}}>
          <div className="brand-mark">N</div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 900, lineHeight: 1.1 }}>STEAM <span style={{ color: 'var(--accent)' }}>'26</span></div>
            <div style={{ fontSize: 10, color: 'var(--muted)', fontFamily: 'var(--font-mono)', letterSpacing: '.05em' }}>NKUST · SUMMER LAB</div>
          </div>
        </a>
        <div className="nav-links">
          <a href="#about" onClick={(e) => {e.preventDefault();onJump('about');}}>關於</a>
          <a href="#schedule" onClick={(e) => {e.preventDefault();onJump('schedule');}}>課程</a>
          <a href="#tournament" onClick={(e) => {e.preventDefault();onJump('tournament');}}>競賽</a>
          <a href="#faq" onClick={(e) => {e.preventDefault();onJump('faq');}}>FAQ</a>
          <span className="countdown-chip">
            <span className="dot"></span>
            T-{daysLeft}d · 7.1 開營
          </span>
          <button className="btn small" onClick={() => onJump('register')}>
            立即報名 →
          </button>
        </div>
      </div>
    </nav>);

}

// ─── Hero ───────────────────────────────────────────────
function Hero({ onRegister }) {
  return (
    <section className="hero" id="top">
      <div className="container">
        <div className="hero-grid">
          <div>
            <span className="eyebrow">2026 高科大夏令營 · 完整營隊辦法</span>
            <h1 style={{ marginTop: 20 }}>
              機器人自走車<br />
              <span className="x">×</span> <span className="underline">AI 科技探索營</span>
            </h1>
            <p className="hero-sub">
              三天動手做、動腦玩。從車體結構、感測器到 Scratch 方塊程式，
              讓國小三至六年級的孩子在任務關卡與團隊競賽中，
              親手讓自己的機器人車跑起來。
            </p>

            <div className="hero-date">
              <div className="big">07.01<br />— 07.03</div>
              <div>
                <div style={{ fontWeight: 800, fontSize: 16 }}>三日營隊</div>
                <div className="small">115年7月1日（三）— 7月3日（五）<br />每日 08:00 – 16:00　|　高雄市彌陀區壽齡國民小學</div>
              </div>
            </div>

            <div className="hero-chips">
              <span className="chip solid"><span style={{ width: 6, height: 6, background: 'var(--primary)', borderRadius: '50%' }}></span> 全程免費</span>
              <span className="chip">招收 30 名</span>
              <span className="chip">國小 3–6 年級</span>
              <span className="chip">提供午餐</span>
              <span className="chip">跨校混編</span>
            </div>

            <div className="hero-cta">
              <button className="btn" onClick={onRegister}>
                立即報名 <span style={{ fontFamily: 'var(--font-display)' }}>→</span>
              </button>
              <a className="btn ghost" href="#schedule" onClick={(e) => {e.preventDefault();document.getElementById('schedule')?.scrollIntoView({ behavior: 'smooth', block: 'start' });}}>
                查看課程
              </a>
            </div>
          </div>

          <div className="robot-stage">
            <div className="stage-corner tl">LAB · ZONE-A</div>
            <div className="stage-corner tr">CAM-01 ● REC</div>
            <div className="stage-corner bl">v1.26.07</div>
            <div className="stage-corner br">TRACK · 1:1</div>
            <div className="stage-grid"></div>
            <div className="stage-track"></div>
            <div className="stage-checker"></div>

            {/* Top-left mini hud */}
            <div style={{
              position: 'absolute', top: 36, left: 36,
              padding: '10px 12px',
              background: 'var(--bg)', border: '2px solid var(--ink)', borderRadius: 10,
              fontFamily: 'var(--font-mono)', fontSize: 11, lineHeight: 1.5
            }}>
              <div>▸ DRIVE  : <b>FWD</b></div>
              <div>▸ SENSOR : 12.4cm</div>
              <div>▸ MISSION: <span style={{ color: 'var(--accent)' }}>RUN</span></div>
            </div>

            {/* Block stack mini hud */}
            <div style={{
              position: 'absolute', top: 36, right: 36,
              display: 'flex', flexDirection: 'column', gap: 0, alignItems: 'flex-end'
            }}>
              <MiniBlock color="var(--primary)">當 ▶ 被點擊</MiniBlock>
              <MiniBlock color="var(--accent)" stack>移動 50 步</MiniBlock>
              <MiniBlock color="var(--blue)" stack>右轉 90 度</MiniBlock>
            </div>

            <RobotCar />
          </div>
        </div>
      </div>
    </section>);

}

function MiniBlock({ color, stack, children }) {
  return (
    <div style={{
      position: 'relative',
      background: color,
      color: 'var(--paper)',
      border: '2px solid var(--ink)',
      borderRadius: 8,
      padding: '7px 12px',
      fontSize: 12,
      fontWeight: 700,
      fontFamily: 'var(--font-cn)',
      marginTop: stack ? -2 : 0,
      boxShadow: '2px 2px 0 var(--ink)',
      zIndex: stack ? 0 : 1
    }}>
      {children}
    </div>);

}

// ─── Highlights ────────────────────────────────────────
function Highlights() {
  const items = [
  { kind: 'tech', num: '01', title: '科技入門', en: 'Tech Intro', desc: '自走車車體、馬達、感測器、控制器的關係，看見科技不再只是黑盒子。', cls: 'b1' },
  { kind: 'code', num: '02', title: '程式設計', en: 'Block Coding', desc: '用 Scratch 方塊程式拖拉組合，不打字也能寫程式，建立邏輯思考。', cls: 'b2' },
  { kind: 'hands', num: '03', title: '動手實作', en: 'Hands-on Lab', desc: '操作、測試、修正、再試一次。把角度、距離、路線變成可以動的指令。', cls: 'b3' },
  { kind: 'team', num: '04', title: '團隊競賽', en: 'Team Showdown', desc: '跨校混編、小組分工、第三天正式競賽，讓每個孩子找到屬於自己的成就。', cls: 'b4' }];

  return (
    <section id="about">
      <div className="container">
        <div className="section-head">
          <div>
            <span className="eyebrow">課程亮點 · Highlights</span>
            <h2 style={{ marginTop: 14 }}>四個關鍵能力，<span className="accent">三天玩透。</span></h2>
          </div>
          <p>不只是體驗。從入門概念、寫程式、動手實作到團隊競賽，每一天都讓孩子帶走一個新的「我會了」。</p>
        </div>
        <div className="highlights">
          {items.map((it) =>
          <div className={`hl ${it.cls}`} key={it.num}>
              <div className="num">{it.num} · {it.en}</div>
              <h3>{it.title}</h3>
              <p>{it.desc}</p>
              <div className="icon"><HLIcon kind={it.kind} /></div>
            </div>
          )}
        </div>

        <div className="stats">
          <div className="stat"><div className="v">3<span style={{ fontSize: 24, marginLeft: 4 }}>天</span></div><div className="l">DURATION · 課程天數</div></div>
          <div className="stat"><div className="v">30</div><div className="l">SEATS · 招生名額</div></div>
          <div className="stat"><div className="v">$0</div><div className="l">FEE · 全程免費 + 午餐</div></div>
          <div className="stat"><div className="v">2<span style={{ fontSize: 24, marginLeft: 4 }}>校</span></div><div className="l">SCHOOLS · 壽齡 × 北嶺</div></div>
        </div>
      </div>
    </section>);

}

// ─── About / 活動宗旨 ──────────────────────────────────
function About() {
  return (
    <section>
      <div className="container">
        <div className="about-grid">
          <div>
            <span className="eyebrow">活動宗旨 · Why STEAM</span>
            <p className="lead" style={{ marginTop: 18 }}>
              不強調死背知識，而是讓學員動手做、親眼看見車子動起來。
            </p>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <p>
              本營隊以 <strong>STEAM 科技教育</strong>為核心，透過機器人自走車、機械手臂車、
              超音波感測器、水平雲台與 <strong>Scratch 方塊程式設計</strong>，
              引導國小學生在實作中理解科技原理。
            </p>
            <p>
              課程設計讓孩子在操作、觀察、試錯與合作中，
              自然而然建立 <strong>邏輯思考、工程思維、問題解決能力</strong>與團隊精神——
              不需要任何先備程式經驗。
            </p>
          </div>
        </div>
      </div>
    </section>);

}

// ─── Schedule ──────────────────────────────────────────
const SCHEDULE = {
  d1: {
    date: '7月 1 日 · 週三',
    sub: '基礎科技課程 × Scratch 入門',
    rows: [
    ['08:00 – 08:30', '報到與集合', '工作人員協助點名、名牌發放與座位安排', 'check'],
    ['08:30 – 10:00', '開幕、師資介紹與營隊安全說明', '介紹活動目標、場地規範與分組方式', 'highlight'],
    ['10:00 – 10:15', '休息', '', 'break'],
    ['10:15 – 12:00', '認識機器人自走車與感測器', '車體結構、馬達、控制器、超音波感測器、水平雲台', null],
    ['12:00 – 13:30', '午休 / 用餐', '主辦單位提供午餐', 'lunch'],
    ['13:30 – 15:00', 'Scratch 方塊程式設計入門', '認識事件、動作、控制、條件判斷與基本邏輯', null],
    ['15:00 – 15:15', '休息', '', 'break'],
    ['15:15 – 15:50', '基礎控制練習', '完成前進、後退、轉向與簡易任務', null],
    ['15:50 – 16:00', '今日總結與第二天預告', '回收設備、提醒攜帶水壺與準時報到', null]]

  },
  d2: {
    date: '7月 2 日 · 週四',
    sub: '破冰交流 × 遙控操作練習 × 小小駕駛員任務挑戰賽',
    rows: [
    ['08:00 – 08:30', '報到與設備檢查', '確認學生到場、控制器與車輛狀態', 'check'],
    ['08:30 – 10:00', '破冰活動與跨校混編分組', '促進壽齡與北嶺學生交流，建立團隊默契', 'highlight'],
    ['10:00 – 10:15', '休息', '', 'break'],
    ['10:15 – 12:00', '遙控器操作教學與基礎駕駛練習', '前進、後退、轉向、停止、夾取與避障操作', null],
    ['12:00 – 13:30', '午休 / 用餐', '主辦單位提供午餐', 'lunch'],
    ['13:30 – 14:10', '趣味競賽規則說明與正式試跑', '說明簡化版 7 關卡與安全規則', null],
    ['14:10 – 15:00', '小小駕駛員任務挑戰賽', '每組 5 分鐘，依序上場挑戰 — 點此查看 7 個任務站與評分', 'practice'],
    ['15:00 – 15:15', '休息', '', 'break'],
    ['15:15 – 15:50', '分享與小獎勵', '頒發最佳駕駛、最佳合作、最佳創意等趣味獎', 'highlight'],
    ['15:50 – 16:00', '第三天正式比賽提醒', '提醒車輛檢錄、試跑與正式比賽流程', null]]

  },
  d3: {
    date: '7月 3 日 · 週五',
    sub: '車輛檢錄 × 嘉賓開場 × 正式比賽 × 頒獎',
    rows: [
    ['08:00 – 08:30', '報到與分組集合', '工作人員協助點名與車輛分配', 'check'],
    ['08:30 – 10:00', '車輛檢錄與操作複習', '檢查車體、電池、控制器、感測器與安全狀態', null],
    ['10:00 – 10:15', '休息', '', 'break'],
    ['10:15 – 12:00', '賽道試跑與最後調整', '開放各組練習，教師協助排除問題', null],
    ['12:00 – 13:30', '午休 / 用餐', '主辦單位提供午餐', 'lunch'],
    ['13:30 – 14:00', '嘉賓開場 · 致詞', '貴賓與指導單位致詞、選手代表宣誓、賽前說明', 'opening'],
    ['14:00 – 15:00', '正式比賽 · 智創機器人奪標攻防賽', '單循環賽制，每回合 3 分鐘 — 點此查看完整規則與場地配置', 'competition'],
    ['15:00 – 15:15', '休息', '工作人員統計成績與準備頒獎', 'break'],
    ['15:15 – 15:50', '頒獎、活動紀錄短片播放與成果分享', '表揚各組表現，播放活動紀錄影片', 'highlight'],
    ['15:50 – 16:00', '大合照、結業與賦歸', '確認學生接送與場地復原', null]]

  }
};

function Schedule() {
  const [day, setDay] = useState('d1');
  const data = SCHEDULE[day];
  const days = [
  { id: 'd1', n: 'DAY 01', t: '科技入門', d: '7.1 週三' },
  { id: 'd2', n: 'DAY 02', t: '操作練習', d: '7.2 週四' },
  { id: 'd3', n: 'DAY 03', t: '正式比賽', d: '7.3 週五' }];

  return (
    <section id="schedule" style={{ background: 'var(--soft-1)', paddingTop: 'var(--pad-section)', paddingBottom: 'var(--pad-section)' }}>
      <div className="container">
        <div className="section-head">
          <div>
            <span className="eyebrow">三日課程 · Schedule</span>
            <h2 style={{ marginTop: 14 }}>每天 08:00 – 16:00<br /><span className="accent">三天一條完整的學習軌跡。</span></h2>
          </div>
          <p>從第一天認識車體、第二天破冰練習，到第三天正式競賽——點選下方分頁切換每日詳細流程。</p>
        </div>

        <div className="schedule-tabs" role="tablist">
          {days.map((d) =>
          <button
            key={d.id}
            role="tab"
            className="tab"
            aria-selected={day === d.id}
            onClick={() => setDay(d.id)}>
            
              <span className="day-num">{d.n}</span>
              <span className="day-title">{d.t}</span>
              <span className="day-date">{d.d}</span>
            </button>
          )}
        </div>

        <div className="card" style={{ padding: '32px 32px 28px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
            <div>
              <div className="mono" style={{ fontSize: 12, color: 'var(--muted)', letterSpacing: '.1em' }}>第 {day.slice(1)} 天 · {data.date}</div>
              <h3 style={{ marginTop: 6 }}>{data.sub}</h3>
            </div>
            <span className="chip"><span className="chip-dot"></span> 共 9 個時段</span>
          </div>

          <div className="timeline">
            {data.rows.map((r, i) => {
              const [time, act, note, type] = r;
              let cls = '';
              if (type === 'lunch') cls = 'lunch';else
              if (type === 'break') cls = 'break';else
              if (type === 'highlight') cls = 'highlight';else
              if (type === 'competition') cls = 'competition';else
              if (type === 'practice') cls = 'practice';else
              if (type === 'opening') cls = 'opening';
              const jumpTarget = type === 'competition' ? 'tournament' : type === 'practice' ? 'practice' : null;
              const clickable = !!jumpTarget;
              const onClick = clickable ? () => document.getElementById(jumpTarget)?.scrollIntoView({ behavior: 'smooth', block: 'start' }) : undefined;
              return (
                <div className="tl-row" key={i}>
                  <div className="tl-time">{time}</div>
                  <div className={`tl-dot ${cls} ${clickable ? 'jump' : ''}`} onClick={onClick} role={clickable ? 'button' : undefined}>
                    <div className="card-row">
                      <div>
                        <div className="activity">{act}{clickable && <span className="jump-arrow"> ↓</span>}</div>
                        {note && <div className="note">{note}</div>}
                      </div>
                      {type === 'check' && <span className="badge">報到</span>}
                      {type === 'lunch' && <span className="badge" style={{ background: 'var(--paper)' }}>用餐</span>}
                      {type === 'break' && <span className="badge" style={{ background: 'transparent', border: 'none', color: 'var(--muted)' }}>休息</span>}
                      {type === 'highlight' && <span className="badge" style={{ background: 'var(--ink)', color: 'var(--bg)', borderColor: 'var(--ink)' }}>主場活動</span>}
                      {type === 'opening' && <span className="badge" style={{ background: 'var(--blue)', color: '#fff', borderColor: 'var(--blue)' }}>嘉賓開場</span>}
                      {type === 'practice' && <span className="badge" style={{ background: 'var(--mint)', color: '#fff', borderColor: 'var(--mint)' }}>練習賽 →</span>}
                      {type === 'competition' && <span className="badge" style={{ background: '#fff', color: 'var(--accent)', borderColor: '#fff' }}>正式比賽 →</span>}
                    </div>
                  </div>
                </div>);

            })}
          </div>
        </div>
      </div>
    </section>);

}

// ─── Tournament: 智創機器人奪標攻防賽 ──────────────────
function FieldDiagram() {
  // 360 × 360 cm field, top-down view
  // Blue team top, red team bottom, green neutral middle
  const W = 540,H = 460;
  const pad = 24;
  const fw = W - pad * 2,fh = H - pad * 2;
  const cx = W / 2;

  // helper for target shapes
  const Target = ({ x, y, shape, color, rotation = 0 }) => {
    if (shape === 'square') return (
      <g transform={`translate(${x},${y}) rotate(${rotation})`}>
        <rect x="-10" y="-3" width="20" height="6" fill={color} stroke="var(--ink)" strokeWidth="1.2" />
        <rect x="-3" y="3" width="6" height="10" fill="var(--ink)" />
      </g>);

    if (shape === 'round') return (
      <g transform={`translate(${x},${y}) rotate(${rotation})`}>
        <ellipse cx="0" cy="0" rx="10" ry="5" fill={color} stroke="var(--ink)" strokeWidth="1.2" />
        <rect x="-2" y="4" width="4" height="9" fill="var(--ink)" />
      </g>);

    // triangle (arrow shape)
    return (
      <g transform={`translate(${x},${y}) rotate(${rotation})`}>
        <path d="M -10 4 L 0 -10 L 10 4 Z" fill={color} stroke="var(--ink)" strokeWidth="1.2" strokeLinejoin="round" />
        <rect x="-2.5" y="3" width="5" height="10" fill="var(--ink)" />
      </g>);

  };

  // occupation pad (round disc on field)
  const Pad = ({ x, y }) =>
  <g transform={`translate(${x},${y})`}>
      <rect x="-14" y="-10" width="28" height="20" fill="#F1E7C9" stroke="var(--ink)" strokeWidth="1.2" rx="2" />
      <circle cx="0" cy="0" r="5" fill="none" stroke="#8a7a4e" strokeWidth="2" />
      <circle cx="0" cy="0" r="2" fill="#8a7a4e" />
    </g>;


  // resource (small dark diamond)
  const Resource = ({ x, y }) =>
  <rect x={x - 3} y={y - 3} width="6" height="6" fill="#2A2A33" transform={`rotate(45 ${x} ${y})`} />;


  // Mini robot symbols used inside the starting boxes
  // Match the spec-tab icons: ◎ circle target = shooter, ✦ star = arm
  const MiniRobot = ({ x, y, color, type }) => {
    return (
      <g transform={`translate(${x},${y})`}>
        {/* rounded coloured tile background */}
        <rect x="-14" y="-14" width="28" height="28" fill={color} stroke="var(--ink)" strokeWidth="1.5" rx="6" />
        {type === 'shooter' ? (
          // ◎ target circle
          <g>
            <circle cx="0" cy="0" r="9" fill="none" stroke="#fff" strokeWidth="2" />
            <circle cx="0" cy="0" r="3" fill="#fff" />
          </g>
        ) : (
          // ✦ 4-point star
          <path
            d="M 0 -10 L 2.6 -2.6 L 10 0 L 2.6 2.6 L 0 10 L -2.6 2.6 L -10 0 L -2.6 -2.6 Z"
            fill="#fff"
            stroke="#fff"
            strokeWidth="0.8"
            strokeLinejoin="round"
          />
        )}
      </g>
    );
  };


  return (
    <svg viewBox={`0 0 ${W} ${H}`} xmlns="http://www.w3.org/2000/svg" style={{ width: '100%', height: 'auto', display: 'block' }}>
      {/* outer border */}
      <rect x={pad} y={pad} width={fw} height={fh} fill="#FFFDF6" stroke="var(--ink)" strokeWidth="2" />

      {/* blue team zone */}
      <line x1={pad} y1={pad + fh * 0.28} x2={pad + fw} y2={pad + fh * 0.28} stroke="#1F6FE0" strokeWidth="3" />
      {/* red team zone */}
      <line x1={pad} y1={pad + fh * 0.72} x2={pad + fw} y2={pad + fh * 0.72} stroke="#C8323E" strokeWidth="3" />
      {/* green neutral zone */}
      <line x1={pad} y1={pad + fh * 0.46} x2={pad + fw} y2={pad + fh * 0.46} stroke="#2E9B5E" strokeWidth="2.5" />
      <line x1={pad} y1={pad + fh * 0.54} x2={pad + fw} y2={pad + fh * 0.54} stroke="#2E9B5E" strokeWidth="2.5" />

      {/* Blue starting box */}
      <rect x={cx - 56} y={pad + 8} width="112" height="58" fill="none" stroke="#1F6FE0" strokeWidth="2.5" />
      <text x={cx} y={pad + 22} textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" fill="#1F6FE0" fontWeight="700">BLUE START</text>
      {/* Blue team: shooter (◎) + arm (✦) */}
      <MiniRobot x={cx - 18} y={pad + 44} color="#1F6FE0" type="shooter" />
      <MiniRobot x={cx + 18} y={pad + 44} color="#1F6FE0" type="arm" />

      {/* Blue targets surrounding starting box */}
      <Target x={pad + 60} y={pad + 30} shape="triangle" color="#1F6FE0" rotation={180} />
      <Target x={pad + 130} y={pad + 30} shape="round" color="#1F6FE0" rotation={180} />
      <Target x={pad + fw - 60} y={pad + 30} shape="triangle" color="#1F6FE0" rotation={180} />
      <Target x={pad + fw - 130} y={pad + 30} shape="round" color="#1F6FE0" rotation={180} />
      <Target x={pad + 60} y={pad + 70} shape="square" color="#1F6FE0" />
      <Target x={pad + fw - 60} y={pad + 70} shape="square" color="#1F6FE0" />

      {/* Blue occupation pads (5 pads on blue side) */}
      <Pad x={pad + 80} y={pad + fh * 0.16} />
      <Pad x={cx - 80} y={pad + fh * 0.16} />
      <Pad x={cx + 80} y={pad + fh * 0.16} />
      <Pad x={pad + fw - 80} y={pad + fh * 0.16} />
      <Pad x={pad + 90} y={pad + fh * 0.34} />
      <Pad x={pad + fw - 90} y={pad + fh * 0.34} />
      <Pad x={cx} y={pad + fh * 0.4} />

      {/* Neutral resources in green zone */}
      {[0.12, 0.25, 0.38, 0.5, 0.62, 0.75, 0.88].map((p, i) =>
      <Resource key={i} x={pad + fw * p} y={pad + fh * 0.5} />
      )}

      {/* Red occupation pads (mirrored) */}
      <Pad x={pad + 80} y={pad + fh * 0.84} />
      <Pad x={cx - 80} y={pad + fh * 0.84} />
      <Pad x={cx + 80} y={pad + fh * 0.84} />
      <Pad x={pad + fw - 80} y={pad + fh * 0.84} />
      <Pad x={pad + 90} y={pad + fh * 0.66} />
      <Pad x={pad + fw - 90} y={pad + fh * 0.66} />
      <Pad x={cx} y={pad + fh * 0.6} />

      {/* Red starting box */}
      <rect x={cx - 56} y={pad + fh - 66} width="112" height="58" fill="none" stroke="#C8323E" strokeWidth="2.5" />
      <text x={cx} y={pad + fh - 12} textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" fill="#C8323E" fontWeight="700">RED START</text>
      {/* Red team: shooter (◎) + arm (✦) */}
      <MiniRobot x={cx - 18} y={pad + fh - 34} color="#C8323E" type="shooter" />
      <MiniRobot x={cx + 18} y={pad + fh - 34} color="#C8323E" type="arm" />

      {/* Red targets */}
      <Target x={pad + 60} y={pad + fh - 30} shape="triangle" color="#C8323E" />
      <Target x={pad + 130} y={pad + fh - 30} shape="round" color="#C8323E" />
      <Target x={pad + fw - 60} y={pad + fh - 30} shape="triangle" color="#C8323E" />
      <Target x={pad + fw - 130} y={pad + fh - 30} shape="round" color="#C8323E" />
      <Target x={pad + 60} y={pad + fh - 70} shape="square" color="#C8323E" rotation={180} />
      <Target x={pad + fw - 60} y={pad + fh - 70} shape="square" color="#C8323E" rotation={180} />

      {/* Dimension labels */}
      <g fontFamily="JetBrains Mono" fontSize="10" fill="var(--ink)">
        <text x={cx} y={pad - 8} textAnchor="middle">360 cm</text>
        <text x={pad - 6} y={pad + fh / 2} textAnchor="end" transform={`rotate(-90 ${pad - 6} ${pad + fh / 2})`}>360 cm</text>
      </g>
      {/* Zone labels */}
      <text x={pad + 8} y={pad + fh * 0.5 - 8} fontFamily="JetBrains Mono" fontSize="9" fill="#2E9B5E" fontWeight="700">NEUTRAL · 中立物資區</text>
    </svg>);

}

const ROBOT_SPECS = {
  shooter: {
    name: '射擊機器人',
    en: 'SHOOTING ROBOT',
    color: 'var(--blue)',
    icon: '◎',
    summary: '裝填乒乓球射擊對方標靶，僅能在己方陣地移動。',
    intro: '射擊機器人由主辦單位統一提供，配備乒乓球發射機構、無線接收模組與遙控介面。學員操作標準規格車輛上場，不可自行改裝或增加額外零件，比賽公平性由主辦單位統一維護。',
    specs: [
    ['重量', '不限制'],
    ['車體', '25 × 25 cm（檢錄符合，高度不限）'],
    ['馬達', '直流馬達 × 最多 6 顆，≤ 6V （TT / N20）'],
    ['伺服馬達', '最多 5 顆，扭力 ≤ 20 kg'],
    ['輪子', '直徑 ≤ 75 mm（履帶亦可）'],
    ['電力', '供給電壓 ≤ 7.4 V'],
    ['彈藥', '40 mm 橘色乒乓球 × 最多 5 顆（場地提供）'],
    ['遙控', 'PS2 / PS3 手把或手機遙控介面']]

  },
  arm: {
    name: '手臂機器人',
    en: 'ARM ROBOT',
    color: 'var(--accent)',
    icon: '✦',
    summary: '抓取物資放置佔領台，可進入中立區但不可越線。',
    intro: '手臂機器人由主辦單位統一提供，配備夾爪機構、水平雲台與遙控介面。學員操作標準規格車輛上場，不可自行改裝或增加額外零件，所有隊伍使用相同硬體，公平競賽。',
    specs: [
    ['重量', '不限制'],
    ['車體', '25 × 25 cm（檢錄符合，高度不限）'],
    ['馬達', '直流馬達 × 最多 4 顆，≤ 6V （TT / N20）'],
    ['伺服馬達', '最多 5 顆，扭力 ≤ 20 kg'],
    ['輪子', '直徑 ≤ 75 mm（履帶亦可）'],
    ['電力', '供給電壓 ≤ 7.4 V'],
    ['抓取', '一次最多抓取 1 顆物資'],
    ['遙控', 'PS2 / PS3 手把或手機遙控介面']]

  }
};

const RULE_GROUPS = [
{
  title: '比賽流程',
  icon: '01',
  items: [
  '手臂機器人優先抓取己方物資，放置於佔領台上',
  '佔領台改變燈號後，裁判依設定球數給予乒乓球',
  '射擊機器人領球後即可向對方標靶射擊',
  '己方物資全數放置後，手臂機器人方可至中立區抓取共同物資',
  '若場上無物資，手臂機器人需回到出發區']

},
{
  title: '移動規則',
  icon: '02',
  items: [
  '手臂機器人可進入中立物資區（綠線），但不可跨越至對方陣線',
  '射擊機器人移動過程不可越過中立物資區，僅能在己方陣地移動',
  '裝填彈藥需將機器人移動回出發區（正投影範圍）後方可裝填',
  '車身上最多攜帶 5 顆乒乓球']

},
{
  title: '物資與佔領台',
  icon: '03',
  items: [
  '手臂機器人一次最多只可夾取 1 顆物資，禁止搜刮',
  '每搜刮 1 個物資累計扣 1 分',
  '抓取物資必須放置在佔領台上後，才可夾取下一個',
  '每個佔領台僅能放置 1 個物資',
  '佔領台上的物資不可再次夾取或被觸發']

},
{
  title: '計分方式',
  icon: '04',
  items: [
  '佔領 1 個佔領台 = 2 分',
  '方形標靶 = 1 分　|　圓形標靶 = 2 分　|　三角形標靶 = 3 分',
  '撞倒己方標靶 → 對方獲得該標靶分數',
  '回合分 = 佔領台得分 + 標靶得分 − 扣分',
  '優先擊倒對方所有標靶者，該回合提前結束']

},
{
  title: '違規與裁定',
  icon: '05',
  items: [
  '射擊機器人若卡球，需回到出發區後選手方可用手觸碰處理',
  '不得故意翻倒或破壞對方機器人，違者取消競賽資格',
  '允許奪取物資過程中之輕微碰撞或推擠',
  '累計警告 3 次即取消競賽資格',
  '選手可向裁判提出暫停 1 分鐘，但競賽時間仍持續計算']

},
{
  title: '賽後與調整',
  icon: '06',
  items: [
  '回合結束後需現場確認分數並簽名',
  '賽後提出異議以簽名確認之分數為準',
  '主辦單位保留依現場狀況微調配置（≤ 30%）之權利',
  '修正事項將於領隊會議或賽前統一說明']

}];


function Tournament() {
  const [tab, setTab] = useState('shooter');
  const ref = useRef(null);
  const robot = ROBOT_SPECS[tab];

  return (
    <section id="tournament" ref={ref}>
      <div className="container">
        <div className="section-head">
          <div>
            <span className="eyebrow">DAY 3 正式比賽 · Formal Tournament</span>
            <h2 style={{ marginTop: 14 }}>智創機器人<br /><span className="accent">奪標攻防賽。</span></h2>
          </div>
          <p>
            場地 <strong>360 × 360 cm</strong>，每隊 2 名選手（1 台射擊機器人 + 1 台手臂機器人）。
            每回合 3 分鐘，依任務、標靶與佔領台分數合計，單循環賽制。
          </p>
        </div>

        {/* Quick facts strip */}
        <div className="tour-facts">
          <div className="fact"><div className="k">FIELD</div><div className="v lg">360×360<span className="u">cm</span></div></div>
          <div className="fact"><div className="k">ROUND</div><div className="v lg">3<span className="u">min</span></div></div>
          <div className="fact"><div className="k">TEAM</div><div className="v lg">2<span className="u">人 / 隊</span></div></div>
          <div className="fact"><div className="k">ROBOTS</div><div className="v lg">1<span className="u">+ 1 台</span></div></div>
          <div className="fact"><div className="k">FORMAT</div><div className="v">單循環賽</div></div>
          <div className="fact"><div className="k">LEVEL</div><div className="v">國小 3–6</div></div>
        </div>

        {/* Field diagram + scoring */}
        <div className="tour-grid">
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ padding: '20px 24px', borderBottom: '2px solid var(--ink)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
              <div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '.1em' }}>FIELD LAYOUT · 場地配置</div>
                <div style={{ fontWeight: 800, fontSize: 18, marginTop: 4 }}>360 × 360 cm 競賽場地（俯視）</div>
              </div>
              <div style={{ display: 'flex', gap: 10, fontSize: 11, fontFamily: 'var(--font-mono)' }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, background: '#1F6FE0', borderRadius: 2 }}></span>BLUE</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, background: '#2E9B5E', borderRadius: 2 }}></span>NEUTRAL</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, background: '#C8323E', borderRadius: 2 }}></span>RED</span>
              </div>
            </div>
            <div style={{ padding: 24, background: 'var(--soft-1)' }}>
              <FieldDiagram />
            </div>
            <div className="legend">
              <span><RobotLegend type="shooter" />射擊機器人</span>
              <span><RobotLegend type="arm" />手臂機器人</span>
              <span><span className="lg-dot" style={{ background: '#F1E7C9', border: '1.5px solid #8a7a4e' }}></span>佔領台</span>
              <span><span className="lg-dot" style={{ background: '#2A2A33', transform: 'rotate(45deg)' }}></span>物資（中立）</span>
              <span><span className="lg-dot" style={{ clipPath: 'polygon(50% 0, 100% 100%, 0 100%)', background: '#1F6FE0' }}></span>三角標靶</span>
              <span><span className="lg-dot" style={{ borderRadius: '50%', background: '#1F6FE0' }}></span>圓形標靶</span>
              <span><span className="lg-dot" style={{ background: '#1F6FE0' }}></span>方形標靶</span>
            </div>
          </div>

          {/* Scoring panel */}
          <div className="card" style={{ background: 'var(--ink)', color: 'var(--bg)', padding: 28 }}>
            <div className="mono" style={{ fontSize: 11, color: 'rgba(255,255,255,.55)', letterSpacing: '.1em' }}>SCORING · 計分方式</div>
            <h3 style={{ color: 'var(--primary)', marginTop: 6, fontSize: 24 }}>每回合分數計算</h3>

            <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <ScoreRow color="var(--mint)" label="佔領一個佔領台" pts="+2" sub="POSITION" shape="pad" />
              <ScoreRow color="#8AB4FF" label="方形標靶（擊中倒下）" pts="+1" sub="SQUARE" shape="square" />
              <ScoreRow color="#FFB347" label="圓形標靶（擊中倒下）" pts="+2" sub="ROUND" shape="round" />
              <ScoreRow color="var(--accent)" label="三角標靶（擊中倒下）" pts="+3" sub="TRIANGLE" shape="triangle" />
              <ScoreRow color="#FF8080" label="搜刮 / 違規物資" pts="−1" sub="PENALTY" shape="x" />
            </div>

            <div style={{ marginTop: 22, padding: 14, background: 'rgba(255,255,255,.06)', borderRadius: 10, fontSize: 13.5, lineHeight: 1.65 }}>
              <strong style={{ color: 'var(--primary)' }}>回合分</strong> = 佔領台得分 + 標靶得分 − 扣分。
              優先擊倒對方所有標靶者該回合提前結束，分數以現場總分計算。
            </div>
          </div>
        </div>

        {/* Robot specs */}
        <div style={{ marginTop: 48 }}>
          <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
            <div>
              <span className="eyebrow">機器人規格 · Robot Specs</span>
              <h3 style={{ marginTop: 8, fontSize: 28 }}>兩台機器人，<span style={{ color: 'var(--accent)' }}>各司其職。</span></h3>
            </div>
            <div className="robot-tabs">
              {Object.entries(ROBOT_SPECS).map(([k, r]) =>
              <button key={k} className={`robot-tab ${tab === k ? 'active' : ''}`} onClick={() => setTab(k)}>
                  <span className="ico" style={{ background: r.color }}>{r.icon}</span>
                  <span>{r.name}</span>
                </button>
              )}
            </div>
          </div>

          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ padding: '24px 28px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28, alignItems: 'stretch' }}>
              <div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '.1em' }}>{robot.en}</div>
                <h3 style={{ marginTop: 6, fontSize: 28, color: robot.color }}>{robot.name}</h3>
                <p style={{ marginTop: 10, color: 'var(--ink-2)', fontSize: 15, lineHeight: 1.6 }}>{robot.summary}</p>
                <div style={{ marginTop: 16, padding: 14, background: 'var(--soft-1)', borderRadius: 10, border: '1.5px dashed var(--ink)', fontSize: 13, lineHeight: 1.65 }}>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--muted)', letterSpacing: '.12em' }}>ABOUT</span>
                  <div style={{ marginTop: 4 }}>{robot.intro}</div>
                </div>
              </div>
              <div>
                <table className="spec-table">
                  <tbody>
                    {robot.specs.map(([k, v]) =>
                    <tr key={k}>
                        <td className="k">{k}</td>
                        <td className="v">{v}</td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

        {/* Rules accordion */}
        <div style={{ marginTop: 48 }}>
          <div style={{ marginBottom: 18 }}>
            <span className="eyebrow">完整規則 · Full Rulebook</span>
            <h3 style={{ marginTop: 8, fontSize: 28 }}>21 條規則，<span style={{ color: 'var(--accent)' }}>分 6 大類。</span></h3>
          </div>
          <div className="rule-grid">
            {RULE_GROUPS.map((g) =>
            <div className="rule-group" key={g.title}>
                <div className="rule-head">
                  <span className="rule-icon">{g.icon}</span>
                  <h4>{g.title}</h4>
                </div>
                <ul>
                  {g.items.map((it, i) => <li key={i}>{it}</li>)}
                </ul>
              </div>
            )}
          </div>
        </div>

        {/* Team registration note */}
        <div className="card" style={{ marginTop: 36, padding: 24, display: 'flex', gap: 20, alignItems: 'center', flexWrap: 'wrap', background: 'var(--primary)', borderColor: 'var(--ink)' }}>
          <div style={{
            width: 56, height: 56, background: 'var(--ink)', color: 'var(--primary)',
            display: 'grid', placeItems: 'center', borderRadius: 14,
            fontFamily: 'var(--font-display)', fontSize: 20
          }}>2v2</div>
          <div style={{ flex: '1 1 320px' }}>
            <div style={{ fontWeight: 800, fontSize: 17 }}>競賽報名 · 不限隊數</div>
            <div style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 4, lineHeight: 1.6 }}>
              每隊 2 名選手（1 台射擊機器人 + 1 台手臂機器人），開放國小 3–6 年級報名。
              參賽選手得與其他競賽選手名單重複。賽制採單循環制，若有變更將提前說明。
            </div>
          </div>
          <button className="btn small" onClick={() => document.getElementById('register')?.scrollIntoView({ behavior: 'smooth', block: 'start' })}>報名營隊 →</button>
        </div>
      </div>
    </section>);

}

function ScoreRow({ color, label, pts, sub, shape }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '40px 1fr auto',
      gap: 14, alignItems: 'center',
      padding: '12px 14px',
      background: 'rgba(255,255,255,.04)', borderRadius: 10
    }}>
      <div style={{ width: 32, height: 32, display: 'grid', placeItems: 'center', background: color, borderRadius: 8 }}>
        <ScoreShape shape={shape} />
      </div>
      <div>
        <div style={{ fontWeight: 700, fontSize: 14 }}>{label}</div>
        <div className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,.5)', letterSpacing: '.12em' }}>{sub}</div>
      </div>
      <div style={{
        fontFamily: 'var(--font-display)', fontSize: 24,
        color: pts.startsWith('−') ? '#FF8080' : 'var(--primary)'
      }}>{pts}</div>
    </div>);

}

function ScoreShape({ shape }) {
  if (shape === 'pad') return <div style={{ width: 16, height: 10, background: '#15131F', borderRadius: 2 }}></div>;
  if (shape === 'square') return <div style={{ width: 12, height: 12, background: '#15131F' }}></div>;
  if (shape === 'round') return <div style={{ width: 14, height: 12, background: '#15131F', borderRadius: '50%' }}></div>;
  if (shape === 'triangle') return <div style={{ width: 0, height: 0, borderLeft: '7px solid transparent', borderRight: '7px solid transparent', borderBottom: '12px solid #15131F' }}></div>;
  if (shape === 'x') return <div style={{ fontFamily: 'var(--font-display)', color: '#15131F', fontSize: 16 }}>×</div>;
  return null;
}

// ─── Notes / 注意事項 ─────────────────────────────────
function Notes() {
  const items = [
  '每日 08:00–08:30 由家長或監護人陪同完成報到',
  '自備個人水壺（500ml 以上），請勿攜帶含糖飲料',
  '主辦單位每日提供午餐；有飲食過敏請於報名時告知',
  '氣喘、癲癇、過敏、心臟病等特殊狀況請填寫健康聲明',
  '活動全程拍照錄影作為紀錄、宣傳與報告使用',
  '請妥善保管個人物品，貴重物品請勿攜帶入場',
  '遵守場地規範、聽從工作人員與助教指引',
  '天災、疫情等不可抗力因素將另行通知調整或取消'];

  return (
    <section style={{ background: 'var(--paper)', borderTop: '2px solid var(--ink)', borderBottom: '2px solid var(--ink)' }}>
      <div className="container">
        <div className="section-head">
          <div>
            <span className="eyebrow">學員注意事項 · Before You Come</span>
            <h2 style={{ marginTop: 14 }}>三件事，<span className="accent">準備好就出發。</span></h2>
          </div>
          <p>下面這些事項請家長與學員一起閱讀，到場時會更順利。報名時也會再次提醒。</p>
        </div>
        <div className="notes">
          {items.map((t) => <div className="note-item" key={t}>{t}</div>)}
        </div>
      </div>
    </section>);

}

// ─── FAQ ──────────────────────────────────────────────
const FAQS = [
{ q: '需要先會寫程式嗎？', a: '完全不用！課程從零開始教 Scratch 方塊程式，孩子用拖拉的方式組合指令，第一天就能讓車子動起來。' },
{ q: '報名費用真的全程免費嗎？', a: '是的，本營隊全程免費，主辦單位每日另提供午餐一份。設備、教材皆由主辦單位準備。' },
{ q: '中午吃什麼？可以告知飲食限制嗎？', a: '主辦單位每日提供午餐。若孩子有飲食過敏、素食或宗教飲食需求，請在報名表的「健康聲明」欄位告知。' },
{ q: '兩所學校的學生會混在一起嗎？', a: '第二天破冰時段會進行跨校混編分組，讓壽齡與北嶺的孩子互相認識，第三天以混編團隊參加正式競賽。' },
{ q: '比賽會很難嗎？我家小孩會不會跟不上？', a: '競賽以遙控操作為主，重點在穩定完成任務與團隊合作。賽道依國小程度設計，避免過度複雜的 S 型路段。' },
{ q: '活動會拍照錄影嗎？我們可以選擇不公開嗎？', a: '活動會全程紀錄。報名時的「肖像權同意」欄位可以選擇「不同意公開使用」，我們會妥善處理該名學員的影像。' },
{ q: '名額滿了怎麼辦？有候補嗎？', a: '依報名順序錄取 30 名，額滿後保留候補名單。若有名額釋出，主辦單位會以報名留存的聯絡方式通知。' }];


function FAQ() {
  const [open, setOpen] = useState(0);
  return (
    <section id="faq">
      <div className="container">
        <div className="section-head">
          <div>
            <span className="eyebrow">常見問題 · FAQ</span>
            <h2 style={{ marginTop: 14 }}>家長最常問的<br /><span className="accent">七個問題。</span></h2>
          </div>
          <p>還有其他疑問？歡迎透過下方聯絡資訊與我們聯繫。</p>
        </div>
        <div className="faq">
          {FAQS.map((f, i) =>
          <div className={`faq-item ${open === i ? 'open' : ''}`} key={f.q}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span><span className="mono" style={{ color: 'var(--muted)', marginRight: 12, fontSize: 13 }}>Q.0{i + 1}</span>{f.q}</span>
                <span className="toggle">+</span>
              </button>
              <div className="faq-a">{f.a}</div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ─── Orgs ──────────────────────────────────────────────
function Orgs() {
  return (
    <section>
      <div className="container">
        <div className="section-head">
          <div>
            <span className="eyebrow">辦理單位 · Organisers</span>
            <h2 style={{ marginTop: 14 }}>由教育部與高科大團隊聯合策劃，<br />兩所合辦小學提供場地與在地支援。</h2>
          </div>
        </div>
        <div className="orgs">
          <div className="orgs-row">
            <div className="role">指導單位</div>
            <span className="org-badge solid">教育部</span>
          </div>
          <div className="orgs-row">
            <div className="role">主辦單位</div>
            <span className="org-badge">國立高雄科技大學 教務處</span>
            <span className="org-badge">教育推廣與經營管理處</span>
          </div>
          <div className="orgs-row">
            <div className="role">合辦單位</div>
            <span className="org-badge">高雄市彌陀區 壽齡國民小學</span>
            <span className="org-badge">高雄市路竹區 北嶺國民小學</span>
          </div>
          <div className="orgs-row">
            <div className="role">協辦單位</div>
            <span className="org-badge">教學發展中心</span>
            <span className="org-badge">USR 推動辦公室</span>
            <span className="org-badge">教育推廣中心</span>
            <span className="org-badge">智慧製造與智能材料研究服務中心</span>
            <span className="org-badge">產品整合設計暨試量產研發中心</span>
          </div>
        </div>
      </div>
    </section>);

}

Object.assign(window, { Nav, Hero, Highlights, About, Schedule, Tournament, Notes, FAQ, Orgs });