// Komonichi — in-app timer notices.
//
// OS notifications (src/timerStore.js) only reach the user if they grant
// permission. This is the always-on, in-app counterpart: quiet themed toasts
// that appear on *any* page, driven by the shared timer engine
// (window.KomonichiTimer). Mounted once at the app shell. Two kinds:
//   • session end  — focus done ("a single bell") / break done.
//   • extend offer — at 5 min left in a focus session, ask whether to add
//     time. If ignored it simply fades; +5m/+10m grow the running timer.
function TimerToast() {
  const T = window.KomonichiTimer;
  const [notice, setNotice] = React.useState(null); // { kind, taskTitle, at } | null
  const lastBellRef = React.useRef(null);
  const lastPromptRef = React.useRef(null);

  React.useEffect(() => {
    // Ignore any signal that fired before this component mounted (e.g. reload).
    try {
      const s0 = T.get();
      lastBellRef.current = s0.bellAt || null;
      lastPromptRef.current = s0.extendPromptAt || null;
    } catch (e) {}
    return T.subscribe((s) => {
      // session ended (focus or break)
      if (s.bellAt && s.bellAt !== lastBellRef.current) {
        lastBellRef.current = s.bellAt;
        let taskTitle = null;
        try {
          const t = s.taskId && window.KomonichiState.getState().tasks.find((x) => x.id === s.taskId);
          taskTitle = t ? t.title : null;
        } catch (e) {}
        setNotice({ kind: s.bellKind, taskTitle, at: s.bellAt });
        return;
      }
      // 5-min "a little longer?" offer
      if (s.extendPromptAt && s.extendPromptAt !== lastPromptRef.current) {
        lastPromptRef.current = s.extendPromptAt;
        setNotice({ kind: 'extend', at: s.extendPromptAt });
      }
    });
  }, []);

  // Each notice fades on its own. The extend offer is the most ephemeral —
  // ignore it and nothing happens.
  React.useEffect(() => {
    if (!notice) return;
    const ms = notice.kind === 'extend' ? 12000 : (notice.kind === 'break' ? 9000 : 14000);
    const id = setTimeout(() => setNotice(null), ms);
    return () => clearTimeout(id);
  }, [notice]);

  if (!notice) return null;

  const close = () => setNotice(null);
  const tendToIt = () => { try { location.hash = '#today'; } catch (e) {} close(); };
  const addMinutes = (m) => { try { T.extend(m); } catch (e) {} close(); };

  let label, message, actions;
  if (notice.kind === 'extend') {
    label = 'five minutes remain';
    message = 'Would you like a little longer?';
    actions = (
      <>
        <button className="btn warm tiny" onClick={() => addMinutes(5)} style={{ flex: '0 0 auto' }}>+5 min</button>
        <button className="btn warm tiny" onClick={() => addMinutes(10)} style={{ flex: '0 0 auto' }}>+10 min</button>
      </>
    );
  } else if (notice.kind === 'break') {
    label = 'the rest is over';
    message = 'Return when you are ready.';
    actions = null;
  } else {
    label = 'a single bell';
    message = notice.taskTitle ? `Your bowl is kept — ${notice.taskTitle}` : 'Your bowl is kept.';
    actions = (
      <button className="btn warm tiny" onClick={tendToIt} style={{ flex: '0 0 auto' }}>tend to it</button>
    );
  }

  return (
    <div role="status" aria-live="polite" className="fade-in"
      style={{ position: 'fixed', left: 0, right: 0, bottom: 24, margin: '0 auto',
               zIndex: 60, maxWidth: 460, width: 'calc(100% - 32px)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px',
                    background: 'rgba(255,254,250,0.97)', border: '1px solid var(--ink-soft)',
                    boxShadow: '0 10px 34px rgba(44,38,32,0.14)' }}>
        <div className="enso breathe" style={{ width: 36, height: 36, flex: '0 0 auto' }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="label" style={{ color: 'var(--persimmon)' }}>{label}</div>
          <div className="display" style={{ fontSize: 18, color: 'var(--ink)', marginTop: 2,
                 whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {message}
          </div>
        </div>
        {actions}
        <button className="btn ghost tiny" onClick={close} style={{ flex: '0 0 auto' }}>dismiss</button>
      </div>
    </div>
  );
}

window.TimerToast = TimerToast;
