/* Dump — pomodoro.jsx: full-screen focus timer modal, break screen + pill.
   Renders whenever pomodoro.status !== 'idle' (except while a break is
   minimised to the floating pill). State + persistence live in store.js. */

/* Tick every second while `active` so derived countdowns re-render. */
function usePomoTick(active) {
  const [, force] = useState(0);
  useEffect(() => {
    if (!active) return;
    const id = setInterval(() => force((n) => n + 1), 250);
    return () => clearInterval(id);
  }, [active]);
  return Date.now();
}

function fmtClock(secs) {
  secs = Math.max(0, Math.round(secs));
  const m = Math.floor(secs / 60);
  const s = secs % 60;
  return m + ':' + String(s).padStart(2, '0');
}

// Live elapsed seconds for the work timer (accumulated + current run segment).
function workElapsed(p) {
  if (p.status === 'running' && p.startedAt) {
    return p.elapsed + (Date.now() - new Date(p.startedAt).getTime()) / 1000;
  }
  return p.elapsed;
}
function breakElapsed(p) {
  if (!p.startedAt) return p.elapsed;
  return (Date.now() - new Date(p.startedAt).getTime()) / 1000;
}

function taskFor(id) {
  const s = DumpStore.getState();
  return s.tasks.find((t) => t.id === id) || s.archive.find((t) => t.id === id) || null;
}

// Count of tasks still to work in the running session (current + queued).
function sessionLeft(pomo) {
  const sess = pomo.session;
  if (!sess) return 0;
  return (sess.remaining || []).length;
}

/* ---------- Circular countdown ---------- */
function TimerRing({ fraction, label, sub }) {
  const R = 130, C = 2 * Math.PI * R;
  return (
    <div className="pomo-ring-wrap">
      <svg className="pomo-ring" viewBox="0 0 300 300" width="300" height="300">
        <circle cx="150" cy="150" r={R} className="pomo-ring-track"></circle>
        <circle
          cx="150" cy="150" r={R} className="pomo-ring-fill"
          strokeDasharray={C}
          strokeDashoffset={C * (1 - fraction)}
          transform="rotate(-90 150 150)"
        ></circle>
      </svg>
      <div className="pomo-ring-center">
        <span className="pomo-clock">{label}</span>
        {sub ? <span className="pomo-clock-sub">{sub}</span> : null}
      </div>
    </div>
  );
}

/* ---------- Work screen ---------- */
function PomodoroWorkScreen({ pomo, settings }) {
  usePomoTick(pomo.status === 'running');
  const task = taskFor(pomo.taskId);
  const total = (settings.pomodoroWork || 25) * 60;
  const elapsed = workElapsed(pomo);
  const remaining = Math.max(0, total - elapsed);
  const inSession = !!pomo.session;
  const left = sessionLeft(pomo);

  // Work complete → freeze and show the completion screen (same modal).
  useEffect(() => {
    if (pomo.status === 'running' && remaining <= 0) {
      DumpAPI.fireNotify("Time's up — did you finish it?", task ? task.text : '');
      DumpStore.set((s) => ({ pomodoro: Object.assign({}, s.pomodoro, { status: 'complete', elapsed: total, startedAt: null }) }));
    }
  }, [remaining, pomo.status]);

  const paused = pomo.status === 'paused';

  // One task on screen at a time — the queued tasks are deliberately NOT named here.
  return (
    <div className="pomo-screen pomo-work">
      <div className="pomo-eyebrow">{Icons.timer(16)} {inSession ? 'Focus session' : 'Focus'}</div>
      <h2 className="pomo-task">{task ? task.text : 'Focus'}</h2>

      <TimerRing
        fraction={total ? remaining / total : 0}
        label={fmtClock(remaining)}
        sub={paused ? 'Paused' : null}
      />

      <div className="pomo-actions">
        {paused ? (
          <button className="btn pomo-btn-solid" onClick={() => DumpAPI.resumePomodoro()}>{Icons.play(15)} Resume</button>
        ) : (
          <button className="btn pomo-btn-solid" onClick={() => DumpAPI.pausePomodoro()}>{Icons.pause(15)} Pause</button>
        )}
        <button className="btn pomo-btn-ghost" onClick={() => DumpAPI.abandonPomodoro()}>{inSession ? 'End session' : 'Abandon'}</button>
      </div>
      <p className="pomo-foot">{inSession
        ? (left > 1 ? left + ' tasks in this session · one at a time' : 'Last one · nearly there')
        : 'Session ' + ((pomo.sessionCount || 0) + 1) + ' today · nav hidden until you’re done'}</p>
    </div>
  );
}

/* ---------- Completion screen ---------- */
function PomodoroCompleteScreen({ pomo }) {
  const task = taskFor(pomo.taskId);
  const inSession = !!pomo.session;

  const finished = () => {
    if (inSession) { DumpAPI.sessionWorkComplete(true); return; } // marks done + mandatory break
    DumpAPI.completePomodoro(pomo.taskId); // increments count + starts break
    DumpAPI.markTaskDone(pomo.taskId);
    DumpAPI.toast('Nice — one Pomodoro logged and the task’s done.');
  };
  const notYet = () => {
    if (inSession) { DumpAPI.sessionWorkComplete(false); return; } // keep task, mandatory break, resume after
    DumpAPI.completePomodoro(pomo.taskId); // increments count, keeps task active
  };

  return (
    <div className="pomo-screen pomo-work">
      <div className="pomo-eyebrow">{Icons.done(16)} Time’s up</div>
      <h2 className="pomo-task">Well done.</h2>
      {task ? <p className="pomo-complete-sub">“{task.text}”</p> : null}
      <p className="pomo-question">Did you finish it?</p>
      <div className="pomo-actions pomo-actions-stack">
        <button className="btn pomo-btn-solid" onClick={finished}>Yes, I finished it</button>
        <button className="btn pomo-btn-ghost" onClick={notYet}>{inSession ? 'Not yet — keep going after a break' : 'Not quite — need more time'}</button>
      </div>
      {inSession ? <p className="pomo-foot">A short break comes next either way — that’s the technique.</p> : null}
    </div>
  );
}

/* ---------- Quick-task screen (session only: small tasks skip the timer) ---------- */
function PomodoroQuickScreen({ pomo }) {
  const task = taskFor(pomo.taskId);
  const left = sessionLeft(pomo);
  return (
    <div className="pomo-screen pomo-work">
      <div className="pomo-eyebrow">{Icons.bolt(15)} Quick one</div>
      <h2 className="pomo-task">{task ? task.text : 'Quick task'}</h2>
      <p className="pomo-complete-sub">{task && task.minutes ? '~' + task.minutes + ' min' : 'A couple of minutes'} — this is too short for a timer. Just do it now.</p>
      <div className="pomo-actions pomo-actions-stack">
        <button className="btn pomo-btn-solid" onClick={() => DumpAPI.sessionQuickDone()}>{Icons.check(14)} Done — next</button>
        <button className="btn pomo-btn-ghost" onClick={() => DumpAPI.sessionQuickToTimer()}>Start a timer anyway</button>
        <button className="btn pomo-btn-ghost" onClick={() => DumpAPI.sessionSkipCurrent()}>Skip for now</button>
      </div>
      <p className="pomo-foot">{left > 1 ? left + ' left in this session' : 'Last one in this session'}</p>
    </div>
  );
}

/* ---------- Session-done summary ---------- */
function PomodoroSessionDoneScreen({ pomo }) {
  const sess = pomo.session || { done: [], total: 0, remaining: [] };
  const doneN = (sess.done || []).length;
  const total = sess.total || doneN;
  const allDone = (sess.remaining || []).length === 0;
  return (
    <div className="pomo-screen pomo-work">
      <div className="pomo-eyebrow">{Icons.done(16)} Focus block done</div>
      <h2 className="pomo-task">{allDone && doneN > 0 ? 'All done.' : doneN > 0 ? 'Good progress.' : 'That’s a stop.'}</h2>
      <p className="pomo-complete-sub">
        {doneN > 0
          ? doneN + ' of ' + total + ' focus task' + (total === 1 ? '' : 's') + ' finished' + (allDone ? ' — whatever else happens, today worked.' : '. The rest are still on your board.')
          : 'Nothing finished this time — that’s fine. Come back when you’ve got a clear stretch.'}
      </p>
      <div className="pomo-actions pomo-actions-stack">
        <button className="btn pomo-btn-solid" onClick={() => DumpAPI.closeSessionDone()}>Back to Today</button>
      </div>
    </div>
  );
}

/* ---------- Break screen ---------- */
function PomodoroBreakScreen({ pomo, settings }) {
  usePomoTick(true);
  const isLong = pomo.status === 'longbreak';
  const total = (isLong ? (settings.pomodoroLongBreak || 15) : (settings.pomodoroBreak || 5)) * 60;
  const remaining = Math.max(0, total - breakElapsed(pomo));
  const sess = pomo.session;
  const nextTask = sess && sess.nextId ? taskFor(sess.nextId) : null;
  // In a session the next task is revealed ONLY here, and the break is mandatory.
  const resuming = sess && sess.nextId && sess.currentId === sess.nextId;

  useEffect(() => {
    if (remaining <= 0) {
      DumpAPI.fireNotify('Break over — ready for the next one?');
      DumpAPI.endBreak();
    }
  }, [remaining]);

  return (
    <div className={'pomo-screen ' + (isLong ? 'pomo-longbreak' : 'pomo-break')}>
      {sess ? null : <button className="pomo-dismiss" onClick={() => DumpAPI.dismissBreakToPill()} aria-label="Minimise">{Icons.x(20)}</button>}
      <div className="pomo-eyebrow">{isLong ? 'Long break' : 'Short break'}</div>
      <h2 className="pomo-task">{isLong ? 'You’ve done four. Rest properly.' : 'Step away. Seriously.'}</h2>
      <p className="pomo-complete-sub">{isLong ? 'A longer reset earns you the next stretch.' : 'You earned it — look away from the screen.'}</p>

      <TimerRing fraction={total ? remaining / total : 0} label={fmtClock(remaining)} />

      {sess && nextTask ? (
        <div className="pomo-next">
          <span className="pomo-next-label">{resuming ? 'Back to' : 'Next up'}</span>
          <span className="pomo-next-task">{nextTask.text}</span>
        </div>
      ) : null}

      <div className="pomo-actions">
        {sess
          ? <button className="btn pomo-btn-ghost pomo-skip" onClick={() => DumpAPI.endFocusSession(true)}>End session</button>
          : <button className="btn pomo-btn-ghost pomo-skip" onClick={() => DumpAPI.endBreak()}>Skip break</button>}
      </div>
      {sess ? (
        <p className="pomo-foot">
          Take the break — it’s part of the method. {nextTask ? (resuming ? 'Then back to it.' : 'Then the next one.') : ''}
          {' '}<button className="pomo-skip-link" onClick={() => DumpAPI.endBreak()}>{nextTask ? (resuming ? 'Skip break, back to it' : 'Skip break, start next') : 'Skip this break'}</button>
        </p>
      ) : null}
    </div>
  );
}

/* ---------- The modal shell ---------- */
function PomodoroModal() {
  const { pomodoro, settings } = useDumpStore();
  const status = pomodoro.status;
  const isBreak = status === 'break' || status === 'longbreak';

  // Hidden while idle, or while a break is minimised to the pill.
  if (status === 'idle') return null;
  if (isBreak && pomodoro.pilled) return null;

  let screen;
  if (status === 'complete') screen = <PomodoroCompleteScreen pomo={pomodoro} />;
  else if (status === 'quickcheck') screen = <PomodoroQuickScreen pomo={pomodoro} />;
  else if (status === 'sessiondone') screen = <PomodoroSessionDoneScreen pomo={pomodoro} />;
  else if (isBreak) screen = <PomodoroBreakScreen pomo={pomodoro} settings={settings} />;
  else screen = <PomodoroWorkScreen pomo={pomodoro} settings={settings} />;

  const tone = status === 'longbreak' ? 'tone-long' : isBreak ? 'tone-break' : 'tone-work';

  return <div className={'pomo-modal ' + tone}>{screen}</div>;
}

/* ---------- Floating break pill ---------- */
function BreakPill() {
  const { pomodoro, settings } = useDumpStore();
  const isBreak = pomodoro.status === 'break' || pomodoro.status === 'longbreak';
  usePomoTick(isBreak && pomodoro.pilled);
  if (!isBreak || !pomodoro.pilled) return null;

  const isLong = pomodoro.status === 'longbreak';
  const total = (isLong ? (settings.pomodoroLongBreak || 15) : (settings.pomodoroBreak || 5)) * 60;
  const remaining = Math.max(0, total - breakElapsed(pomodoro));

  return (
    <button className={'break-pill' + (isLong ? ' long' : '')} onClick={() => DumpAPI.reopenBreak()}>
      <span className="break-pill-dot"></span>
      {isLong ? 'Long break' : 'Break'} · {fmtClock(remaining)}
    </button>
  );
}

window.PomodoroModal = PomodoroModal;
window.BreakPill = BreakPill;
