/* global React */
const { useState, useEffect, useMemo, useRef } = React;

// ═══════════════════════════════════════════════
// Regulus · 共燃英語團  —  主應用
// ═══════════════════════════════════════════════

const START_DATE = new Date('2026-04-19'); // Day 1 = today

function daysSince(date) {
  const ms = Date.now() - date.getTime();
  return Math.max(1, Math.floor(ms / 86400000) + 1);
}

// localStorage persistence hook
function useStore(key, initial) {
  const [val, setVal] = useState(() => {
    try {
      const raw = localStorage.getItem('regulus.' + key);
      return raw ? JSON.parse(raw) : initial;
    } catch { return initial; }
  });
  useEffect(() => {
    try { localStorage.setItem('regulus.' + key, JSON.stringify(val)); } catch {}
  }, [key, val]);
  return [val, setVal];
}

// ═══════════════ STAR SVG (獅子座 α 星) ═══════════════
function ConstellationLeo({ size = 180, pulse = true }) {
  // 獅子座的主要星點（近似）— Regulus 在左下，最亮
  const stars = [
    { x: 28,  y: 132, r: 6.5, name: 'Regulus', main: true, label: 'α' },
    { x: 60,  y: 96,  r: 3.0, name: 'η Leo' },
    { x: 92,  y: 72,  r: 3.8, name: 'γ Leo', label: 'γ' },
    { x: 130, y: 48,  r: 3.2, name: 'ζ Leo' },
    { x: 158, y: 30,  r: 4.0, name: 'μ Leo' },
    { x: 118, y: 120, r: 3.5, name: 'θ Leo' },
    { x: 150, y: 108, r: 3.8, name: 'δ Leo', label: 'δ' },
    { x: 175, y: 130, r: 5.2, name: 'Denebola', label: 'β' },
    { x: 78,  y: 140, r: 3.0, name: '' },
  ];
  const lines = [[0,1],[1,2],[2,3],[3,4],[2,5],[5,6],[6,7],[0,8],[8,5]];
  return (
    <svg viewBox="0 0 200 170" width={size} height={size * 170/200} style={{ overflow: 'visible' }}>
      {lines.map(([a,b], i) => (
        <line key={i}
          x1={stars[a].x} y1={stars[a].y}
          x2={stars[b].x} y2={stars[b].y}
          stroke="var(--ink-faint)" strokeWidth="0.6" strokeDasharray="1.5 2" opacity="0.55" />
      ))}
      {stars.map((s, i) => (
        <g key={i}>
          {s.main && pulse && (
            <circle cx={s.x} cy={s.y} r={s.r + 4} fill="var(--star)" opacity="0.18">
              <animate attributeName="r" values={`${s.r+4};${s.r+10};${s.r+4}`} dur="2.8s" repeatCount="indefinite" />
              <animate attributeName="opacity" values="0.22;0.05;0.22" dur="2.8s" repeatCount="indefinite" />
            </circle>
          )}
          <circle cx={s.x} cy={s.y} r={s.r}
            fill={s.main ? 'var(--star)' : 'var(--ink)'}
            stroke={s.main ? 'var(--star-glow)' : 'none'}
            strokeWidth={s.main ? 1.5 : 0} />
          {s.label && (
            <text x={s.x + s.r + 4} y={s.y + 3}
              fontFamily="var(--f-hand)" fontSize="14"
              fill={s.main ? 'var(--star)' : 'var(--ink-faint)'}
              fontWeight={s.main ? 700 : 400}>
              {s.label}
            </text>
          )}
          {s.main && (
            <text x={s.x - 6} y={s.y + 24}
              fontFamily="var(--f-hand)" fontSize="16"
              fill="var(--star)" fontWeight={700}>
              Regulus
            </text>
          )}
        </g>
      ))}
    </svg>
  );
}

// ═══════════════ HERO ═══════════════
function Hero({ day, goal }) {
  return (
    <section style={{ padding: '32px 0 20px', position: 'relative' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 48, alignItems: 'start' }}>
        <div>
          <div style={{ fontFamily: 'var(--f-mono)', fontSize: 11, letterSpacing: '0.2em',
                        textTransform: 'uppercase', color: 'var(--ink-faint)', marginBottom: 16 }}>
            Personal  ·  AI 共燃英語團  ·  Ch. Regulus
          </div>
          <h1 className="hand" style={{ fontSize: 92, lineHeight: 0.92, fontWeight: 700,
                                         letterSpacing: '-2px', color: 'var(--ink)' }}>
            22 天後<br/>
            <span className="hl-yellow">我要聽得懂</span><br/>
            NFL 的<span style={{ color: 'var(--red-mark)' }}>英文</span>解說
          </h1>
          <p className="serif" style={{ fontSize: 17, color: 'var(--ink-2)', marginTop: 24,
                                         maxWidth: 560, lineHeight: 1.75 }}>
            年底賽季開打前，達到能聽懂英文解說、並對基礎戰術有所理解的程度。
            <br/>不為工作學、為熱愛學 — 這樣才不會想放棄。
          </p>
          <div style={{ display: 'flex', gap: 24, marginTop: 40, alignItems: 'center' }}>
            <div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--ink-faint)',
                                              letterSpacing: '0.15em', textTransform: 'uppercase' }}>
                Today is
              </div>
              <div className="hand" style={{ fontSize: 72, fontWeight: 700, lineHeight: 1,
                                              color: 'var(--star)', marginTop: 4 }}>
                Day {day}
              </div>
            </div>
            <div style={{ width: 1, height: 90, background: 'var(--rule)' }} />
            <div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--ink-faint)',
                                              letterSpacing: '0.15em', textTransform: 'uppercase' }}>
                Of the 共燃 journey
              </div>
              <div className="serif" style={{ fontSize: 15, color: 'var(--ink-2)', marginTop: 8,
                                                fontStyle: 'italic', maxWidth: 240 }}>
                「不是倒數，是累積。<br/>每一天都在添柴火。」
              </div>
            </div>
          </div>
        </div>

        {/* RIGHT: 星座 + 終端打招呼 */}
        <div style={{ position: 'relative' }}>
          <div style={{ position: 'relative', padding: '20px 0 28px 20px' }}>
            <div className="hand" style={{ position: 'absolute', top: 0, left: 0,
                                            fontSize: 18, color: 'var(--ink-faint)',
                                            transform: 'rotate(-4deg)' }}>
              ✦ 獅子座 α 星 ✦
            </div>
            <div style={{ marginTop: 28 }}>
              <ConstellationLeo size={260} />
            </div>
            <div className="hand" style={{ marginTop: 8, fontSize: 14, color: 'var(--ink-2)',
                                            maxWidth: 260, lineHeight: 1.4, fontStyle: 'italic' }}>
              「Regulus 在拉丁文裡是『小國王』。<br/>
              &nbsp;&nbsp;夜空裡最亮的那顆，就是我。」
            </div>
          </div>

          <div className="terminal" style={{ marginTop: 24 }}>
            <div className="terminal-body">
              <div className="term-line">
                <span className="term-prompt">$</span>
                <span>whoami</span>
              </div>
              <div style={{ paddingLeft: 18, color: 'var(--term-fg)' }}>regulus · learner · NFL rookie</div>
              <div className="term-line" style={{ marginTop: 8 }}>
                <span className="term-prompt">$</span>
                <span>cat ./mission.txt</span>
              </div>
              <div style={{ paddingLeft: 18 }}>
                <span className="term-comment"># Day {day} of 共燃</span><br/>
                <span className="term-key">goal</span>: <span className="term-val">"understand NFL broadcasts in English"</span><br/>
                <span className="term-key">deadline</span>: <span className="term-val">"before season kickoff"</span><br/>
                <span className="term-key">mode</span>: <span className="term-val">"C · challenge"</span>
              </div>
              <div className="term-line" style={{ marginTop: 8 }}>
                <span className="term-prompt">$</span>
                <span>_<span className="term-caret" /></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.useStore = useStore;
window.daysSince = daysSince;
window.START_DATE = START_DATE;
window.Hero = Hero;
window.ConstellationLeo = ConstellationLeo;
