// Burst mode — fullscreen Pomodoro takeover.
// Locks the user to ONE task. Big clock. Calm dark space.
// ADHD pattern: kill the dashboard, one thing, time-boxed.

function BurstMode() {
  const { state, closeBurst, pauseBurst, tickBurst, toggleTask, startBurst, setBurstLength } = useStore();
  const b = state.burst;
  if (!b.active) return null;

  // Find the task being focused on
  const priority = state.priorities.find((p) => p.id === b.priorityId);
  const task = priority?.tasks.find((t) => t.id === b.taskId);

  // ticker
  React.useEffect(() => {
    if (!b.running) return;
    const id = setInterval(tickBurst, 1000);
    return () => clearInterval(id);
  }, [b.running, tickBurst]);

  // ESC to close
  React.useEffect(() => {
    const k = (e) => { if (e.key === 'Escape') closeBurst(); };
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, [closeBurst]);

  const mins = Math.floor(b.remaining / 60);
  const secs = b.remaining % 60;
  const timeLabel = `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  const pct = b.length > 0 ? 1 - b.remaining / b.length : 0;
  const r = 150;
  const C = 2 * Math.PI * r;
  const dashOffset = C * (1 - pct);

  const finished = b.remaining === 0;

  return (
    <div className="mc-burst" role="dialog" aria-label="Burst mode">
      <div className="mc-burst-hd">
        <div className="lbl"><span className="dot"/> Burst mode · {b.phase}</div>
        <button className="mc-burst-close" onClick={closeBurst} aria-label="Close burst mode">
          <Icons.X size={16}/>
        </button>
      </div>

      <div className="mc-burst-stage">
        <div className="mc-burst-task">
          <div className="step">{priority?.tag || 'focus'}</div>
          <h2>{task ? task.label : (priority?.title || 'Pick a task to focus on')}</h2>
          {priority && (
            <div className="src">From priority · {priority.title}</div>
          )}
        </div>

        <div className="mc-ring">
          <svg viewBox="0 0 320 320">
            <defs>
              <linearGradient id="mc-grad" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%"   stopColor="#2a3be1"/>
                <stop offset="50%"  stopColor="#7a26ea"/>
                <stop offset="100%" stopColor="#e412f1"/>
              </linearGradient>
            </defs>
            <circle className="track" cx="160" cy="160" r={r}/>
            <circle className="fill"  cx="160" cy="160" r={r}
                    strokeDasharray={C} strokeDashoffset={dashOffset}/>
          </svg>
          <div className="clock">
            <div className="time">{timeLabel}</div>
            <div className="phase">{finished ? 'finished — well done' : (b.running ? 'in flow' : 'paused')}</div>
          </div>
        </div>

        <div className="mc-burst-controls">
          {finished ? (
            <>
              <button className="btn primary" onClick={() => {
                if (task) toggleTask(priority.id, task.id);
                closeBurst();
              }}>
                <Icons.Check size={15}/> Mark done & close
              </button>
              <button className="btn" onClick={() => startBurst(b.priorityId, b.taskId, b.length)}>
                <Icons.Refresh size={15}/> One more round
              </button>
            </>
          ) : (
            <>
              <button className="btn primary" onClick={pauseBurst}>
                {b.running ? <><Icons.Pause size={14}/> Pause</> : <><Icons.Play size={14}/> Resume</>}
              </button>
              {task && (
                <button className="btn" onClick={() => { toggleTask(priority.id, task.id); closeBurst(); }}>
                  <Icons.Check size={14}/> Finish task
                </button>
              )}
              <BurstLengthPicker length={b.length} setLength={setBurstLength}/>
            </>
          )}
        </div>
      </div>

      <div className="mc-burst-foot">
        <div className="stats">
          <div>
            <b>{b.completedToday}</b>
            <div>bursts today</div>
          </div>
          <div>
            <b>{b.streakDays}</b>
            <div>day streak</div>
          </div>
          <div>
            <b>{Math.round(b.completedToday * b.length / 60)}m</b>
            <div>focused</div>
          </div>
        </div>

        {priority && priority.tasks.length > 1 && (
          <div className="siblings">
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, textTransform: 'uppercase',
              letterSpacing: '0.16em', color: 'rgba(255,255,255,0.4)', marginBottom: 4 }}>
              up next in this priority
            </div>
            {priority.tasks.filter((t) => !t.done && t.id !== b.taskId).slice(0, 3).map((t) => (
              <div key={t.id} className="ti" onClick={() => startBurst(priority.id, t.id, b.length)}>
                <span className="dot"/> {t.label}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function BurstLengthPicker({ length, setLength }) {
  const opts = [
    { v: 25 * 60, label: '25' },
    { v: 30 * 60, label: '30' },
    { v: 45 * 60, label: '45' },
    { v: 52 * 60, label: '52' },
  ];
  return (
    <div style={{ display: 'inline-flex', gap: 4, padding: 3,
      background: 'rgba(255,255,255,0.06)', borderRadius: 999,
      border: '1px solid rgba(255,255,255,0.1)' }}>
      {opts.map((o) => (
        <button key={o.v}
          onClick={() => setLength(o.v)}
          style={{
            appearance: 'none', border: 0, cursor: 'pointer',
            padding: '6px 12px', borderRadius: 999,
            fontFamily: 'inherit', fontWeight: 600, fontSize: 12,
            color: length === o.v ? '#fff' : 'rgba(255,255,255,0.55)',
            background: length === o.v ? 'rgba(255,255,255,0.15)' : 'transparent',
          }}>
          {o.label}m
        </button>
      ))}
    </div>
  );
}

Object.assign(window, { BurstMode });
