/* global React, RC, FONTS, rgba, MODES, IcGradCap, IcPause, IcX, CameraFeed, Skipping, PhoneFrame, SCREEN_W, SCREEN_H */
// ─────────────────────────────────────────────────────────────
// RopeCounter V3 — 跳绳中 (LiveScreen) · state machine
//   wait      选完模式进入：小人轮廓 + 「全身进框」提示，翻转 / 退出
//   detected  识别到人体：框角变绿，提示变为「已识别」，随即进入倒计时
//   countdown 3 · 2 · 1（未识别到人体则一直停在 wait，不倒计时）
//   active    开始计数：左上时间 · 右上次数 · 底部 暂停 / 结束
//   paused    暂停遮罩：继续 / 结束
// ─────────────────────────────────────────────────────────────
const { useState: useStateL, useEffect: useEffectL } = React;

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

// standing-person pictogram (head + body, arms at sides, legs) — full-body framing guide
const Person = ({ width = 200, height = 400, color = '#fff', opacity = 0.92 }) => (
  <svg width={width} height={height} viewBox="0 0 100 200" fill={color} opacity={opacity} aria-hidden="true" style={{ display: 'block' }}>
    <circle cx="50" cy="22" r="18"/>
    <path d="M36 46h28c8 0 14 6 15 14l6 52c.5 4-2.5 7-6 7s-6-3-6.5-7l-4-38v46H31V74l-4 38c-.5 4-3 7-6.5 7s-6.5-3-6-7l6-52c1-8 7-14 15-14z"/>
    <path d="M31 122h16v66c0 5-3.5 9-8 9s-8-4-8-9zM53 122h16v66c0 5-3.5 9-8 9s-8-4-8-9z"/>
  </svg>
);
const IcPower = ({ size = 22, color = '#fff' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.2" strokeLinecap="round" aria-hidden="true"><path d="M12 3v9"/><path d="M7 6.3a7.5 7.5 0 1 0 10 0"/></svg>
);

const glassL = { whiteSpace: 'nowrap', background: 'rgba(0,0,0,0.42)', backdropFilter: 'blur(18px) saturate(180%)', WebkitBackdropFilter: 'blur(18px) saturate(180%)', border: '0.5px solid rgba(255,255,255,0.18)', color: 'rgba(255,255,255,0.95)' };
const ACCENT_L = '#34D399', RED_L = '#FF453A';

const IcFlip = ({ size = 22, color = '#fff' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M4 8.5h2.2l1.6-2.5h8.4l1.6 2.5H20v10H4z"/><circle cx="12" cy="13.2" r="3.2"/><path d="M16.6 3.2 18.4 5l-1.8 1.8" opacity="0"/>
  </svg>
);
const IcPlay = ({ size = 20, color = '#fff' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={color} aria-hidden="true"><path d="M7 4.8v14.4c0 .9 1 1.4 1.7.9l10.6-7.2c.6-.4.6-1.3 0-1.7L8.7 3.9C8 3.4 7 3.9 7 4.8z"/></svg>
);

// bare control: icon + label, no backing disc (bottom-left / bottom-right)
function Ctl({ icon, label, onClick, danger = false }) {
  const col = danger ? '#FF6B61' : '#fff';
  return (
    <button onClick={onClick} aria-label={label} style={{ background: 'none', border: 'none', padding: '10px 6px', minWidth: 44, minHeight: 44, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 8, color: col, fontFamily: 'inherit', filter: 'drop-shadow(0 1px 3px rgba(0,0,0,0.6))' }}>
      {icon}<span style={{ fontSize: 15, fontWeight: 600 }}>{label}</span>
    </button>
  );
}
// dark rounded readout — time (left) / count (right), bold white digits, no caption
function Readout({ children, font, color = '#fff' }) {
  return <div style={{ background: 'rgba(30,30,34,0.86)', borderRadius: 18, padding: '6px 22px', minWidth: 116, textAlign: 'center', fontFamily: font.rounded, fontSize: 60, fontWeight: 700, lineHeight: 1.2, letterSpacing: -1.5, color, fontVariantNumeric: 'tabular-nums', boxShadow: '0 2px 8px rgba(0,0,0,0.35)' }}>{children}</div>;
}

function Corners({ color, top, bottom, inset = 40 }) {
  const c = (pos, r) => <span style={{ position: 'absolute', width: 30, height: 30, opacity: 0.95, transition: 'border-color 240ms', ...pos, borderRadius: r }}/>;
  const b = `3px solid ${color}`;
  return (<>
    {c({ left: inset, top, borderLeft: b, borderTop: b }, '8px 0 0 0')}
    {c({ right: inset, top, borderRight: b, borderTop: b }, '0 8px 0 0')}
    {c({ left: inset, bottom, borderLeft: b, borderBottom: b }, '0 0 0 8px')}
    {c({ right: inset, bottom, borderRight: b, borderBottom: b }, '0 0 8px 0')}
  </>);
}

function LiveScreen({ platform = 'ios', dark = false, mode = 'goalTime', live = true, phase: phaseProp = 'active', countdownN = 3, durationMin = 1, targetCount = 200, onStop, onExit }) {
  const font = platform === 'android' ? FONTS.android : FONTS.ios;
  const isExam = mode === 'exam', timed = isExam || mode === 'goalTime', counted = mode === 'goalCount';
  const totalSec = isExam ? 60 : timed ? Math.round(durationMin * 60) : 0;
  const cadence = 142;

  const [phase, setPhase] = useStateL(live ? 'wait' : phaseProp);
  const [cd, setCd] = useStateL(live ? 3 : countdownN);
  const [count, setCount] = useStateL(live ? 0 : 127);
  const [elapsed, setElapsed] = useStateL(live ? 0 : (timed ? Math.min(28, Math.max(0, totalSec - 20)) : 154));
  const [pulse, setPulse] = useStateL(false);
  const [cam, setCam] = useStateL('front');

  // wait → detected (simulated body detection) → countdown 3·2·1 → active
  useEffectL(() => {
    if (!live) return;
    if (phase === 'wait') { const t = setTimeout(() => setPhase('detected'), 2600); return () => clearTimeout(t); }
    if (phase === 'detected') { const t = setTimeout(() => { setCd(3); setPhase('countdown'); }, 700); return () => clearTimeout(t); }
    if (phase === 'countdown') { const t = setTimeout(() => { if (cd <= 1) setPhase('active'); else setCd(n => n - 1); }, 1000); return () => clearTimeout(t); }
    if (phase === 'active') {
      const tick = setInterval(() => { setCount(n => n + 1); setPulse(true); setTimeout(() => setPulse(false), 140); }, 60000 / cadence);
      const sec = setInterval(() => setElapsed(e => e + 1), 1000);
      return () => { clearInterval(tick); clearInterval(sec); };
    }
  }, [live, phase, cd]);

  const remaining = timed ? Math.max(0, totalSec - elapsed) : 0;
  const done = (timed && remaining <= 0) || (counted && count >= targetCount);
  useEffectL(() => { if (live && phase === 'active' && done) { const t = setTimeout(() => onStop && onStop(), 400); return () => clearTimeout(t); } }, [live, phase, done, onStop]);

  const progress = timed ? 1 - remaining / totalSec : counted ? Math.min(1, count / targetCount) : 0;
  const modeLabel = MODES.find(m => m.key === mode)?.label || '自由模式';
  const preStart = phase === 'wait' || phase === 'detected' || phase === 'countdown';
  const detected = phase !== 'wait';
  const frameColor = detected ? ACCENT_L : 'rgba(255,255,255,0.85)';

  return (
    <PhoneFrame platform={platform} dark={dark} statusDark={false}>
      <CameraFeed dark radius={0}/>
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg,rgba(0,0,0,0.55) 0%,rgba(0,0,0,0) 26%,rgba(0,0,0,0) 62%,rgba(0,0,0,0.6) 100%)', pointerEvents: 'none' }}/>

      {/* person pictogram — solid guide while waiting, faint once counting */}
      <div style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-50%)', transition: 'opacity 300ms', pointerEvents: 'none' }}>
        <Person width={230} height={460} opacity={preStart ? 0.92 : 0.28}/>
      </div>
      <Corners color={frameColor} top={150} bottom={150} inset={28}/>

      {/* top row: mode pill (pre-start) · time (left) + count (right) once counting */}
      <div style={{ position: 'absolute', top: 62, left: 16, right: 16, zIndex: 5, fontFamily: font.sans, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        {preStart
          ? <div style={{ ...glassL, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 12px', borderRadius: 999, fontSize: 13.5, fontWeight: 600 }}>{isExam && <IcGradCap size={12} color="#fff"/>}{modeLabel}{timed && ` · ${fmtL(totalSec)}`}{counted && ` · ${targetCount} 次`}</div>
          : <>
              <Readout font={font} color={timed && remaining <= 10 ? '#FF6B61' : '#fff'}>{fmtL(timed ? remaining : elapsed)}</Readout>
              <div style={{ transform: pulse ? 'scale(1.05)' : 'scale(1)', transformOrigin: 'right center', transition: 'transform 140ms cubic-bezier(.2,.7,.3,1)' }}><Readout font={font}>{count}</Readout></div>
            </>}
      </div>

      {/* center hint (wait / detected) or countdown digit */}
      {preStart && (
        <div style={{ position: 'absolute', left: 0, right: 0, top: '50%', transform: 'translateY(-50%)', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, zIndex: 6, fontFamily: font.sans, pointerEvents: 'none' }}>
          {phase === 'countdown'
            ? <div key={cd} className="rc-cd" style={{ width: 132, height: 132, borderRadius: 999, background: 'rgba(0,0,0,0.5)', border: `4px solid ${ACCENT_L}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: font.rounded, fontSize: 84, fontWeight: 700, color: '#fff', lineHeight: 1, boxShadow: `0 0 0 10px ${rgba(ACCENT_L, 0.18)}` }}>{cd}</div>
            : <>
                <div style={{ ...glassL, background: detected ? rgba(ACCENT_L, 0.22) : 'rgba(0,0,0,0.5)', border: `1px solid ${detected ? rgba(ACCENT_L, 0.7) : 'rgba(255,255,255,0.22)'}`, padding: '12px 22px', borderRadius: 18, fontSize: 20, fontWeight: 700, letterSpacing: 0.5, transition: 'all 240ms' }}>
                  {detected ? '已识别，准备开始' : '请让全身进入框内'}
                </div>
                <div style={{ fontSize: 13, fontWeight: 500, color: 'rgba(255,255,255,0.75)', textShadow: '0 1px 3px rgba(0,0,0,0.6)' }}>{detected ? '倒计时后自动开始计数' : '识别到人后自动开始，无需点击'}</div>
              </>}
        </div>
      )}

      {/* paused overlay */}
      {phase === 'paused' && (
        <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.42)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 4, fontFamily: font.sans }}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
            <span style={{ ...glassL, width: 72, height: 72, borderRadius: 999, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><IcPause size={30} color="#fff"/></span>
            <div style={{ fontSize: 22, fontWeight: 700, color: '#fff' }}>已暂停</div>
            <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)' }}>计时与计数已停止</div>
          </div>
        </div>
      )}

      {/* bottom controls */}
      <div style={{ position: 'absolute', left: 12, right: 12, bottom: 30, zIndex: 5, fontFamily: font.sans }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          {preStart
            ? <><Ctl icon={<IcFlip size={22}/>} label={cam === 'front' ? '翻转 · 前置' : '翻转 · 后置'} onClick={() => setCam(k => k === 'front' ? 'back' : 'front')}/>
               <Ctl icon={<IcPower size={20}/>} label="退出" onClick={onExit}/></>
            : <>{phase === 'paused'
                ? <Ctl icon={<IcPlay size={20}/>} label="继续" onClick={() => setPhase('active')}/>
                : <Ctl icon={<IcPause size={22} color="#fff"/>} label="暂停" onClick={() => setPhase('paused')}/>}
               <Ctl danger icon={<IcPower size={20} color="#FF6B61"/>} label="结束" onClick={onStop}/></>}
        </div>
      </div>
    </PhoneFrame>
  );
}

Object.assign(window, { LiveScreen });
