// About / 版本資訊 — 設定 → 版本資訊。
// Shows the running version, a Shorebird "檢查更新" flow (check → download → restart),
// and a grouped changelog. Release rows vs. Shorebird 修補 rows are visually distinct.

const BASE_VERSION = '2.4.1';

// Changelog — newest first. `patch` marks a Shorebird code-push entry.
const CHANGELOG = [
  { v: '2.4.1', patch: 3, date: '2026/07/01', notes: [
    '修正部分自選股報價未即時更新',
    '縮短推播通知延遲',
  ] },
  { v: '2.4.1', patch: 2, date: '2026/06/24', notes: [
    '修正登出後仍收到推播的問題',
  ] },
  { v: '2.4.1', patch: null, date: '2026/06/18', notes: [
    '新增用戶管理後台',
    '支援看盤時螢幕長亮',
    '效能與穩定度優化',
  ] },
  { v: '2.4.0', patch: null, date: '2026/05/30', notes: [
    '全新訂閱管理介面',
    '市場聊天室改版',
  ] },
];

function About({ navigate, patchNumber = 3 }) {
  const t = window.flutterTokens;
  const running = `${BASE_VERSION}.${patchNumber ?? 0}`;

  // Update-check state machine (simulated for the prototype).
  // In production: ShorebirdUpdater().checkForUpdate() → .update() → Restart.restartApp()
  const [status, setStatus] = React.useState('idle'); // idle | checking | latest | available | downloading | restart
  const timer = React.useRef(null);
  React.useEffect(() => () => clearTimeout(timer.current), []);

  const runStep = (next, ms, val) => { timer.current = setTimeout(() => setStatus(val), ms); setStatus(next); };

  const onCheck = () => {
    if (status === 'checking' || status === 'downloading') return;
    if (status === 'available') { // start download
      timer.current = setTimeout(() => setStatus('restart'), 1600);
      setStatus('downloading');
      return;
    }
    if (status === 'restart') return;
    // idle / latest → check. Demo: pretend a patch is available.
    timer.current = setTimeout(() => setStatus('available'), 1100);
    setStatus('checking');
  };

  const cfg = {
    idle:        { label: '檢查更新',        icon: 'refresh', tone: 'ink',   sub: null },
    checking:    { label: '檢查中…',          icon: 'refresh', tone: 'ink',   sub: null, spin: true },
    latest:      { label: '已是最新版本',      icon: 'check',   tone: 'mint',  sub: '你正在使用最新的更新' },
    available:   { label: '下載更新',          icon: 'download',tone: 'accent',sub: '有可用的 Shorebird 更新' },
    downloading: { label: '下載中…',          icon: 'download',tone: 'accent',sub: null, spin: true },
    restart:     { label: '重新啟動以套用',    icon: 'refresh', tone: 'accent',sub: '更新已下載完成' },
  }[status];

  const toneColor = { ink: t.ink, mint: t.mintDk, accent: t.ink }[cfg.tone];

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 60, background: t.surfaceAlt,
      display: 'flex', flexDirection: 'column',
      animation: 'pushIn 240ms cubic-bezier(.2,.7,.2,1)',
    }}>
      <style>{`@keyframes aboutSpin{to{transform:rotate(360deg)}}`}</style>

      {/* App bar */}
      <div style={{
        padding: '60px 16px 12px', background: t.surface, flexShrink: 0,
        borderBottom: `1px solid ${t.hairline}`,
        display: 'flex', alignItems: 'center', gap: 4,
      }}>
        <button onClick={() => navigate({ screen: 'list' })} style={{
          background: 'none', border: 'none', cursor: 'pointer',
          padding: 6, marginLeft: -6, color: t.ink, display: 'flex',
        }}>
          <window.Icon name="back" size={22}/>
        </button>
        <div style={{
          flex: 1, minWidth: 0, textAlign: 'center',
          fontFamily: '"Plus Jakarta Sans", "Noto Sans TC", sans-serif',
          fontSize: 18, fontWeight: 700, color: t.ink, letterSpacing: -0.4,
        }}>版本資訊</div>
        <div style={{ width: 34 }}/>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 40 }}>
        {/* Current version hero */}
        <div style={{ padding: '30px 24px 22px', textAlign: 'center' }}>
          <div style={{
            width: 56, height: 56, borderRadius: 16, margin: '0 auto 14px',
            background: t.ink, display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <window.Icon name="candles" size={28} color="#fff" strokeWidth={2}/>
          </div>
          <div style={{
            fontFamily: '"Plus Jakarta Sans", "Noto Sans TC", sans-serif',
            fontSize: 20, fontWeight: 700, color: t.ink, letterSpacing: -0.4,
          }}>股票提醒</div>
          <div style={{
            marginTop: 6, fontSize: 15, fontWeight: 600, color: t.ink2,
            fontVariantNumeric: 'tabular-nums', letterSpacing: 0.2,
          }}>版本 {running}</div>
        </div>

        {/* Update-check card */}
        <div style={{ padding: '0 14px' }}>
          <button
            onClick={onCheck}
            style={{
              width: '100%', background: t.surface, border: `1px solid ${t.hairline}`,
              borderRadius: 14, padding: '15px 18px', cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 14, textAlign: 'left',
              fontFamily: 'inherit',
            }}
          >
            <span style={{
              flexShrink: 0, width: 30, display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: toneColor,
              animation: cfg.spin ? 'aboutSpin 900ms linear infinite' : 'none',
            }}>
              <window.Icon name={cfg.icon} size={22} color={toneColor} strokeWidth={1.8}/>
            </span>
            <span style={{ flex: 1, minWidth: 0 }}>
              <span style={{ display: 'block', fontSize: 16, fontWeight: 600, color: toneColor, letterSpacing: -0.2 }}>{cfg.label}</span>
              {cfg.sub && <span style={{ display: 'block', marginTop: 2, fontSize: 12.5, color: t.ink3 }}>{cfg.sub}</span>}
            </span>
            {status === 'available' && (
              <span style={{
                flexShrink: 0, width: 9, height: 9, borderRadius: '50%', background: t.coralDk,
              }}/>
            )}
          </button>
        </div>

        {/* Changelog */}
        <div style={{
          padding: '26px 22px 10px',
          fontFamily: '"Plus Jakarta Sans", "Noto Sans TC", sans-serif',
          fontSize: 12, fontWeight: 700, color: t.ink3, letterSpacing: 1,
        }}>版本紀錄</div>

        <div style={{ margin: '0 14px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {CHANGELOG.map((e, i) => {
            const isRunning = e.v === BASE_VERSION && (e.patch ?? 0) === (patchNumber ?? 0);
            return (
              <div key={i} style={{
                background: t.surface, border: `1px solid ${t.hairline}`,
                borderRadius: 14, padding: '16px 18px',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                  <span style={{
                    fontSize: 16, fontWeight: 700, color: t.ink, letterSpacing: -0.3,
                    fontVariantNumeric: 'tabular-nums',
                  }}>{e.v}{e.patch != null ? `.${e.patch}` : ''}</span>
                  {isRunning && (
                    <span style={{
                      fontSize: 10.5, fontWeight: 700, letterSpacing: 0.3,
                      color: t.ink, border: `1px solid ${t.hairline}`,
                      padding: '2px 7px', borderRadius: 999,
                    }}>目前版本</span>
                  )}
                  <span style={{ marginLeft: 'auto', fontSize: 12, color: t.ink3, fontVariantNumeric: 'tabular-nums' }}>{e.date}</span>
                </div>
                <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 7 }}>
                  {e.notes.map((n, j) => (
                    <li key={j} style={{ display: 'flex', gap: 9, fontSize: 13.5, color: t.ink2, lineHeight: 1.45 }}>
                      <span style={{ flexShrink: 0, width: 4, height: 4, borderRadius: '50%', background: t.ink3, marginTop: 7 }}/>
                      <span>{n}</span>
                    </li>
                  ))}
                </ul>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { About });
