/* global React, RC, FONTS, rgba, ELEV, PhoneFrame, SCREEN_W, TabHeader */
// ─────────────────────────────────────────────────────────────
// RopeCounter V3 — Tab 1「跳绳」: pick a mode, set a target, start.
// Synchronized with iOS IdleView in MeasurementView.swift (_claudecode_20261104):
// - 3 modes: 定时 (goalTime / exam 60″ preset) · 定数 (goalCount) · 自由 (free)
// - Header subtitle centered on title row:
//   timed: "上次定时01:20，跳绳80个"
//   count: "上次定数80个，用时01:20"
//   free:  "上次自由01:20，跳绳80个"
// - Free mode hero "想跳就跳": 44.8pt (64 * 0.70) light rounded, same row height as 64pt digits
// - Free mode hint: "自在随心" (height 30pt, matching preset chips row)
// - Count presets: [100, 200, 500, 1000] (pure numbers without comma)
// - CTA: "开始跳 01:00" / "开始跳 200 个" / "开始跳绳" // 2026.11.04 Naron
// ─────────────────────────────────────────────────────────────
const { useState: useStateH } = React;

const START_MODES = [
  { key: 'timed', label: '定时' },
  { key: 'count', label: '定数' },
  { key: 'free',  label: '自由' },
];

function fmtSec(sec) {
  const m = Math.floor(sec / 60), s = sec % 60;
  return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}

// Step button — tap = ±10; press-and-hold repeats, accelerating (280ms → 40ms).
function StepBtn({ c, dark, dir, onStep, disabled }) {
  const timer = React.useRef(null), delay = React.useRef(280);
  const stop = () => { if (timer.current) clearTimeout(timer.current); timer.current = null; delay.current = 280; };
  const loop = () => { onStep(); delay.current = Math.max(40, delay.current * 0.82); timer.current = setTimeout(loop, delay.current); };
  const start = (e) => { if (disabled) return; e.preventDefault(); onStep(); timer.current = setTimeout(loop, 420); };
  React.useEffect(() => stop, []);
  return (
    <button disabled={disabled} aria-label={dir === '+' ? '增加' : '减少'}
      onPointerDown={start} onPointerUp={stop} onPointerLeave={stop} onPointerCancel={stop} onContextMenu={(e) => e.preventDefault()}
      style={{ width: 52, height: 52, borderRadius: 999, border: 'none', cursor: disabled ? 'default' : 'pointer', touchAction: 'none', userSelect: 'none',
        background: rgba(c.accent, dark ? 0.18 : 0.10), color: c.accent, opacity: disabled ? 0.35 : 1,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke={c.accent} strokeWidth="2.4" strokeLinecap="round"><path d="M4 10h12"/>{dir === '+' && <path d="M10 4v12"/>}</svg>
    </button>
  );
}

function ModeSegmented({ c, dark, font, value, onChange }) {
  return (
    <div style={{ display: 'flex', background: c.surfaceMuted, borderRadius: 14, padding: 4, gap: 2 }}>
      {START_MODES.map((m) => {
        const on = m.key === value;
        return (
          <button key={m.key} onClick={() => onChange(m.key)} style={{
            flex: 1, height: 40, border: 'none', borderRadius: 11, cursor: 'pointer',
            background: on ? c.surface : 'transparent', color: on ? c.textPri : c.textSec,
            fontFamily: font.sans, fontSize: 15, fontWeight: on ? 600 : 500, letterSpacing: -0.2,
            boxShadow: on ? (dark ? 'none' : ELEV[1]) : 'none', border: on && dark ? `1px solid ${c.border}` : 'none',
            transition: 'background 160ms'
          }}>{m.label}</button>
        );
      })}
    </div>
  );
}

// Which recording-engine mode a start-config resolves to.
function resolveStart(cfg) {
  if (cfg.mode === 'timed') return { mode: 'goalTime', durationMin: cfg.sec / 60 };
  if (cfg.mode === 'count') return { mode: 'goalCount', targetCount: cfg.count };
  return { mode: 'free' };
}

function StartScreen({ platform = 'ios', dark = false, tab = 'measure', onTab, onStart, province = 'BJ', onPickProvince, cfg, onCfg, pro, onPro, last = true, quotaExhausted = false, onQuotaPaywall }) {
  const c = dark ? RC.dark : RC.light;
  const font = platform === 'android' ? FONTS.android : FONTS.ios;
  const [local, setLocal] = useStateH({ mode: 'timed', sec: 60, count: 200, exam: true });
  const s = cfg || local, set = (patch) => (onCfg || setLocal)({ ...s, ...patch });
  const isTimed = s.mode === 'timed', isCount = s.mode === 'count';

  // Stepper ±10 (iOS minSec=10, maxSec=1800; minCount=10, maxCount=3000) // 2026.11.04 Naron
  const step = (delta) => {
    if (isTimed) {
      const next = Math.min(1800, Math.max(10, s.sec + delta * 10));
      set({ sec: next });
    } else if (isCount) {
      const next = Math.min(3000, Math.max(10, s.count + delta * 10));
      set({ count: next });
    }
  };

  let hero, hint;
  if (isTimed) {
    hero = fmtSec(s.sec); hint = null;
  } else if (isCount) {
    hero = String(s.count); hint = null;
  } else {
    hero = '想跳就跳'; hint = '自在随心';
  }

  // Last session subtitle per mode (X168-B / X168-D exact punctuation & spacing) // 2026.11.04 Naron
  const LAST = {
    timed: '上次定时01:20，跳绳80个',
    count: '上次定数80个，用时01:20',
    free:  '上次自由01:20，跳绳80个',
  };
  const lastLine = last ? LAST[s.mode] : null;

  const cta = isTimed ? `开始跳 ${fmtSec(s.sec)}` : isCount ? `开始跳 ${s.count} 个` : '开始跳绳';

  return (
    <PhoneFrame platform={platform} dark={dark} statusDark={!dark} tab={tab} onTab={onTab}>
      <div style={{ position: 'absolute', inset: 0, background: c.bg }} />
      <TabHeader c={c} font={font} platform={platform} title="跳绳" subtitle={lastLine} />

      <div style={{ position: 'absolute', top: platform === 'android' ? 110 : 112, left: 16, right: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {/* mode card (height 330, radius 24, padding 16) */}
        <div style={{ height: 330, position: 'relative', overflow: 'hidden', background: c.surface, borderRadius: 24, padding: 16,
          border: dark ? `1px solid ${c.border}` : 'none', boxShadow: dark ? 'none' : ELEV[2], display: 'flex', flexDirection: 'column' }} data-comment-anchor="8c495e73a2-div-80-9">
          <ModeSegmented c={c} dark={dark} font={font} value={s.mode} onChange={(k) => set({ mode: k })} />

          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14, position: 'relative' }}>
            {/* stepper row — free mode uses 44.8px (70% of 64px) light rounded inside 64px strut */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, width: '100%', justifyContent: 'center', minHeight: 64 }}>
              {(isTimed || isCount) && <StepBtn c={c} dark={dark} dir="-" disabled={isTimed ? s.sec <= 10 : s.count <= 10} onStep={() => step(-1)} />}
              <div style={{
                minWidth: 170, height: 64, display: 'flex', alignItems: 'center', justifyContent: 'center',
                textAlign: 'center', fontFamily: font.rounded,
                fontSize: s.mode === 'free' ? 44.8 : 64, fontWeight: 300,
                color: c.textPri, fontVariantNumeric: 'tabular-nums',
                letterSpacing: s.mode === 'free' ? 0 : -2, lineHeight: 1
              }}>{hero}</div>
              {(isTimed || isCount) && <StepBtn c={c} dark={dark} dir="+" disabled={isTimed ? s.sec >= 1800 : s.count >= 3000} onStep={() => step(1)} />}
            </div>

            {hint ? (
              <div style={{ height: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13.5, color: c.textSec, fontWeight: 500 }}>{hint}</div>
            ) : (
              <div style={{ display: 'flex', justifyContent: 'center', gap: 6, height: 30, alignItems: 'center' }}>
                {(isTimed ? [30, 60, 180, 300] : [100, 200, 500, 1000]).map((v) => {
                  const on = isTimed ? s.sec === v : s.count === v;
                  return (
                    <button key={v} onClick={() => isTimed ? set({ sec: v }) : set({ count: v })} style={{
                      height: 30, padding: '0 12px', borderRadius: 999, border: 'none', cursor: 'pointer',
                      background: on ? rgba(c.accent, dark ? 0.2 : 0.12) : c.surfaceMuted,
                      color: on ? c.accent : c.textSec, fontFamily: font.mono, fontSize: 12.5, fontWeight: 600
                    }}>{isTimed ? (v < 60 ? `${v}″` : `${v / 60}′`) : String(v)}</button>
                  );
                })}
              </div>
            )}
          </div>
        </div>

        <button onClick={quotaExhausted ? onQuotaPaywall : () => onStart && onStart(resolveStart(s))} style={{
          height: 56, borderRadius: 16, border: 'none', cursor: 'pointer', flexShrink: 0,
          background: quotaExhausted ? c.warning : c.accent,
          color: quotaExhausted ? '#FFFFFF' : c.onAccent,
          fontFamily: font.sans, fontSize: 17, fontWeight: 600, letterSpacing: -0.2,
          boxShadow: dark ? 'none' : ELEV[2],
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6
        }}>
          {quotaExhausted ? (
            <>
              <span>新手村额度已用完</span>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M17 9h-1V7a4 4 0 0 0-8 0v2H7a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2zm-7-2a2 2 0 1 1 4 0v2h-4V7z"/></svg>
              <span>点击查看解锁攻略</span>
            </>
          ) : cta}
        </button>
      </div>
    </PhoneFrame>
  );
}

Object.assign(window, { StartScreen, START_MODES, resolveStart, fmtSec });
