/* global React, RC, FONTS, rgba, examTier, ELEV, MODES, IcGradCap, IcPause,
   IcChevDown, CameraFeed, CamScrim, Skipping, Waveform, PhoneFrame */
// ─────────────────────────────────────────────────────────────
// RopeCounter V2 — ⭐ Recording screen (3-zone layout)
// Zone 1 camera (top 58%) · Zone 2 waveform (bottom-left 55%w) ·
// Zone 3 count (bottom-right 45%w). Gaps space.sm(8), edge space.lg(16).
// Count + badge sit on a SURFACE card → accent count + over-surface
// badge tint (not the over-camera white treatment).
// States: idle | active(exam) | active(free/goal). Live-animated.
// ─────────────────────────────────────────────────────────────
const { useState: useStateR, useEffect: useEffectR, useRef: useRefR } = React;

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

// ─── Glass pill (over-camera) ───
function GlassPill({ children, onClick, strong = false, style = {} }) {
  return (
    <div role={onClick ? 'button' : undefined} onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 7,
      padding: '7px 13px', borderRadius: 999,
      background: strong ? 'rgba(0,0,0,0.42)' : 'rgba(0,0,0,0.36)',
      backdropFilter: 'blur(18px) saturate(180%)', WebkitBackdropFilter: 'blur(18px) saturate(180%)',
      border: '0.5px solid rgba(255,255,255,0.22)', color: 'rgba(255,255,255,0.96)',
      fontSize: 14, fontWeight: 600, letterSpacing: -0.1, cursor: onClick ? 'pointer' : 'default',
      whiteSpace: 'nowrap', flexShrink: 0,
      ...style,
    }}>{children}</div>
  );
}

function RecBadge() {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 11px 5px 9px',
      borderRadius: 999, background: 'rgba(0,0,0,0.36)',
      backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
      border: '0.5px solid rgba(255,255,255,0.18)', color: 'rgba(255,255,255,0.92)',
      fontSize: 11.5, fontWeight: 700, letterSpacing: 0.6,
    }}>
      <span className="rc-rec-dot" style={{ width: 7, height: 7, borderRadius: 999, background: '#FF453A' }}/>
      REC
    </div>
  );
}

function CountdownRing({ remaining, total }) {
  const r = 24, circ = 2 * Math.PI * r, pct = remaining / total;
  return (
    <div style={{ width: 56, height: 56, position: 'relative', filter: 'drop-shadow(0 2px 6px rgba(0,0,0,0.4))' }}>
      <svg width="56" height="56" viewBox="0 0 56 56">
        <circle cx="28" cy="28" r={r} fill="rgba(0,0,0,0.28)" stroke="rgba(255,255,255,0.25)" strokeWidth="4"/>
        <circle cx="28" cy="28" r={r} fill="none" stroke="#34D399" strokeWidth="4"
          strokeDasharray={circ} strokeDashoffset={circ * (1 - pct)} strokeLinecap="round"
          transform="rotate(-90 28 28)" style={{ transition: 'stroke-dashoffset 1s linear' }}/>
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 13, fontWeight: 600, color: '#fff', fontFamily: 'ui-monospace, "SF Mono", monospace',
        textShadow: '0 1px 3px rgba(0,0,0,0.6)', letterSpacing: -0.2,
      }}>{fmtClock(remaining)}</div>
    </div>
  );
}

// ─── ModeMenu (idle only) — glass dropdown of the 4 modes ───
function ModeMenu({ mode, open, onToggle, onSet }) {
  const current = MODES.find(m => m.key === mode) || MODES[0];
  return (
    <div style={{ position: 'relative' }}>
      <GlassPill onClick={onToggle} strong>
        {current.key === 'exam' && <IcGradCap size={12} color="rgba(255,255,255,0.96)"/>}
        <span>{current.label}</span>
        <IcChevDown size={11} color="rgba(255,255,255,0.78)"/>
      </GlassPill>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', left: '50%', transform: 'translateX(-50%)',
          minWidth: 168, background: 'rgba(28,28,32,0.9)',
          backdropFilter: 'blur(24px) saturate(180%)', WebkitBackdropFilter: 'blur(24px) saturate(180%)',
          border: '0.5px solid rgba(255,255,255,0.14)', borderRadius: 14, padding: 6,
          boxShadow: '0 12px 32px rgba(0,0,0,0.45)', zIndex: 30,
        }}>
          {MODES.map(m => {
            const active = m.key === mode;
            return (
              <div key={m.key} onClick={() => onSet(m.key)} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
                padding: '9px 12px', borderRadius: 9, cursor: 'pointer',
                color: 'rgba(255,255,255,0.96)', fontSize: 15, fontWeight: active ? 600 : 500,
                background: active ? 'rgba(255,255,255,0.08)' : 'transparent',
              }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  {m.key === 'exam' && <IcGradCap size={12} color="rgba(255,255,255,0.96)"/>}
                  {m.label}
                </span>
                {active && <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 7.5l3 3 6-6.5"/></svg>}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── Zone 2: waveform card ───
function WaveCard({ c, dark, w, h, font, live, flat, cadence }) {
  const padW = w - 24, chartH = Math.max(40, h - 92);
  return (
    <div style={{
      width: w, height: h, background: c.surface, borderRadius: 16, padding: 12,
      boxSizing: 'border-box', display: 'flex', flexDirection: 'column',
      border: dark ? `1px solid ${c.border}` : 'none', boxShadow: dark ? 'none' : ELEV[2],
    }}>
      <div style={{ fontSize: 12, color: c.textSec, fontWeight: 500, marginBottom: 6 }}>跳跃节律</div>
      <div style={{ position: 'relative' }}>
        <Waveform width={padW} height={chartH} accent={c.accent} muted={c.surfaceMuted} live={live} flat={flat} cadence={cadence}/>
        {flat && (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: c.textTer, fontSize: 12.5, fontWeight: 500 }}>准备好了开始跳</div>
        )}
      </div>
      <div style={{ height: 1, background: c.border, margin: '10px 0 8px' }}/>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: font.mono, fontSize: 16, fontWeight: 600, color: flat ? c.textTer : c.accent, fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
            {flat ? '—' : `${cadence} 次/分`}
          </div>
          <div style={{ fontSize: 11, color: c.textTer, marginTop: 3 }}>节拍</div>
        </div>
        {!flat && (
          <div style={{ fontSize: 12, fontWeight: 600, color: c.examHigh, display: 'flex', alignItems: 'center', gap: 3 }}>
            节律 平稳 ✓
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Zone 3: count card ───
function CountCard({ c, dark, w, h, font, mode, state, count, score, maxScore, elapsed, pulse }) {
  const tier = examTier(score, maxScore);
  const tierC = c[tier];
  const isExam = mode === 'exam';
  const idle = state === 'idle';
  // hero fills ~60–70% of card width; scale down for 4+ digits
  const digits = String(count).length;
  const heroSize = idle ? 64 : digits >= 4 ? 52 : 68;
  return (
    <div style={{
      width: w, height: h, background: c.surface, borderRadius: 16, padding: 12,
      boxSizing: 'border-box', display: 'flex', flexDirection: 'column',
      border: dark ? `1px solid ${c.border}` : 'none', boxShadow: dark ? 'none' : ELEV[2],
    }}>
      <div style={{ fontSize: 12, color: c.textSec, fontWeight: 500 }}>已跳</div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
        <div style={{
          fontFamily: font.rounded, fontSize: heroSize, fontWeight: 200, lineHeight: 0.95,
          color: idle ? c.textTer : c.accent, fontVariantNumeric: 'tabular-nums', letterSpacing: -2,
          transform: pulse ? 'scale(1.04)' : 'scale(1)', transition: 'transform 160ms cubic-bezier(.2,.7,.3,1)',
        }}>{idle ? '—' : count}</div>

        {!idle && isExam && (
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 4, padding: '5px 9px', borderRadius: 999,
            background: rgba(tierC, dark ? 0.18 : 0.14), color: tierC,
            fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap', letterSpacing: -0.2,
          }}>
            <IcGradCap size={11} color={tierC}/>
            <span style={{ fontFamily: font.mono, fontVariantNumeric: 'tabular-nums' }}>≈{score}/{maxScore}分</span>
          </div>
        )}
        {!idle && !isExam && (
          <div style={{ fontFamily: font.mono, fontSize: 17, fontWeight: 600, color: c.textSec, fontVariantNumeric: 'tabular-nums' }}>{fmtClock(elapsed)}</div>
        )}
      </div>

      <div style={{ textAlign: 'center', fontSize: 11.5, color: c.textTer, fontWeight: 500, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4 }}>
        {idle ? '点击下方开始' : isExam ? fmtClock(elapsed) : <><IcPause size={11} color={c.textTer}/>长按暂停</>}
      </div>
    </div>
  );
}

// ─── Recording screen ───
function RecordingScreen({
  platform = 'ios', dark = false, mode = 'exam', state = 'idle', live = true,
  province = 'BJ', targetCount = 200, durationMin = 3,
  menuOpen = false, onToggleMenu, onSetMode, onStart, onStop, onPickProvince,
  tab, onTab,
}) {
  const c = dark ? RC.dark : RC.light;
  const font = platform === 'android' ? FONTS.android : FONTS.ios;
  const isExam = mode === 'exam';
  const examGated = isExam && province == null;
  const active = state === 'active';

  // ── live engine ── seeds = spec's representative frame so the canvas
  // static shot and the live prototype both read right; live ticks up from it.
  const seedCount = isExam ? 247 : 312;
  const seedElapsed = isExam ? 28 : 154;
  const totalSec = isExam ? 60 : (mode === 'goalTime' ? durationMin * 60 : 999);
  const [count, setCount] = useStateR(seedCount);
  const [elapsed, setElapsed] = useStateR(seedElapsed);
  const [pulse, setPulse] = useStateR(false);
  const cadence = 142;
  const score = examScore(count);

  useEffectR(() => {
    if (!active || !live) return;
    setCount(seedCount); setElapsed(seedElapsed);
    const beat = 60000 / cadence;
    const tick = setInterval(() => {
      setCount(n => n + 1);
      setPulse(true); setTimeout(() => setPulse(false), 150);
    }, beat);
    const sec = setInterval(() => setElapsed(e => e + 1), 1000);
    return () => { clearInterval(tick); clearInterval(sec); };
    // eslint-disable-next-line
  }, [active, live, mode]);

  const remaining = Math.max(0, totalSec - elapsed);
  useEffectR(() => {
    if (active && isExam && remaining <= 0 && live) { const t = setTimeout(() => onStop && onStop(), 400); return () => clearTimeout(t); }
  }, [active, isExam, remaining, live, onStop]);

  // layout math
  const topReserve = 52;
  const tabH = platform === 'android' ? 78 : 83;
  const bottomReserve = active ? 30 : tabH + 6;
  const ctaBlock = !active ? 56 + 14 + (examGated ? 40 : 0) : 0;
  const blockH = SCREEN_H - topReserve - bottomReserve - ctaBlock - 8;
  const gap = 8;
  const camH = Math.round((blockH - gap) * 0.58);
  const rowH = blockH - gap - camH;
  const rowW = SCREEN_W - 32;
  const z2W = Math.round((rowW - gap) * 0.55);
  const z3W = rowW - gap - z2W;

  const modeLabel = MODES.find(m => m.key === mode)?.label || '自由模式';
  const provLabel = province ? '北京 · 初三 · 男' : null;

  return (
    <PhoneFrame platform={platform} dark={dark} statusDark={!dark} tab={tab} onTab={onTab} hideTab={active}>
      <div style={{ position: 'absolute', inset: 0, background: c.bg }}/>
      <div style={{ position: 'absolute', top: topReserve, left: 16, right: 16, bottom: 0, display: 'flex', flexDirection: 'column', gap }}>

        {/* ── Zone 1: camera card ── */}
        <div style={{ position: 'relative', width: '100%', height: camH, borderRadius: 24, overflow: 'hidden' }}>
          <CameraFeed dark={dark} radius={24}/>
          {/* silhouette guide */}
          <div style={{ position: 'absolute', left: '50%', top: '52%', transform: 'translate(-50%,-50%)' }}>
            <Skipping width={camH * 0.5} height={camH * 0.78} opacity={active ? 0.18 : 0.3}/>
          </div>
          <CamScrim radius={24}/>

          {/* top-left: countdown ring (exam active) + REC */}
          <div style={{ position: 'absolute', top: 12, left: 12, display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-start', zIndex: 4 }}>
            {active && isExam && <CountdownRing remaining={remaining} total={totalSec}/>}
            {active && <RecBadge/>}
          </div>

          {/* top-center: mode (menu when idle, read-only pill when active) */}
          <div style={{ position: 'absolute', top: 12, left: 0, right: 0, display: 'flex', justifyContent: 'center', zIndex: 5 }}>
            {!active
              ? <ModeMenu mode={mode} open={menuOpen} onToggle={onToggleMenu} onSet={onSetMode}/>
              : <GlassPill>{isExam && <IcGradCap size={12} color="rgba(255,255,255,0.96)"/>}{modeLabel}</GlassPill>}
          </div>

          {/* idle secondary chip under the mode menu (exam set / goal) */}
          {!active && (
            <div style={{ position: 'absolute', top: 54, left: 0, right: 0, display: 'flex', justifyContent: 'center', zIndex: 4 }}>
              {isExam && province != null && <GlassPill onClick={onPickProvince} style={{ fontSize: 12.5, fontWeight: 500, padding: '5px 11px' }}>{provLabel}<IcChevDown size={9} color="rgba(255,255,255,0.7)"/></GlassPill>}
              {mode === 'goalCount' && <GlassPill style={{ fontSize: 12.5, fontWeight: 500, padding: '5px 11px' }}>目标 {targetCount} 次<IcChevDown size={9} color="rgba(255,255,255,0.7)"/></GlassPill>}
              {mode === 'goalTime' && <GlassPill style={{ fontSize: 12.5, fontWeight: 500, padding: '5px 11px' }}>{durationMin} 分钟<IcChevDown size={9} color="rgba(255,255,255,0.7)"/></GlassPill>}
            </div>
          )}
        </div>

        {/* ── Zone 2 + 3 row ── */}
        <div style={{ display: 'flex', gap, height: rowH }}>
          <div onClick={active ? onStop : undefined} style={{ cursor: active ? 'pointer' : 'default' }}>
            <WaveCard c={c} dark={dark} w={z2W} h={rowH} font={font} live={active && live} flat={!active} cadence={cadence}/>
          </div>
          <div onClick={active ? onStop : undefined} style={{ cursor: active ? 'pointer' : 'default' }}>
            <CountCard c={c} dark={dark} w={z3W} h={rowH} font={font} mode={mode} state={state} count={count} score={score} maxScore={20} elapsed={elapsed} pulse={pulse}/>
          </div>
        </div>

        {/* ── idle CTA ── */}
        {!active && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 }}>
            {examGated && (
              <div onClick={onPickProvince} role="button" style={{
                alignSelf: 'center', display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 14px', borderRadius: 999,
                background: rgba(c.warning, dark ? 0.18 : 0.14), color: c.warning, fontSize: 13.5, fontWeight: 600, cursor: 'pointer',
              }}>
                <span style={{ width: 6, height: 6, borderRadius: 999, background: c.warning, boxShadow: `0 0 6px ${c.warning}` }}/>
                选择中考标准 →
              </div>
            )}
            <button onClick={examGated ? onPickProvince : onStart} style={{
              height: 56, borderRadius: 16, border: 'none', cursor: 'pointer',
              background: examGated ? c.surfaceMuted : c.accent,
              color: examGated ? c.textTer : c.onAccent,
              fontFamily: font.sans, fontSize: 17, fontWeight: 600, letterSpacing: -0.2,
              boxShadow: examGated ? 'none' : ELEV[2],
            }}>
              {examGated ? '请先选择中考标准' : isExam ? '开始 60 秒测试' : mode === 'goalTime' ? `开始 ${durationMin} 分钟` : '开始测量'}
            </button>
          </div>
        )}
      </div>
    </PhoneFrame>
  );
}

// Exam score curve — anchored to MASTER data: full-mark (20分) = 340 jumps,
// 247 jumps → 17分 (mid tier, 85%). Non-linear like real 中考 tables.
function examScore(count) {
  if (count >= 340) return 20;
  if (count >= 247) return Math.round(17 + (count - 247) * 3 / 93);
  if (count >= 150) return Math.round(11 + (count - 150) * 6 / 97);
  return Math.max(1, Math.round(count / 150 * 11));
}

Object.assign(window, { RecordingScreen });
