/* global React, RC, FONTS, rgba, examTier, ELEV, IcGradCap, IcChevRight, IcCrown,
   SkipIcon, PhoneFrame, SCREEN_W */
// ─────────────────────────────────────────────────────────────
// RopeCounter V3 — Tab 2「练」: Dual-Chart Card + 3 Metric Cards + Score Trend + Recent Records
// Synchronized with iOS TrendsView.swift, RCTrendChartsV3_claudecode_20260906.swift &
// RCRecordRowV3_claudecode_20260904.swift (_claudecode_20261104) // 2026.11.04 Naron
// ─────────────────────────────────────────────────────────────
const { useState: useStateD } = React;

function ProBadge({ c, font, pro, onClick }) {
  const member = !!pro, life = pro === 'forever';
  const bg = life ? '#1E293B' : c.accent, fg = life ? '#F4B942' : c.onAccent;
  const label = pro === 'forever' ? '永久会员' : pro === '3y' ? '3 年会员' : pro === '1y' ? '1 年会员' : pro === '1m' ? '月卡会员' : '开通会员';
  return (
    <span onClick={onClick} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, height: 22, padding: '0 8px 0 6px', borderRadius: 999, cursor: onClick ? 'pointer' : 'default',
      background: member ? bg : 'transparent', border: member ? 'none' : `1px solid ${c.border}`, color: member ? (life ? '#F8FAFC' : c.onAccent) : c.textSec,
      fontFamily: font.sans, fontSize: 11.5, fontWeight: 700, letterSpacing: 0.2, verticalAlign: 'middle' }}>
      <IcCrown size={12} color={member ? fg : c.textTer} filled={life}/>{label}</span>
  );
}

// RCTabPageHeaderV3_claudecode_20260906: top=54, height=112, title on left, optional centered subtitle, optional trailing control (used by Tab 3 WeChat capsule) // 2026.11.04 Naron
function TabHeader({ c, font, platform, title, subtitle, pro, onPro, badge: showBadge, trailing }) {
  const badge = showBadge ? <ProBadge c={c} font={font} pro={pro} onClick={onPro}/> : null;
  if (platform === 'android') {
    return (
      <div style={{ position: 'absolute', top: 54, left: 0, right: 0, zIndex: 8, padding: '14px 20px 10px' }}>
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', minHeight: 30 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 22, fontWeight: 600, color: c.textPri, lineHeight: 1.15 }}>{title}{badge}</span>
          {subtitle && <span style={{ position: 'absolute', left: 0, right: 0, textAlign: 'center', fontSize: 13, lineHeight: 1.15, color: c.textSec, pointerEvents: 'none' }}>{subtitle}</span>}
          {trailing && <div style={{ display: 'flex', alignItems: 'center', zIndex: 2 }}>{trailing}</div>}
        </div>
      </div>
    );
  }
  return (
    <div style={{ position: 'absolute', top: 54, left: 0, right: 0, zIndex: 8, padding: '8px 20px 8px' }}>
      <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', minHeight: 42 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 32, fontWeight: 700, color: c.textPri, letterSpacing: -0.5, lineHeight: 1.15 }}>{title}{badge}</span>
        {subtitle && <span style={{ position: 'absolute', left: 0, right: 0, textAlign: 'center', fontSize: 13, lineHeight: 1.15, color: c.textSec, pointerEvents: 'none' }}>{subtitle}</span>}
        {trailing && <div style={{ display: 'flex', alignItems: 'center', zIndex: 2 }}>{trailing}</div>}
      </div>
    </div>
  );
}

// ── Records Data (synchronized with RCRecordRowV3_claudecode_20260904: 个数 + 用时在第一行，MM-dd HH:mm · N个/分 在第二行，右侧模式胶囊 定时/定数/自由) ── // 2026.11.04 Naron
const REC_GROUPS = [
  { label: '本周', rows: [
    { id: 'r1', date: '11-04 16:20', count: 247, durText: '1分 0秒', cad: 142, modeLabel: '定时', hasVideo: true, score: 17 },
    { id: 'r2', date: '11-02 07:45', count: 224, durText: '1分 0秒', cad: 138, modeLabel: '定时', hasVideo: true, score: 15 },
    { id: 'r3', date: '11-01 18:02', count: 312, durText: '2分 34秒', cad: 121, modeLabel: '自由', hasVideo: false, score: 16 },
  ]},
  { label: '上周', rows: [
    { id: 'r4', date: '10-27 10:10', count: 201, durText: '1分 25秒', cad: 132, modeLabel: '定数', hasVideo: false, score: 13 },
    { id: 'r5', date: '10-25 17:30', count: 188, durText: '1分 0秒', cad: 128, modeLabel: '定时', hasVideo: false, score: 12 },
  ]},
];

function RecordRowV3({ c, font, dark, r, last, onOpen }) {
  return (
    <div onClick={() => onOpen && onOpen(r)} style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', cursor: 'pointer',
      borderBottom: last ? 'none' : `1px solid ${c.border}`
    }}>
      <div style={{
        width: 38, height: 38, borderRadius: 11, background: rgba(c.accent, dark ? 0.18 : 0.10),
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
      }}>
        <SkipIcon size={20} color={c.accent}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
          <span style={{ fontFamily: font.mono, fontSize: 17, fontWeight: 700, color: c.textPri, fontVariantNumeric: 'tabular-nums' }}>{r.count}</span>
          <span style={{ fontSize: 12, color: c.textTer }}>个</span>
          <span style={{ fontSize: 12.5, color: c.textSec }}>· {r.durText}</span>
        </div>
        <div style={{ fontSize: 12.5, color: c.textSec, marginTop: 2 }}>{r.date} · {r.cad}个/分</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
        {r.hasVideo && (
          <span style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            width: 24, height: 24, borderRadius: 999, background: rgba(c.accent, dark ? 0.2 : 0.12), color: c.accent
          }} title="可回看录像">
            <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><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>
          </span>
        )}
        <span style={{ fontSize: 12, color: c.textTer, padding: '3px 8px', borderRadius: 999, background: c.surfaceMuted }}>{r.modeLabel}</span>
      </div>
      <IcChevRight size={14} color={c.textTer}/>
    </div>
  );
}

function RecordsListScreen({ platform = 'ios', dark = false, tab = 'history', onTab, onOpen, empty = false }) {
  const c = dark ? RC.dark : RC.light;
  const font = platform === 'android' ? FONTS.android : FONTS.ios;

  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="全部记录"/>
      <div style={{ position: 'absolute', top: platform === 'android' ? 110 : 112, left: 0, right: 0, bottom: platform === 'android' ? 84 : 90,
        overflow: 'auto', padding: '4px 16px 16px' }}>
        {REC_GROUPS.map(g => (
          <div key={g.label} style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: c.textSec, padding: '6px 4px 8px' }}>{g.label}</div>
            <div style={{ background: c.surface, borderRadius: 16, overflow: 'hidden',
              border: dark ? `1px solid ${c.border}` : 'none', boxShadow: dark ? 'none' : ELEV[1] }}>
              {g.rows.map((r, i) => (
                <RecordRowV3 key={r.id} c={c} font={font} dark={dark} r={r} last={i === g.rows.length - 1} onOpen={onOpen}/>
              ))}
            </div>
          </div>
        ))}
      </div>
    </PhoneFrame>
  );
}

// ── Dual-View 7-Day Chart Card (RCWeekBarChartV3_claudecode_20260906: Bar chart <-> Dot scatter chart + 4pt sliding underline + 38pt Y-axis) ── // 2026.11.04 Naron
function TrendsDualChartCard({ c, font, dark, initialMetric = 'count' }) {
  const [metric, setMetric] = useStateD(initialMetric); // 'count' | 'speed'
  const [selectedSlot, setSelectedSlot] = useStateD(null);
  const isDot = metric === 'speed';

  const labels = ['10-29', '10-30', '10-31', '11-01', '11-02', '11-03', '今天'];
  const countValues = [188, 0, 201, 312, 224, 0, 247];
  const speedValues = [132, 0, 138, 121, 146, 0, 158];
  const values = isDot ? speedValues : countValues;

  const axisMax = isDot ? 200 : 400;
  const ticks = isDot ? [200, 150, 100, 50, 0] : [400, 300, 200, 100, 0];
  const fractions = [0, 0.25, 0.5, 0.75, 1.0];

  const totalW = SCREEN_W - 32 - 32; // 329
  const plotLeft = 38;
  const plotW = totalW - plotLeft;
  const plotTop = 24;
  const plotBottom = 150;
  const plotH = plotBottom - plotTop; // 126
  const labelH = 22;
  const slotW = plotW / values.length;

  const switchTab = (k) => {
    setMetric(k);
    setSelectedSlot(null);
  };

  return (
    <div style={{
      background: c.surface, borderRadius: 16, padding: 16,
      border: dark ? `1px solid ${c.border}` : 'none', boxShadow: dark ? 'none' : ELEV[2]
    }}>
      {/* Dual tab header with 4pt accent underline */}
      <div style={{ position: 'relative', display: 'flex', gap: 8, marginBottom: 8 }}>
        {[
          { key: 'count', title: '近7天跳绳个数' },
          { key: 'speed', title: '近7天最快速度(个/分)' },
        ].map((t) => {
          const on = metric === t.key;
          return (
            <button key={t.key} onClick={() => switchTab(t.key)} style={{
              flex: 1, minHeight: 44, border: 'none', background: 'transparent', cursor: 'pointer', padding: '0 2px',
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', position: 'relative'
            }}>
              <span style={{
                fontFamily: font.sans, fontSize: 15, fontWeight: on ? 700 : 400,
                color: on ? c.textPri : c.textSec, whiteSpace: 'nowrap', position: 'relative', paddingBottom: 6
              }}>
                {t.title}
                {on && (
                  <span style={{
                    position: 'absolute', left: 0, right: 0, bottom: 0, height: 4, borderRadius: 2,
                    background: c.accent, transition: 'all 180ms ease-in-out'
                  }}/>
                )}
              </span>
            </button>
          );
        })}
      </div>

      {/* Plot area: 38pt Y-axis + 5 dashed grid lines + 7 slots */}
      <div style={{ position: 'relative', width: totalW, height: plotBottom + labelH, userSelect: 'none' }}>
        <svg width={totalW} height={plotBottom + labelH} viewBox={`0 0 ${totalW} ${plotBottom + labelH}`} style={{ display: 'block', overflow: 'visible' }}>
          {/* 5 dashed grid lines + Y-axis labels */}
          {fractions.map((frac, idx) => {
            const y = plotTop + frac * plotH;
            return (
              <g key={idx}>
                <line x1={plotLeft} y1={y} x2={plotLeft + plotW} y2={y} stroke={c.border} strokeWidth="1" strokeDasharray="3 3"/>
                <text x={plotLeft - 6} y={y + 3.5} textAnchor="end" fill={c.textTer} fontSize="10" fontFamily={font.mono}>{ticks[idx]}</text>
              </g>
            );
          })}

          {/* 7 date slots */}
          {values.map((v, i) => {
            const cx = plotLeft + (i + 0.5) * slotW;
            const ratio = Math.min(1, Math.max(0, v / axisMax));
            const markW = isDot ? (v > 0 ? 8 : 6) : 18;
            const markH = isDot ? (v > 0 ? 8 : 3) : (v > 0 ? Math.max(4, ratio * plotH) : 3);
            const cy = isDot
              ? (v > 0 ? Math.min(plotBottom - markH / 2, Math.max(plotTop + markH / 2, plotBottom - ratio * plotH)) : plotBottom - markH / 2)
              : (plotBottom - markH / 2);
            const topY = cy - markH / 2;
            const isSelected = selectedSlot === i;
            const markOpacity = v > 0 ? (selectedSlot === null || isSelected ? 1 : 0.45) : 1;
            const showReadout = v > 0 && (selectedSlot === null || isSelected);
            const readoutText = isSelected ? `${v} ${isDot ? '个/分' : '个'}` : String(v);
            const readoutY = Math.max(10, topY - 5);

            return (
              <g key={i} onClick={() => setSelectedSlot(selectedSlot === i ? null : i)} style={{ cursor: 'pointer' }}>
                <rect x={plotLeft + i * slotW} y={0} width={slotW} height={plotBottom + labelH} fill="transparent"/>
                {isDot ? (
                  <rect
                    x={cx - markW / 2} y={cy - markH / 2} width={markW} height={markH} rx={4}
                    fill={v > 0 ? c.accent : rgba(c.accent, dark ? 0.4 : 0.28)}
                    stroke={v > 0 ? c.surface : 'none'} strokeWidth={v > 0 ? 2 : 0}
                    opacity={markOpacity}
                  />
                ) : (
                  <path
                    d={`M${cx - markW / 2},${topY + 4} a4,4 0 0 1 4,-4 h${markW - 8} a4,4 0 0 1 4,4 v${Math.max(0, markH - 4)} h-${markW} Z`}
                    fill={v > 0 ? c.accent : rgba(c.accent, dark ? 0.4 : 0.28)}
                    opacity={markOpacity}
                  />
                )}
                {showReadout && (
                  <text
                    x={Math.min(plotLeft + plotW - 14, Math.max(plotLeft + 14, cx))}
                    y={readoutY}
                    textAnchor="middle"
                    fill={isSelected ? c.textPri : c.textSec}
                    fontSize="11"
                    fontWeight={isSelected ? '700' : '600'}
                    fontFamily={font.mono}
                  >{readoutText}</text>
                )}
                <text
                  x={cx} y={plotBottom + 15} textAnchor="middle"
                  fill={isSelected ? c.textPri : c.textTer}
                  fontWeight={isSelected ? '600' : '400'}
                  fontSize="11" fontFamily={font.sans}
                >{labels[i]}</text>
              </g>
            );
          })}
        </svg>
      </div>
    </div>
  );
}

function LineChart({ c, font, dark, data }) {
  const W = SCREEN_W - 32 - 32, H = 130, max = 20, pad = 6;
  const stepX = (W - pad * 2) / (data.length - 1);
  const pts = data.map((v, i) => [pad + i * stepX, H - pad - (v / max) * (H - pad * 2)]);
  const path = pts.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ');
  const area = `${path} L${pts[pts.length - 1][0]},${H} L${pts[0][0]},${H} Z`;
  return (
    <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }}>
      <defs><linearGradient id="lcfill" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stopColor={c.accent} stopOpacity="0.22"/><stop offset="100%" stopColor={c.accent} stopOpacity="0"/>
      </linearGradient></defs>
      {[5, 10, 15, 20].map(g => { const y = H - pad - (g / max) * (H - pad * 2);
        return <line key={g} x1={pad} y1={y} x2={W - pad} y2={y} stroke={c.border} strokeWidth="1" strokeDasharray="3 4"/>; })}
      <path d={area} fill="url(#lcfill)"/>
      <path d={path} fill="none" stroke={c.accent} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round"/>
      {pts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r={i === pts.length - 1 ? 3.5 : 2.4} fill={c.accent}/>)}
    </svg>
  );
}

// 3 equal-width metric cards (X147-A6/A8/A10: 近7天总计 1486 个 | 总计时长 10 分 25 秒 | 平均速度 142 个/分) // 2026.11.04 Naron
function MetricCard({ c, font, dark, label, value, unit, durationParts }) {
  return (
    <div style={{ flex: 1, minWidth: 0, background: c.surface, borderRadius: 16, padding: '14px 12px',
      border: dark ? `1px solid ${c.border}` : 'none', boxShadow: dark ? 'none' : ELEV[1] }}>
      <div style={{ fontSize: 12, color: c.textSec }}>{label}</div>
      <div style={{ marginTop: 6, display: 'flex', alignItems: 'baseline', gap: 2, whiteSpace: 'nowrap' }}>
        {durationParts ? (
          <>
            <span style={{ fontFamily: font.mono, fontSize: 20, fontWeight: 700, color: c.textPri, fontVariantNumeric: 'tabular-nums' }}>{durationParts[0]}</span>
            <span style={{ fontSize: 11.5, color: c.textTer }}> 分 </span>
            <span style={{ fontFamily: font.mono, fontSize: 20, fontWeight: 700, color: c.textPri, fontVariantNumeric: 'tabular-nums' }}>{durationParts[1]}</span>
            <span style={{ fontSize: 11.5, color: c.textTer }}> 秒</span>
          </>
        ) : (
          <>
            <span style={{ fontFamily: font.mono, fontSize: 20, fontWeight: 700, color: c.textPri, fontVariantNumeric: 'tabular-nums' }}>{value}</span>
            <span style={{ fontSize: 11.5, color: c.textTer }}>{unit}</span>
          </>
        )}
      </div>
    </div>
  );
}

// ── Recent records (history merged into 练) ──
function RecentRecords({ c, font, dark, onOpen }) {
  return (
    <div>
      {REC_GROUPS.map(g => (
        <div key={g.label} style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: c.textSec, padding: '2px 4px 8px' }}>{g.label}</div>
          <div style={{ background: c.surface, borderRadius: 16, overflow: 'hidden', border: dark ? `1px solid ${c.border}` : 'none', boxShadow: dark ? 'none' : ELEV[1] }}>
            {g.rows.map((r, i) => (
              <RecordRowV3 key={r.id} c={c} font={font} dark={dark} r={r} last={i === g.rows.length - 1} onOpen={onOpen}/>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Screen D: Trends (Tab 2「练」) ──
function TrendsScreen({ platform = 'ios', dark = false, tab = 'trends', onTab, onOpen, pro, onPro, initialMetric = 'count' }) {
  const c = dark ? RC.dark : RC.light;
  const font = platform === 'android' ? FONTS.android : FONTS.ios;
  const scores = [11, 12, 12, 13, 13, 14, 15, 15, 16, 17];

  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="练习痕迹 + 统计分析"/>
      <div style={{ position: 'absolute', top: platform === 'android' ? 110 : 112, left: 0, right: 0, bottom: platform === 'android' ? 84 : 90,
        overflow: 'auto', padding: '10px 16px 16px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <TrendsDualChartCard c={c} font={font} dark={dark} initialMetric={initialMetric}/>

        <div style={{ display: 'flex', gap: 10 }}>
          <MetricCard c={c} font={font} dark={dark} label="近7天总计" value="1172" unit="个"/>
          <MetricCard c={c} font={font} dark={dark} label="总计时长" durationParts={[8, 20]}/>
          <MetricCard c={c} font={font} dark={dark} label="平均速度" value="141" unit="个/分"/>
        </div>

        <div style={{ background: c.surface, borderRadius: 16, padding: 16, border: dark ? `1px solid ${c.border}` : 'none', boxShadow: dark ? 'none' : ELEV[2] }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
            <span style={{ fontSize: 15, fontWeight: 600, color: c.textPri }}>评分趋势</span>
            <span style={{ fontFamily: font.mono, fontSize: 13, fontWeight: 600, color: c.examMid }}>近 10 次 · 满分 20</span>
          </div>
          <LineChart c={c} font={font} dark={dark} data={scores}/>
          <div style={{ marginTop: 8, fontSize: 13, color: c.textSec }}>稳步上升 · 从 11 分到 17 分，继续保持</div>
        </div>
        <RecentRecords c={c} font={font} dark={dark} onOpen={onOpen}/>
      </div>
    </PhoneFrame>
  );
}

Object.assign(window, { ProBadge, RecordsListScreen, TrendsScreen, TrendsDualChartCard, TabHeader, REC_GROUPS });
