// Contraction timer — start/stop, duration, interval, pattern guidance.

function ContractionsPage() {
  const load = (k, d) => { try { return JSON.parse(localStorage.getItem(k) || d); } catch(e) { return JSON.parse(d); } };

  const [contractions, setContractions] = React.useState(() => load('cx_log', '[]'));
  const [active, setActive] = React.useState(false);
  const [cxStart, setCxStart] = React.useState(null);
  const [elapsed, setElapsed] = React.useState(0);
  const [nowTs, setNowTs] = React.useState(() => Date.now());

  React.useEffect(() => {
    localStorage.setItem('cx_log', JSON.stringify(contractions));
  }, [contractions]);

  // Tick every second to keep "since last contraction" display live.
  // Using Date.now()-based calculation means screen-sleep never drifts the result.
  React.useEffect(() => {
    const tick = () => setNowTs(Date.now());
    const id = setInterval(tick, 1000);
    const onVisible = () => { if (!document.hidden) tick(); };
    document.addEventListener('visibilitychange', onVisible);
    return () => { clearInterval(id); document.removeEventListener('visibilitychange', onVisible); };
  }, []);

  React.useEffect(() => {
    if (!active) return;
    const id = setInterval(() => setElapsed(Math.floor((Date.now() - cxStart) / 1000)), 200);
    return () => clearInterval(id);
  }, [active, cxStart]);

  const startCx = () => {
    const now = Date.now();
    setCxStart(now);
    setActive(true);
    setElapsed(0);
  };

  const stopCx = () => {
    if (!cxStart) return;
    const dur = Math.floor((Date.now() - cxStart) / 1000);
    const last = contractions[contractions.length - 1];
    const interval = last ? Math.floor((cxStart - last.start) / 1000) : null;
    const next = [...contractions, { start: cxStart, end: Date.now(), duration: dur, interval }];
    setContractions(next);
    setActive(false);
    setCxStart(null);
    setElapsed(0);
  };

  const clearAll = () => {
    if (!confirm('確定清除所有記錄？')) return;
    setContractions([]);
    setActive(false);
    setCxStart(null);
    setElapsed(0);
  };

  const fmtSec = (s) => {
    if (s == null) return '—';
    const m = Math.floor(s / 60);
    const sec = s % 60;
    return m > 0 ? `${m}m ${sec}s` : `${sec}s`;
  };
  const fmtTime = (ts) => {
    const d = new Date(ts);
    return `${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}`;
  };

  // Pattern analysis — use last 3 contractions
  const recent = contractions.slice(-6);
  const avgDur = recent.length > 0
    ? Math.round(recent.reduce((s, c) => s + c.duration, 0) / recent.length)
    : null;
  const intervals = recent.filter(c => c.interval != null).map(c => c.interval);
  const avgInt = intervals.length > 0
    ? Math.round(intervals.reduce((s,v) => s+v, 0) / intervals.length)
    : null;

  // 5-1-1 rule: 5 min apart, 1 min duration, 1 hour
  const rule511 = avgInt != null && avgDur != null && avgInt <= 300 && avgDur >= 60;
  const rule711 = avgInt != null && avgDur != null && avgInt <= 420 && avgDur >= 45;

  const advice = rule511
    ? { zh:'⚠ 符合 5-1-1 法則，建議前往醫院', en:'5-1-1 rule met — head to hospital', color:'var(--rose)', bg:'var(--rose-soft)' }
    : rule711
    ? { zh:'宮縮頻率增加，密切觀察', en:'Contractions intensifying — monitor closely', color:'var(--butter)', bg:'color-mix(in oklab,var(--butter) 20%,white)' }
    : contractions.length > 0
    ? { zh:'持續記錄，尚未達到就醫標準', en:'Keep timing — not yet at hospital threshold', color:'var(--sage)', bg:'var(--sage-soft)' }
    : null;

  return (
    <div style={{ padding:'16px 16px 100px', display:'flex', flexDirection:'column', gap:16 }}>
      <SectionTitle zh="宮縮計時" en="Contraction Timer" />

      {/* Advice banner */}
      {advice && (
        <div style={{
          padding:'12px 16px', borderRadius:10,
          background: advice.bg, border:`1px solid color-mix(in oklab,${advice.color} 25%,var(--line))`,
        }}>
          <div style={{ fontSize:13, fontWeight:600, color: advice.color }}>{advice.zh}</div>
          <div className="en" style={{ fontSize:10.5, color:'var(--ink-soft)', marginTop:2 }}>{advice.en}</div>
        </div>
      )}

      {/* Stats row */}
      <div style={{ display:'flex', gap:10 }}>
        <StatChip label="宮縮次數" value={contractions.length} unit="次 total" />
        <StatChip label="平均時長" value={avgDur != null ? fmtSec(avgDur) : '—'} unit="duration" color="var(--accent)" />
        <StatChip label="平均間隔" value={avgInt != null ? fmtSec(avgInt) : '—'} unit="interval" color="var(--ink)" />
      </div>

      {/* Big button */}
      <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:16, padding:'8px 0' }}>
        {active ? (
          <>
            <div style={{ textAlign:'center', marginBottom:4 }}>
              <div className="mono" style={{ fontSize:42, fontWeight:500, color:'var(--rose)', letterSpacing:'0.04em', lineHeight:1 }}>
                {fmtSec(elapsed)}
              </div>
              <div style={{ fontSize:11, color:'var(--ink-faint)', marginTop:4 }}>宮縮中 · contraction in progress</div>
            </div>
            <BigButton onClick={stopCx} label="停止" sublabel="Stop" color="var(--rose)" pulse />
          </>
        ) : (
          <>
            {contractions.length > 0 && contractions[contractions.length-1]?.interval == null && (
              <div className="mono" style={{ fontSize:13, color:'var(--ink-faint)', textAlign:'center' }}>
                上次：{fmtSec(contractions[contractions.length-1]?.duration)} 時長
              </div>
            )}
            {contractions.length > 0 && (() => {
              const last = contractions[contractions.length-1];
              const secSince = Math.floor((nowTs - last.end) / 1000);
              return (
                <div style={{ textAlign:'center', marginBottom:4 }}>
                  <div className="mono" style={{ fontSize:22, color:'var(--ink-soft)', fontWeight:500 }}>
                    間隔 {fmtSec(secSince)}
                  </div>
                  <div style={{ fontSize:10.5, color:'var(--ink-faint)' }}>since last contraction</div>
                </div>
              );
            })()}
            <BigButton onClick={startCx} label="開始" sublabel="Start" color="var(--accent)" />
          </>
        )}
      </div>

      {/* 5-1-1 guide */}
      <Card pad="14px">
        <div style={{ fontSize:10.5, color:'var(--ink-faint)', letterSpacing:'0.06em', marginBottom:10 }}>
          就醫指引 · WHEN TO GO
        </div>
        {[
          { rule:'5-1-1 法則', zh:'每 5 分鐘一次、每次 1 分鐘、持續 1 小時 → 前往醫院', color:'var(--rose)' },
          { rule:'7-1-1 法則', zh:'初產婦可稍晚，每 7 分鐘一次、每次 1 分鐘持續觀察', color:'var(--butter)' },
          { rule:'緊急情況', zh:'破水、大量出血、胎動消失 → 立即就醫', color:'var(--rose)' },
        ].map(g => (
          <div key={g.rule} style={{ display:'flex', gap:10, marginBottom:10, alignItems:'flex-start' }}>
            <div style={{
              minWidth:48, padding:'3px 0', textAlign:'center',
              background:`color-mix(in oklab,${g.color} 15%,white)`,
              borderRadius:6, fontSize:9.5, fontWeight:600, color:g.color,
              fontFamily:"'JetBrains Mono',monospace",
            }}>{g.rule}</div>
            <div style={{ fontSize:11.5, color:'var(--ink)', lineHeight:1.5 }}>{g.zh}</div>
          </div>
        ))}
      </Card>

      {/* History */}
      {contractions.length > 0 && (
        <Card pad="14px">
          <div style={{
            display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10,
          }}>
            <div style={{ fontSize:10.5, color:'var(--ink-faint)', letterSpacing:'0.06em' }}>
              記錄 · LOG ({contractions.length})
            </div>
            <button className="btn-reset" onClick={clearAll} style={{
              fontSize:10.5, color:'var(--rose)', borderBottom:'1px dashed var(--rose)',
            }}>清除</button>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:1 }}>
            {[...contractions].reverse().slice(0,12).map((c, i) => (
              <div key={c.start} style={{
                display:'grid', gridTemplateColumns:'60px 80px 80px',
                padding:'8px 0', borderBottom:'1px solid var(--line-soft)',
                fontFamily:"'JetBrains Mono',monospace", fontSize:11.5,
              }}>
                <span style={{ color:'var(--ink-soft)' }}>{fmtTime(c.start)}</span>
                <span style={{ color:'var(--ink)', fontWeight:500 }}>{fmtSec(c.duration)}</span>
                <span style={{ color: c.interval && c.interval<=300 ? 'var(--rose)' : 'var(--ink-soft)' }}>
                  {c.interval != null ? `↔ ${fmtSec(c.interval)}` : '—'}
                </span>
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}

Object.assign(window, { ContractionsPage });
