/* global React, Icon, IconBtn, db */
const { useState, useEffect, useRef, useCallback, useMemo } = React;

// ============================================================
// Breathing exercise — guided animated breath patterns.
// A big circle that smoothly scales with each phase of the pattern.
// No scoring, no streaks — calm tool.
// ============================================================

const BREATH_PATTERNS = [
  {
    id: 'box',
    name: 'Box breathing',
    tagline: 'Equal in, hold, out, hold. Used by navy SEALs to stay calm under stress.',
    phases: [
      { kind: 'in',   label: 'Breathe in',  seconds: 4 },
      { kind: 'hold', label: 'Hold',        seconds: 4 },
      { kind: 'out',  label: 'Breathe out', seconds: 4 },
      { kind: 'hold', label: 'Hold',        seconds: 4 },
    ],
  },
  {
    id: '478',
    name: '4 · 7 · 8',
    tagline: 'Dr. Andrew Weil\'s "natural tranquilizer." Slows you down for sleep.',
    phases: [
      { kind: 'in',   label: 'Breathe in',  seconds: 4 },
      { kind: 'hold', label: 'Hold',        seconds: 7 },
      { kind: 'out',  label: 'Breathe out', seconds: 8 },
    ],
  },
  {
    id: 'deep',
    name: 'Deep relaxation',
    tagline: 'Long, slow cycles. For when the day has been a lot.',
    phases: [
      { kind: 'in',   label: 'Breathe in',  seconds: 6 },
      { kind: 'hold', label: 'Hold gently', seconds: 2 },
      { kind: 'out',  label: 'Breathe out', seconds: 8 },
    ],
  },
  {
    id: 'energize',
    name: 'Focus & energize',
    tagline: 'Quick, even rhythm to sharpen attention before deep work.',
    phases: [
      { kind: 'in',   label: 'Breathe in',  seconds: 3 },
      { kind: 'out',  label: 'Breathe out', seconds: 3 },
    ],
  },
  {
    id: 'coherent',
    name: 'Coherent breathing',
    tagline: '5-second in, 5-second out — a balanced rhythm linked to HRV stability.',
    phases: [
      { kind: 'in',   label: 'Breathe in',  seconds: 5 },
      { kind: 'out',  label: 'Breathe out', seconds: 5 },
    ],
  },
];

const PHASE_COLORS = {
  in:   'hsl(168, 60%, 50%)',
  hold: 'hsl(258, 60%, 65%)',
  out:  'hsl(212, 70%, 60%)',
};

function BreathingTool() {
  const [patternId, setPatternId] = useState('box');
  const [targetCycles, setTargetCycles] = useState(8);
  const [playing, setPlaying] = useState(false);
  const [cycleCount, setCycleCount] = useState(0);
  const [phaseIdx, setPhaseIdx] = useState(0);
  const [phaseStart, setPhaseStart] = useState(null); // ms timestamp
  const [now, setNow] = useState(Date.now());
  const tickRef = useRef(null);

  const pattern = useMemo(() => BREATH_PATTERNS.find(p => p.id === patternId) || BREATH_PATTERNS[0], [patternId]);
  const phase = pattern.phases[phaseIdx];

  // Load preferences
  useEffect(() => {
    db.kv.get('breathingPrefs').then(rec => {
      if (rec?.v) {
        if (rec.v.patternId) setPatternId(rec.v.patternId);
        if (typeof rec.v.targetCycles === 'number') setTargetCycles(rec.v.targetCycles);
      }
    });
  }, []);
  const savePrefs = () => db.kv.put({ k: 'breathingPrefs', v: { patternId, targetCycles } });
  useEffect(() => { savePrefs(); }, [patternId, targetCycles]);

  // Tick at 30fps for smooth circle animation; we drive everything off Date.now()
  useEffect(() => {
    if (!playing) return;
    tickRef.current = setInterval(() => setNow(Date.now()), 33);
    return () => { if (tickRef.current) clearInterval(tickRef.current); };
  }, [playing]);

  // Advance phase when its duration elapses
  useEffect(() => {
    if (!playing || !phaseStart) return;
    const elapsed = (now - phaseStart) / 1000;
    if (elapsed >= phase.seconds) {
      const nextIdx = phaseIdx + 1;
      if (nextIdx >= pattern.phases.length) {
        // Cycle complete
        const nextCount = cycleCount + 1;
        if (nextCount >= targetCycles) {
          // Session finished
          setPlaying(false);
          setCycleCount(nextCount);
          setPhaseIdx(0);
          setPhaseStart(null);
          return;
        }
        setCycleCount(nextCount);
        setPhaseIdx(0);
      } else {
        setPhaseIdx(nextIdx);
      }
      setPhaseStart(Date.now());
    }
  }, [now, playing, phaseStart, phase, phaseIdx, pattern, cycleCount, targetCycles]);

  const start = () => {
    if (playing) return;
    setPhaseIdx(0);
    setCycleCount(0);
    setPhaseStart(Date.now());
    setNow(Date.now());
    setPlaying(true);
  };
  const stop = () => {
    setPlaying(false);
    setPhaseIdx(0);
    setPhaseStart(null);
  };
  const pause = () => {
    setPlaying(false);
  };
  const resume = () => {
    setPhaseStart(Date.now() - (phase.seconds - getRemaining()) * 1000);
    setPlaying(true);
  };

  const elapsed = playing && phaseStart ? (now - phaseStart) / 1000 : 0;
  const progress = Math.min(1, elapsed / phase.seconds);
  function getRemaining() {
    return Math.max(0, phase.seconds - elapsed);
  }
  // Scale the circle: in = grow from 0.5 → 1.0; out = shrink 1.0 → 0.5; hold = stay where the previous phase ended.
  const scale = useMemo(() => {
    if (!playing) return 0.5;
    if (phase.kind === 'in')  return 0.5 + 0.5 * progress;
    if (phase.kind === 'out') return 1.0 - 0.5 * progress;
    // hold — figure out which side we're on (after in vs after out)
    // Find previous non-hold phase
    let prevKind = 'in';
    for (let i = phaseIdx - 1; i >= 0; i--) {
      if (pattern.phases[i].kind !== 'hold') { prevKind = pattern.phases[i].kind; break; }
    }
    return prevKind === 'in' ? 1.0 : 0.5;
  }, [playing, phase, progress, phaseIdx, pattern]);

  const finished = cycleCount >= targetCycles && !playing;

  return (
    <div className="breath-tool">
      <header className="breath-head">
        <div>
          <h1>Breathing</h1>
          <p>Slow your breath, slow your mind. Pick a pattern — the circle leads.</p>
        </div>
      </header>

      <section className="breath-stage">
        <div className="breath-circle-wrap">
          {/* Animated circle */}
          <div
            className={`breath-circle phase-${phase.kind}`}
            style={{
              transform: `scale(${scale})`,
              transition: playing ? `transform ${phase.seconds}s ${phase.kind === 'hold' ? 'linear' : 'cubic-bezier(0.4, 0, 0.6, 1)'}` : 'transform 600ms ease',
              background: `radial-gradient(circle at 35% 30%, color-mix(in oklab, ${PHASE_COLORS[phase.kind]} 80%, white 20%) 0%, ${PHASE_COLORS[phase.kind]} 70%)`,
              boxShadow: `0 0 80px color-mix(in oklab, ${PHASE_COLORS[phase.kind]} 40%, transparent)`,
            }}
          />
          {/* Phase label centered over circle */}
          <div className="breath-label">
            {finished ? (
              <>
                <div className="breath-cue">Done</div>
                <div className="breath-count">Completed {cycleCount} cycle{cycleCount === 1 ? '' : 's'}</div>
              </>
            ) : !playing && cycleCount === 0 ? (
              <>
                <div className="breath-cue">Ready</div>
                <div className="breath-count">{pattern.phases.map(p => p.seconds).join(' · ')}</div>
              </>
            ) : (
              <>
                <div className="breath-cue" style={{ color: PHASE_COLORS[phase.kind] }}>{phase.label}</div>
                <div className="breath-count">
                  {Math.ceil(getRemaining())}s · cycle {cycleCount + 1} / {targetCycles}
                </div>
              </>
            )}
          </div>
        </div>

        <div className="breath-controls">
          {!playing ? (
            <button className="lh-btn primary breath-primary" onClick={cycleCount > 0 && cycleCount < targetCycles ? resume : start}>
              <Icon name="play_arrow" />{cycleCount > 0 && cycleCount < targetCycles ? 'Resume' : finished ? 'Start again' : 'Begin'}
            </button>
          ) : (
            <button className="lh-btn ghost breath-primary" onClick={pause}>
              <Icon name="pause" />Pause
            </button>
          )}
          {(playing || cycleCount > 0) && (
            <button className="lh-btn ghost" onClick={stop}>
              <Icon name="stop" />Stop
            </button>
          )}
        </div>
      </section>

      {/* Pattern picker */}
      <section className="breath-pickers">
        <div className="breath-picker">
          <div className="breath-picker-label">Pattern</div>
          <div className="breath-pattern-grid">
            {BREATH_PATTERNS.map(p => (
              <button
                key={p.id}
                className={`breath-pattern-card ${patternId === p.id ? 'is-active' : ''}`}
                onClick={() => { setPatternId(p.id); stop(); }}
                disabled={playing}
              >
                <div className="breath-pattern-name">{p.name}</div>
                <div className="breath-pattern-tag">{p.tagline}</div>
                <div className="breath-pattern-rhythm">
                  {p.phases.map((ph, i) => (
                    <span key={i} className={`breath-pattern-phase phase-${ph.kind}`}>{ph.seconds}s</span>
                  ))}
                </div>
              </button>
            ))}
          </div>
        </div>

        <div className="breath-picker">
          <div className="breath-picker-label">Cycles</div>
          <div className="breath-cycles">
            <input
              type="range"
              min="3" max="20" step="1"
              value={targetCycles}
              onChange={e => setTargetCycles(parseInt(e.target.value, 10))}
              disabled={playing}
            />
            <div className="breath-cycles-value">
              <span className="breath-cycles-num">{targetCycles}</span> cycles
              <span className="breath-cycles-time">
                ≈ {Math.round(targetCycles * pattern.phases.reduce((a, p) => a + p.seconds, 0) / 60)} min
              </span>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

window.BreathingTool = BreathingTool;
