/* global React, RC, FONTS, rgba, examTier, ELEV, IcGradCap, IcArrowUp, IcHeart,
   IcTrash, IcChevDown, Waveform, PhoneFrame, Skipping */
// ─────────────────────────────────────────────────────────────
// RopeCounter V3 — Result (unified video card + 4-col stats + "回到练习页")
// & Record Detail (96pt bold mono count + "个" + exam badge + progress + 2x2 grid)
// Synchronized with iOS MeasurementView.swift & RecordDetailView.swift (_claudecode_20261104) // 2026.11.04 Naron
// ─────────────────────────────────────────────────────────────

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

// top bar with a leading control (close × or back ‹)
function TopBar({ c, font, leading = 'close', title, onLeading, trailing }) {
  return (
    <div style={{ position: 'absolute', top: 54, left: 0, right: 0, height: 44, zIndex: 10,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 10px' }}>
      <button onClick={onLeading} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 8,
        display: 'flex', alignItems: 'center', gap: 4, color: c.textPri, fontFamily: font.sans, fontSize: 17 }}>
        {leading === 'close'
          ? <svg width="22" height="22" viewBox="0 0 22 22"><circle cx="11" cy="11" r="11" fill={c.surfaceMuted}/><path d="M7 7l8 8M15 7l-8 8" stroke={c.textSec} strokeWidth="1.8" strokeLinecap="round"/></svg>
          : <svg width="12" height="20" viewBox="0 0 12 20" fill="none"><path d="M10 2L2 10l8 8" stroke={c.textPri} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>}
      </button>
      {title && <div style={{ fontSize: 16, fontWeight: 600, color: c.textPri }}>{title}</div>}
      <div style={{ minWidth: 38, paddingRight: 6 }}>{trailing}</div>
    </div>
  );
}

// ── Hero result block for RecordDetailView (X130 G2 + X147-A16/A16b: 96pt bold mono + 20pt "个" on right baseline) ── // 2026.11.04 Naron
function HeroResult({ c, font, count, score, maxScore, fullMark, dark, isExam = true }) {
  const tier = examTier(score, maxScore);
  const tierC = isExam ? c[tier] : c.textPri;
  const pct = Math.min(count / fullMark, 1);
  const remain = Math.max(0, fullMark - count);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
      <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 6 }}>
        <span style={{ fontSize: 20, visibility: 'hidden' }} aria-hidden="true">个</span>
        <span style={{ fontFamily: font.mono, fontSize: 96, fontWeight: 700, lineHeight: 0.92, color: tierC,
          fontVariantNumeric: 'tabular-nums', letterSpacing: 0 }}>{count}</span>
        <span style={{ fontSize: 20, color: c.textTer, fontWeight: 500 }}>个</span>
      </div>

      {isExam && (
        <>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '9px 18px', borderRadius: 999,
            background: rgba(tierC, dark ? 0.18 : 0.14), color: tierC, fontFamily: font.mono, fontSize: 19, fontWeight: 600,
            fontVariantNumeric: 'tabular-nums' }}>
            <IcGradCap size={16} color={tierC}/>
            体测 {score} 分 / 满分 {maxScore}
          </div>

          {/* progress to full mark */}
          <div style={{ width: '100%', marginTop: 4 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: c.textPri, marginBottom: 8 }}>
              {remain <= 0 ? '已达满分线 ✓' : `距满分还差 ${remain} 个`}
            </div>
            <div style={{ position: 'relative', height: 8, borderRadius: 999, background: c.surfaceMuted, overflow: 'hidden' }}>
              <div style={{ position: 'absolute', inset: 0, width: `${pct * 100}%`, background: tierC, borderRadius: 999 }}/>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontFamily: font.mono, fontSize: 12, color: c.textSec, fontVariantNumeric: 'tabular-nums' }}>
              <span>你的位置 {count}</span><span>满分 {fullMark}</span>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function StatsGrid({ c, font, dark, stats }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', background: c.surface, borderRadius: 16, overflow: 'hidden',
      border: dark ? `1px solid ${c.border}` : 'none', boxShadow: dark ? 'none' : ELEV[2] }}>
      {stats.map((s, i) => (
        <div key={s.label} style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 4,
          borderRight: i % 2 === 0 ? `1px solid ${c.border}` : 'none',
          borderTop: i >= 2 ? `1px solid ${c.border}` : 'none' }}>
          <div style={{ fontSize: 12, color: c.textSec }}>{s.label}</div>
          <div style={{ fontFamily: font.mono, fontSize: 17, fontWeight: 600, color: c.textPri, fontVariantNumeric: 'tabular-nums' }}>{s.val}</div>
        </div>
      ))}
    </div>
  );
}

// ── Screen C: Result (iOS X146-A + 2026-10-29 unified ResultView: Video Card -> 4-col stats row -> "回到练习页") ── // 2026.11.04 Naron
function ResultScreen({ platform = 'ios', dark = false, onAgain, onSave,
  count = 247, dur = '01:00', speed = 142, kcal = 24 }) {
  const c = dark ? RC.dark : RC.light;
  const font = platform === 'android' ? FONTS.android : FONTS.ios;
  const goPractice = onSave || onAgain;

  return (
    <PhoneFrame platform={platform} dark={dark} statusDark={!dark} hideTab>
      <div style={{ position: 'absolute', inset: 0, background: c.bg }}/>
      <div style={{ position: 'absolute', top: 64, left: 16, right: 16, bottom: 26, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20 }}>
        {/* Vertical Video Result Card (9:16 portrait preview centered) */}
        <div style={{
          flex: 1, width: 296, maxWidth: '100%', borderRadius: 20, overflow: 'hidden', position: 'relative',
          background: dark ? 'linear-gradient(170deg,#262420 0%,#161412 100%)' : 'linear-gradient(170deg,#d8cfc2 0%,#9e917d 100%)',
          border: `1px solid ${c.border}`, boxShadow: dark ? 'none' : ELEV[2],
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <div style={{ opacity: 0.45 }}>
            <Skipping width={160} height={240} opacity={0.85}/>
          </div>
          {/* Play button overlay */}
          <div style={{
            position: 'absolute', width: 56, height: 56, borderRadius: 999,
            background: 'rgba(15,23,42,0.56)', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
            border: '1px solid rgba(255,255,255,0.28)', display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff"><path d="M8 5.2v13.6c0 .8.9 1.3 1.6.8l10.2-6.8c.6-.4.6-1.2 0-1.6L9.6 4.4C8.9 3.9 8 4.4 8 5.2z"/></svg>
          </div>
          <div style={{
            position: 'absolute', left: 12, bottom: 12, padding: '4px 10px', borderRadius: 999,
            background: 'rgba(15,23,42,0.52)', color: '#fff', fontFamily: font.mono, fontSize: 12, fontWeight: 600
          }}>{dur} · 点击回看录像</div>
        </div>

        {/* 1-row 4-column stats (legacyStatsRow4_claudecode_20260917: 本次总数 | 时长 | 速度 | 卡路里) */}
        <div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 0' }}>
          {[
            { label: '本次总数', val: `${count} 个`, accent: true },
            { label: '时长', val: dur },
            { label: '速度', val: `${speed} 个/分` },
            { label: '卡路里', val: `≈ ${kcal}` },
          ].map((col, idx) => (
            <React.Fragment key={col.label}>
              {idx > 0 && <div style={{ width: 1, height: 32, background: c.border }}/>}
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                <span style={{ fontSize: 12, color: c.textSec }}>{col.label}</span>
                <span style={{ fontFamily: font.mono, fontSize: 15, fontWeight: 600, color: col.accent ? c.accent : c.textPri, fontVariantNumeric: 'tabular-nums' }}>{col.val}</span>
              </div>
            </React.Fragment>
          ))}
        </div>

        {/* Primary CTA: "回到练习页" (2026-10-29) */}
        <button onClick={goPractice} style={{
          width: '100%', height: 56, borderRadius: 12, border: 'none', cursor: 'pointer', flexShrink: 0,
          background: c.accent, color: c.onAccent, fontFamily: font.sans, fontSize: 17, fontWeight: 600,
          boxShadow: dark ? 'none' : ELEV[2]
        }}>回到练习页</button>
      </div>
    </PhoneFrame>
  );
}

// ── Screen E: Record Detail (iOS RecordDetailView.swift) ── // 2026.11.04 Naron
function RecordDetailScreen({ platform = 'ios', dark = false, onBack, onDelete,
  count = 224, score = 15, maxScore = 20, fullMark = 340, date = '2026-11-04 周三 16:20', modeLabel = '定时' }) {
  const c = dark ? RC.dark : RC.light;
  const font = platform === 'android' ? FONTS.android : FONTS.ios;
  return (
    <PhoneFrame platform={platform} dark={dark} statusDark={!dark} hideTab>
      <div style={{ position: 'absolute', inset: 0, background: c.bg }}/>
      <TopBar c={c} font={font} leading="back" title="记录详情" onLeading={onBack}/>
      <div style={{ position: 'absolute', top: 104, left: 16, right: 16, bottom: 20, overflow: 'auto',
        display: 'flex', flexDirection: 'column', gap: 16, paddingBottom: 20 }}>
        <div style={{ textAlign: 'center', fontSize: 12, color: c.textTer, fontFamily: font.mono }}>{date}</div>
        <HeroResult c={c} font={font} dark={dark} count={count} score={score} maxScore={maxScore} fullMark={fullMark}/>
        <StatsGrid c={c} font={font} dark={dark} stats={[
          { label: '时长', val: '01:00' },
          { label: '速度', val: '139 个/分' },
          { label: '消耗', val: '≈ 22 千卡' },
          { label: '模式', val: modeLabel },
        ]}/>
        <button onClick={onDelete} style={{ height: 50, borderRadius: 14, background: 'none', cursor: 'pointer',
          border: `1px solid ${c.border}`, color: c.danger, fontFamily: font.sans, fontSize: 16, fontWeight: 500,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
          <IcTrash size={17} color={c.danger}/>删除这条记录
        </button>
      </div>
    </PhoneFrame>
  );
}

Object.assign(window, { ResultScreen, RecordDetailScreen, TopBar });
