// ─── Today (PM-060 Life OS) ───
// One screen that says what is happening NOW, what is NEXT, today's LF tasks
// and what is DONE, with big buttons. NOW/NEXT come from EPFC's calendar feed
// (table lf_today_feed, written through the lf-today function). The phone and
// the box work out now/next and the block-start chime from the clock, so the
// last feed keeps working when the network drops.
// Spec: OneDrive\02 Work and Misc. Archive\Laminar Flow\specs\TODAY-FEED-v1.md
//
// Device-local state uses keys WITHOUT the `lf.` prefix on purpose: the sync
// layer ships every `lf.*` key to Postgres and the office file, and none of
// this (feed cache, chime switch, which view the phone opens) belongs there.

(function () {
  const FEED_KEY = 'lfTodayFeed';
  const ACT_KEY = 'lfBlockActions';
  const QUEUE_KEY = 'lfBlockActionsQueue';
  const CHIMED_KEY = 'lfChimed';
  const CHIME_KEY = 'lfChime';
  const VIEW_KEY = 'lfPhoneView';
  const POLL_MS = 5 * 60 * 1000;
  const TICK_MS = 10 * 1000;
  const START_WINDOW_MS = 2 * 60 * 1000;   // a background tab ticks about once a minute

  // A block's role key → the app's role (index.html ROLES). No role = grey.
  const roleInfo = (key) => {
    if (!key || !window.modeOf) return { label: '', color: '#4B5563' };
    const r = window.modeOf(key);
    return r.id === 'unassigned' ? { label: '', color: r.color } : { label: r.label, color: r.color };
  };

  const ls = {
    get(k, d) { try { const v = localStorage.getItem(k); return v == null ? d : JSON.parse(v); } catch (e) { return d; } },
    set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} },
  };
  const localDate = (t = new Date()) => `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(t.getDate()).padStart(2, '0')}`;
  const coarse = () => !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);

  const subs = new Set();
  const emit = () => subs.forEach((f) => { try { f(); } catch (e) {} });
  const state = {
    cache: ls.get(FEED_KEY, null),                                  // { feed, generated_at, updated_at, fetched_at }
    actions: ls.get(ACT_KEY, { date: localDate(), map: {} }),       // today's taps, by block id
    lastStart: null,                                                // { id, at }: drives the float's flash
    fetching: false, flushing: false, error: null, pip: null,
  };

  const parse = (list) => (Array.isArray(list) ? list : [])
    .filter((b) => b && b.id && b.start && b.end)
    .map((b) => ({ ...b, s: Date.parse(b.start), e: Date.parse(b.end) }))
    .filter((b) => Number.isFinite(b.s) && Number.isFinite(b.e))
    .sort((a, b) => a.s - b.s);

  function nowNext(t = Date.now()) {
    const f = state.cache && state.cache.feed;
    if (!f) return { now: null, next: null, blocks: [] };
    const blocks = parse(f.blocks);
    const cur = blocks.filter((b) => b.s <= t && t < b.e);
    const now = cur.length ? cur[cur.length - 1] : null;            // overlapping: the latest-started wins
    let next = blocks.find((b) => b.s > t) || null;
    if (!next && f.next_day_first) { const n = parse([f.next_day_first])[0]; if (n && n.s > t) next = n; }
    return { now, next, blocks };
  }

  function rollActions() {
    const d = localDate();
    if (state.actions.date !== d) { state.actions = { date: d, map: {} }; ls.set(ACT_KEY, state.actions); }
  }

  async function signedInUser() {
    try { const { data } = await window.sb.auth.getSession(); return (data && data.session && data.session.user) || null; } catch (e) { return null; }
  }

  async function pullActions() {
    rollActions();
    const { data, error } = await window.sb.from('lf_block_actions').select('block_id, action, at, task_id').eq('date', state.actions.date).order('at');
    if (error) return;
    (data || []).forEach((r) => {
      const cur = state.actions.map[r.block_id];
      if (!cur || Number(cur.at) <= Number(r.at)) state.actions.map[r.block_id] = { action: r.action, at: Number(r.at), task_id: r.task_id };
    });
    ls.set(ACT_KEY, state.actions);
  }

  async function flushQueue() {
    if (state.flushing || !window.sb) return;
    const q = ls.get(QUEUE_KEY, []);
    if (!q.length) return;
    state.flushing = true;
    try {
      const user = await signedInUser();
      if (!user) return;
      const { error } = await window.sb.from('lf_block_actions').insert(q.map((r) => ({ ...r, user_id: user.id })));
      if (!error) ls.set(QUEUE_KEY, ls.get(QUEUE_KEY, []).slice(q.length));   // the queue only appends
    } catch (e) {} finally { state.flushing = false; }
  }

  // Weekly scorecard (PM-066): a PNG in the PRIVATE bucket `scorecards`,
  // <user_id>/<YYYY-MM-DD>.png. Listed at most every 30 min; shown only if it
  // is from the last 14 days; downloaded with his session when he taps it
  // (never a public or signed link).
  const SC_LIST_MS = 30 * 60 * 1000;
  state.scorecard = null; state.scListedAt = 0;
  async function listScorecard(user) {
    if (Date.now() - state.scListedAt < SC_LIST_MS) return;
    state.scListedAt = Date.now();
    const { data, error } = await window.sb.storage.from('scorecards').list(user.id, { limit: 20, sortBy: { column: 'name', order: 'desc' } });
    if (error) return;
    const today = localDate(); const min = localDate(new Date(Date.now() - 13 * 86400000));
    const hit = (data || []).map((o) => o.name).filter((n) => /^\d{4}-\d{2}-\d{2}\.png$/.test(n))
      .map((n) => n.slice(0, 10)).filter((d) => d <= today && d >= min).sort().pop();
    state.scorecard = hit ? { date: hit, path: `${user.id}/${hit}.png` } : null;
  }
  async function scorecardUrl() {
    if (!state.scorecard || !window.sb) return null;
    const { data, error } = await window.sb.storage.from('scorecards').download(state.scorecard.path);
    return error || !data ? null : URL.createObjectURL(data);
  }

  async function refresh() {
    if (!window.sb || state.fetching) return;
    const user = await signedInUser();
    if (!user) return;
    state.fetching = true;
    try {
      const { data, error } = await window.sb.from('lf_today_feed').select('feed, generated_at, updated_at').maybeSingle();
      if (error) throw error;
      if (data) { state.cache = { ...data, fetched_at: Date.now() }; ls.set(FEED_KEY, state.cache); }
      state.error = null;
      await pullActions();
      await flushQueue();
      try { await listScorecard(user); } catch (e) {}
    } catch (e) { state.error = String((e && e.message) || e); }
    state.fetching = false;
    emit();
  }

  function findTask(taskId) {
    const ps = (window.LF && window.LF.get('projects')) || [];
    for (const p of ps) for (const m of (p.branches || [])) for (const t of (m.leaves || [])) if (t.id === taskId) return { p, m, t };
    return null;
  }

  // His tap on a block. Done on a task block also completes that LF task: it
  // is his own tap, the same as ticking it anywhere else in the app.
  function recordAction(block, action) {
    rollActions();
    const at = Date.now();
    const row = { block_id: String(block.id), date: localDate(new Date(block.s)), action, task_id: block.lf_task_id || null, at, source: coarse() ? 'phone' : 'box' };
    state.actions.map[row.block_id] = { action, at, task_id: row.task_id };
    ls.set(ACT_KEY, state.actions);
    ls.set(QUEUE_KEY, [...ls.get(QUEUE_KEY, []), row]);
    if (action === 'done' && block.lf_task_id) {
      const hit = findTask(block.lf_task_id);
      if (hit && !hit.t.done && window.setTaskDoneCascade) window.setTaskDoneCascade(hit.p.id, hit.m.id, hit.t.id, true);
    }
    emit();
    flushQueue();
  }

  // ── Chime ──────────────────────────────────────────────────────────────────
  // One soft two-note chime. On by default where there is a mouse (the box),
  // off on touch screens (the phone just refreshes), switchable per device.
  let audio = null;
  const chimeOn = () => { const v = localStorage.getItem(CHIME_KEY); return v === '1' ? true : v === '0' ? false : !coarse(); };
  function audioCtx() {
    if (!audio) { const C = window.AudioContext || window.webkitAudioContext; if (!C) return null; audio = new C(); }
    return audio;
  }
  function unlockAudio() { if (!chimeOn()) return; const a = audioCtx(); if (a && a.state === 'suspended') a.resume().catch(() => {}); }
  ['pointerdown', 'keydown'].forEach((ev) => window.addEventListener(ev, unlockAudio, { capture: true, passive: true }));
  function playChime() {
    const a = audioCtx(); if (!a) return;
    if (a.state === 'suspended') a.resume().catch(() => {});
    const t0 = a.currentTime + 0.03;
    [[659.25, 0], [880, 0.3]].forEach(([f, d]) => {
      const o = a.createOscillator(); const g = a.createGain();
      o.type = 'sine'; o.frequency.value = f;
      g.gain.setValueAtTime(0.0001, t0 + d);
      g.gain.exponentialRampToValueAtTime(0.16, t0 + d + 0.02);
      g.gain.exponentialRampToValueAtTime(0.0001, t0 + d + 1.4);
      o.connect(g); g.connect(a.destination); o.start(t0 + d); o.stop(t0 + d + 1.5);
    });
  }
  function setChime(on) {
    try { localStorage.setItem(CHIME_KEY, on ? '1' : '0'); } catch (e) {}
    if (on) {
      unlockAudio();
      try { if (window.Notification && Notification.permission === 'default') Notification.requestPermission(); } catch (e) {}
    }
    emit();
  }

  // The floating window is always on top, so at block start it only has to
  // flash. With no float open and the app in the background, a silent system
  // notification is the "front" cue (the chime is the sound).
  function cueFront(b, next) {
    if (state.pip || !document.hidden) return;
    try {
      if (window.Notification && Notification.permission === 'granted') {
        new Notification('Now: ' + b.title, { body: next ? 'Next ' + fmtTime(next.s) + ' · ' + next.title : '', tag: 'lf-block', silent: true });
      }
    } catch (e) {}
  }

  function tick() {
    rollActions();
    const t = Date.now();
    const { blocks, next } = nowNext(t);
    const ch = ls.get(CHIMED_KEY, { date: localDate(), ids: [] });
    if (ch.date !== localDate()) { ch.date = localDate(); ch.ids = []; }
    const started = blocks.filter((b) => b.s <= t && t - b.s < START_WINDOW_MS && !ch.ids.includes(b.id));
    if (started.length) {
      started.forEach((b) => ch.ids.push(b.id));
      ls.set(CHIMED_KEY, ch);                                       // shared by every LF tab: one chime per block
      const cue = started.filter((b) => b.chime !== false);
      if (cue.length) {
        const b = cue[cue.length - 1];
        state.lastStart = { id: b.id, at: t };
        if (chimeOn()) playChime();
        cueFront(b, next);
      }
    }
    emit();
  }

  // ── Floating now/next window (Document Picture-in-Picture) ────────────────
  async function openFloat() {
    if (!('documentPictureInPicture' in window)) { alert('The floating window needs Chrome or Edge 116+.'); return; }
    if (state.pip) { try { state.pip.focus(); } catch (e) {} return; }
    try {
      const win = await window.documentPictureInPicture.requestWindow({ width: 340, height: 220 });
      [...document.querySelectorAll('style, link[rel="stylesheet"]')].forEach((n) => win.document.head.appendChild(n.cloneNode(true)));
      Object.assign(win.document.body.style, { margin: '0', background: '#050505', color: '#e0e0e0', fontFamily: "'Plus Jakarta Sans', sans-serif", overflow: 'hidden' });
      win.document.title = 'LF · Now';
      win.addEventListener('pagehide', () => { state.pip = null; emit(); });
      state.pip = win;
      unlockAudio();
      emit();
    } catch (e) { console.error('Float failed:', e); }
  }
  function closeFloat() { if (state.pip) { try { state.pip.close(); } catch (e) {} state.pip = null; emit(); } }

  // Which view a phone opens: ?view=today|full wins and is remembered; a narrow
  // screen opens Today unless he chose the full app.
  function initialPhoneView() {
    try {
      const q = new URLSearchParams(location.search).get('view');
      if (q === 'today' || q === 'full') { localStorage.setItem(VIEW_KEY, q); return q; }
    } catch (e) {}
    const narrow = !!(window.matchMedia && window.matchMedia('(max-width: 760px)').matches);
    if (!narrow) return 'full';
    return localStorage.getItem(VIEW_KEY) === 'full' ? 'full' : 'today';
  }
  function setPhoneView(v) { try { localStorage.setItem(VIEW_KEY, v); } catch (e) {} }

  const fmtTime = (ms) => new Date(ms).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });

  setInterval(tick, TICK_MS);
  setInterval(() => { if (!document.hidden) refresh(); }, POLL_MS);
  document.addEventListener('visibilitychange', () => { if (!document.hidden) { refresh(); tick(); } });
  window.addEventListener('online', () => refresh());
  setTimeout(() => { refresh(); tick(); }, 1500);   // after the auth client restores its session

  window.LFToday = {
    refresh, recordAction, nowNext, openFloat, closeFloat, chimeOn, setChime, playChime, initialPhoneView, setPhoneView, scorecardUrl,
    roleInfo, fmtTime, localDate,
    subscribe: (f) => { subs.add(f); return () => subs.delete(f); },
    snapshot: () => state,
  };
})();

// ── React side ────────────────────────────────────────────────────────────────
function useToday() {
  const [, force] = React.useState(0);
  React.useEffect(() => window.LFToday.subscribe(() => force((n) => n + 1)), []);
  const st = window.LFToday.snapshot();
  const t = Date.now();
  return { ...window.LFToday.nowNext(t), t, cache: st.cache, actions: st.actions.map, error: st.error, lastStart: st.lastStart, pip: st.pip, scorecard: st.scorecard };
}

function ScorecardCard({ sc }) {
  const [url, setUrl] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  React.useEffect(() => () => { if (url) URL.revokeObjectURL(url); }, [url]);
  if (!sc) return null;
  const toggle = async () => {
    if (url) { URL.revokeObjectURL(url); setUrl(null); return; }
    setBusy(true);
    setUrl(await window.LFToday.scorecardUrl());
    setBusy(false);
  };
  const label = new Date(sc.date + 'T12:00:00').toLocaleDateString([], { weekday: 'short', day: 'numeric', month: 'short' });
  return (
    <div style={{ borderRadius: 14, border: `1px solid ${T_COL.line}`, background: T_COL.card, overflow: 'hidden' }}>
      <button onClick={toggle} style={{ width: '100%', minHeight: 52, display: 'flex', alignItems: 'center', gap: 10, padding: '0 16px', background: 'transparent', border: 'none', color: T_COL.text, fontSize: 16, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer', textAlign: 'left' }}>
        <span>📊</span><span style={{ flex: 1 }}>Scorecard · week ending {label}</span>
        <span style={{ fontSize: 13, color: T_COL.dim }}>{busy ? '…' : url ? 'Hide' : 'Open'}</span>
      </button>
      {url && <img src={url} alt={'Scorecard, week ending ' + sc.date} style={{ display: 'block', width: '100%', height: 'auto' }} />}
    </div>
  );
}

const T_COL = { bg: '#050505', card: '#0d0d0d', line: '#1c1c1c', dim: '#6b6b6b', text: '#e8e8e8' };
const tRgb = (hex) => { const h = (hex || '#4B5563').replace('#', ''); const n = parseInt(h.length === 3 ? h.split('').map((c) => c + c).join('') : h, 16); return `${(n >> 16) & 255},${(n >> 8) & 255},${n & 255}`; };
const minsLeft = (ms) => Math.max(0, Math.ceil(ms / 60000));
const fmtMins = (m) => (m >= 60 ? `${Math.floor(m / 60)} h ${m % 60 ? (m % 60) + ' min' : ''}`.trim() : `${m} min`);

function dueTone(due, today) {
  if (!due) return null;
  const d = Math.round((Date.parse(due + 'T00:00:00') - Date.parse(today + 'T00:00:00')) / 86400000);
  if (d < 0) return { c: '#EF4444', t: `${-d}d late` };
  if (d === 0) return { c: '#F97316', t: 'today' };
  if (d <= 2) return { c: '#EAB308', t: d === 1 ? 'tomorrow' : `in ${d}d` };
  return { c: T_COL.dim, t: due.slice(5) };
}

function RefChips({ refs, onCopied }) {
  if (!Array.isArray(refs) || !refs.length) return null;
  const copy = async (text) => { try { await navigator.clipboard.writeText(text); onCopied && onCopied('Copied'); } catch (e) { onCopied && onCopied('Copy failed'); } };
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 14 }}>
      {refs.slice(0, 8).map((r, i) => r && r.url
        ? <a key={i} href={r.url} target="_blank" rel="noopener noreferrer" style={chip}>↗ {r.label || r.url}</a>
        : <button key={i} onClick={() => copy(r.path || r.text || '')} style={{ ...chip, cursor: 'pointer' }} title={r.path || r.text}>⧉ {r.label || 'copy'}</button>)}
    </div>
  );
}
const chip = { display: 'inline-flex', alignItems: 'center', gap: 6, minHeight: 36, padding: '6px 12px', borderRadius: 999, border: '1px solid #2a2a2a', background: '#121212', color: '#cfcfcf', fontSize: 14, textDecoration: 'none', fontFamily: 'inherit' };

function NowCard({ now, next, t, act, onCopied, compact }) {
  if (!now) {
    return (
      <div style={{ borderRadius: 16, border: `1px solid ${T_COL.line}`, background: T_COL.card, padding: compact ? 12 : 18 }}>
        <div style={lbl}>NOW</div>
        <div style={{ fontSize: compact ? 16 : 20, fontWeight: 600, marginTop: 6, color: '#bdbdbd' }}>Nothing on the calendar</div>
        {next && <div style={{ fontSize: 14, color: T_COL.dim, marginTop: 4 }}>Free for {fmtMins(minsLeft(next.s - t))}</div>}
      </div>
    );
  }
  const r = window.LFToday.roleInfo(now.role);
  const left = minsLeft(now.e - t);
  const pct = Math.min(100, Math.max(0, ((t - now.s) / Math.max(1, now.e - now.s)) * 100));
  return (
    <div style={{ borderRadius: 16, background: `rgba(${tRgb(r.color)},0.14)`, borderLeft: `5px solid ${r.color}`, padding: compact ? '12px 14px' : '18px 18px 16px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={lbl}>NOW</span>
        {r.label && <span style={{ ...lbl, color: '#a3a3a3' }}>· {r.label}</span>}
        {act && <span style={{ marginLeft: 'auto', fontSize: 12, fontWeight: 700, color: act.action === 'done' ? '#22C55E' : '#a3a3a3' }}>{act.action === 'done' ? '✓ DONE' : '↷ SKIPPED'}</span>}
      </div>
      <div style={{ fontSize: compact ? 18 : 26, fontWeight: 700, lineHeight: 1.2, marginTop: 6, color: T_COL.text }}>{now.title}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: compact ? 6 : 10 }}>
        <span style={{ fontSize: compact ? 24 : 40, fontWeight: 800, fontVariantNumeric: 'tabular-nums', color: T_COL.text }}>{fmtMins(left)}</span>
        <span style={{ fontSize: 14, color: '#9a9a9a' }}>left · until {window.LFToday.fmtTime(now.e)}</span>
      </div>
      <div style={{ height: 4, borderRadius: 4, background: 'rgba(255,255,255,0.08)', marginTop: 10, overflow: 'hidden' }}>
        <div style={{ width: pct + '%', height: '100%', background: r.color }} />
      </div>
      {!compact && <RefChips refs={now.refs} onCopied={onCopied} />}
    </div>
  );
}
const lbl = { fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', color: '#8a8a8a' };

function NextLine({ next, t, compact }) {
  if (!next) return null;
  const r = window.LFToday.roleInfo(next.role);
  const inMin = minsLeft(next.s - t);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: compact ? '8px 4px 0' : '14px 16px', borderRadius: 14, border: compact ? 'none' : `1px solid ${T_COL.line}`, background: compact ? 'transparent' : T_COL.card }}>
      <span style={{ width: 10, height: 10, borderRadius: 999, background: r.color, flexShrink: 0 }} />
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ ...lbl, fontSize: 10 }}>NEXT · {window.LFToday.fmtTime(next.s)} · in {fmtMins(inMin)}</div>
        <div style={{ fontSize: compact ? 14 : 17, fontWeight: 600, color: '#d6d6d6', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{next.title}</div>
      </div>
    </div>
  );
}

function BigButton({ children, onClick, disabled, tone }) {
  const solid = tone === 'go';
  return (
    <button onClick={onClick} disabled={disabled} style={{
      flex: 1, minHeight: 64, borderRadius: 14, fontSize: 18, fontWeight: 700, fontFamily: 'inherit', cursor: disabled ? 'default' : 'pointer',
      border: solid ? 'none' : '1px solid #2e2e2e', background: disabled ? '#111' : (solid ? '#166534' : '#151515'),
      color: disabled ? '#444' : (solid ? '#eafff0' : '#d4d4d4'),
    }}>{children}</button>
  );
}

function TodayScreen({ phone, onFullApp, onRoles }) {
  const { now, next, blocks, t, cache, actions, error, pip, scorecard } = useToday();
  const [projects] = window.useLFState('projects', []);
  const [missionOrder] = window.useLFState('missionOrder', []);
  const [pending, setPending] = React.useState(null);           // { block, action, timer }
  const [toast, setToast] = React.useState('');
  const [capOpen, setCapOpen] = React.useState(false);
  const capRef = React.useRef(null);
  const today = window.LFToday.localDate();
  React.useEffect(() => { window.LFToday.refresh(); }, []);

  const say = (msg) => { setToast(msg); setTimeout(() => setToast((m) => (m === msg ? '' : m)), 2500); };

  // Done / Skip wait 5 s so a mis-tap can be undone before EPFC sees it.
  const act = (action) => {
    if (!now) return;
    if (pending) clearTimeout(pending.timer);
    const block = now;
    const timer = setTimeout(() => { window.LFToday.recordAction(block, action); setPending(null); }, 5000);
    setPending({ block, action, timer });
  };
  const undo = () => { if (pending) { clearTimeout(pending.timer); setPending(null); } };

  const nowAct = now ? (pending && pending.block.id === now.id ? { action: pending.action } : actions[now.id]) : null;

  // Today's LF tasks, in his Mission Control order.
  const rows = [];
  (projects || []).forEach((p) => {
    if (p.archived || p.status === 'archived') return;
    (p.branches || []).forEach((m) => {
      if (m.archived) return;
      (m.leaves || []).forEach((tk) => { if (tk.today) rows.push({ p, m, t: tk, key: `${p.id}:${m.id}:${tk.id}` }); });
    });
  });
  rows.sort((a, b) => {
    const ai = missionOrder.indexOf(a.key), bi = missionOrder.indexOf(b.key);
    if (ai === -1 && bi === -1) return 0; if (ai === -1) return 1; if (bi === -1) return -1; return ai - bi;
  });
  const open = rows.filter((r) => !r.t.done);
  const doneTasks = rows.filter((r) => r.t.done);
  const doneBlocks = blocks.filter((b) => actions[b.id]).map((b) => ({ b, a: actions[b.id] }));

  const saveCapture = () => {
    const text = (capRef.current && capRef.current.value || '').trim();
    if (!text) { setCapOpen(false); return; }
    window.LF.update('inboxItems', (items = []) => [{ id: crypto.randomUUID(), text, type: 'unassigned', urgency: 'medium', images: [], fresh: true }, ...(items || [])]);
    capRef.current.value = '';
    setCapOpen(false);
    say('Saved to Inbox');
  };

  const ageMin = cache && cache.generated_at ? Math.floor((t - Date.parse(cache.generated_at)) / 60000) : null;
  const feedNote = !cache || !cache.feed ? 'No calendar feed yet'
    : (cache.feed.date && cache.feed.date !== today) ? `Feed is from ${cache.feed.date}`
    : (ageMin != null && ageMin > 45) ? `Feed ${ageMin} min old` : null;
  const chimeOn = window.LFToday.chimeOn();
  const pipOk = typeof window !== 'undefined' && 'documentPictureInPicture' in window && !phone;

  return (
    <div style={{ height: phone ? '100dvh' : '100%', overflowY: 'auto', background: T_COL.bg, WebkitOverflowScrolling: 'touch' }}>
      <div style={{ maxWidth: 560, margin: '0 auto', padding: `calc(${phone ? 44 : 14}px + env(safe-area-inset-top)) 16px calc(110px + env(safe-area-inset-bottom))`, display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, minHeight: 40 }}>
          <div>
            <div style={{ fontSize: 20, fontWeight: 800, color: T_COL.text }}>Today</div>
            <div style={{ fontSize: 12, color: T_COL.dim }}>{new Date(t).toLocaleDateString([], { weekday: 'long', day: 'numeric', month: 'short' })}{feedNote ? <span style={{ color: '#d97706' }}> · {feedNote}</span> : null}{error && !feedNote ? <span style={{ color: '#d97706' }}> · offline, last feed</span> : null}</div>
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
            <button onClick={() => window.LFToday.setChime(!chimeOn)} title={chimeOn ? 'Chime on at block start (this device)' : 'Chime off (this device)'} style={iconBtn}>{chimeOn ? '🔔' : '🔕'}</button>
            {pipOk && <button onClick={() => (pip ? window.LFToday.closeFloat() : window.LFToday.openFloat())} title="Floating now/next window, always on top" style={iconBtn}>{pip ? '✕ Float' : '⧉ Float'}</button>}
            {phone && onRoles && <button onClick={onRoles} style={iconBtn}>Roles</button>}
            {phone && onFullApp && <button onClick={onFullApp} style={iconBtn}>Full app</button>}
          </div>
        </div>

        <NowCard now={now} next={next} t={t} act={nowAct} onCopied={say} />
        <div style={{ display: 'flex', gap: 10 }}>
          <BigButton tone="go" onClick={() => act('done')} disabled={!now || !!nowAct}>✓ Done</BigButton>
          <BigButton onClick={() => act('skip')} disabled={!now || !!nowAct}>↷ Skip</BigButton>
        </div>
        <NextLine next={next} t={t} />

        {!capOpen
          ? <BigButton onClick={() => { setCapOpen(true); setTimeout(() => capRef.current && capRef.current.focus(), 30); }}>+ Capture</BigButton>
          : (
            <div style={{ borderRadius: 14, border: `1px solid ${T_COL.line}`, background: T_COL.card, padding: 12 }}>
              <textarea ref={capRef} rows={4} placeholder="Say or type the thought. Your keyboard's mic dictates." style={{ width: '100%', boxSizing: 'border-box', background: '#0a0a0a', color: T_COL.text, border: '1px solid #262626', borderRadius: 10, padding: 12, fontSize: 17, fontFamily: 'inherit', resize: 'vertical' }} />
              <div style={{ display: 'flex', gap: 10, marginTop: 10 }}>
                <BigButton tone="go" onClick={saveCapture}>Save to Inbox</BigButton>
                <BigButton onClick={() => setCapOpen(false)}>Cancel</BigButton>
              </div>
            </div>
          )}

        <ScorecardCard sc={scorecard} />

        <div style={{ ...lbl, marginTop: 10 }}>TODAY'S TASKS · {open.length}</div>
        {!open.length && <div style={{ fontSize: 14, color: T_COL.dim }}>Nothing flagged for today.</div>}
        {open.map((r) => {
          const mc = window.modeOf ? window.modeOf(r.t.mode, r.p.id).color : '#4B5563';
          const due = dueTone(r.t.dueDate, today);
          return (
            <div key={r.key} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 12, background: T_COL.card, border: `1px solid ${T_COL.line}` }}>
              <button onClick={() => window.setTaskDoneCascade(r.p.id, r.m.id, r.t.id, true)} aria-label="Mark done" style={{ width: 32, height: 32, borderRadius: 999, border: '2px solid #3a3a3a', background: 'transparent', cursor: 'pointer', flexShrink: 0 }} />
              <span style={{ width: 8, height: 8, borderRadius: 999, background: mc, flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 0, fontSize: 16, color: T_COL.text, lineHeight: 1.3 }}>{r.t.label}</div>
              {due && <span style={{ fontSize: 12, fontWeight: 700, color: due.c, flexShrink: 0 }}>{due.t}</span>}
            </div>
          );
        })}

        {(doneBlocks.length > 0 || doneTasks.length > 0) && <div style={{ ...lbl, marginTop: 10 }}>DONE</div>}
        {doneBlocks.map(({ b, a }) => (
          <div key={'b' + b.id} style={{ fontSize: 14, color: a.action === 'done' ? '#7a7a7a' : '#5a5a5a', padding: '2px 4px' }}>
            {a.action === 'done' ? '✓' : '↷'} {window.LFToday.fmtTime(b.s)} {b.title}{a.action === 'skip' ? ' (skipped, rolls on)' : ''}
          </div>
        ))}
        {doneTasks.map((r) => (
          <div key={'t' + r.key} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, color: '#6a6a6a', padding: '2px 4px' }}>
            <span style={{ flex: 1, textDecoration: 'line-through' }}>✓ {r.t.label}</span>
            <button onClick={() => window.setTaskDoneCascade(r.p.id, r.m.id, r.t.id, false)} style={{ ...iconBtn, minHeight: 28, fontSize: 12 }}>undo</button>
          </div>
        ))}
      </div>

      {(pending || toast) && (
        <div style={{ position: 'fixed', left: 16, right: 16, bottom: 'calc(18px + env(safe-area-inset-bottom))', maxWidth: 528, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', borderRadius: 14, background: '#1a1a1a', border: '1px solid #2a2a2a', boxShadow: '0 8px 30px rgba(0,0,0,0.6)', zIndex: 50 }}>
          <span style={{ flex: 1, fontSize: 15, color: T_COL.text }}>{pending ? (pending.action === 'done' ? '✓ Done: ' : '↷ Skipped: ') + pending.block.title : toast}</span>
          {pending && <button onClick={undo} style={{ ...iconBtn, fontWeight: 700, color: '#93c5fd' }}>Undo</button>}
        </div>
      )}
    </div>
  );
}
const iconBtn = { minHeight: 36, padding: '0 12px', borderRadius: 10, border: '1px solid #262626', background: '#101010', color: '#cfcfcf', fontSize: 14, fontFamily: 'inherit', cursor: 'pointer' };

// The always-on-top window on the box. Flashes for 20 s when a block starts.
function TodayFloat() {
  const { now, next, t, actions, lastStart } = useToday();
  const flashing = lastStart && t - lastStart.at < 20000;
  const nowAct = now ? actions[now.id] : null;
  return (
    <div style={{ height: '100vh', boxSizing: 'border-box', padding: 10, display: 'flex', flexDirection: 'column', gap: 6, outline: flashing ? '3px solid #FBBF24' : 'none', outlineOffset: -3 }}>
      <NowCard now={now} next={next} t={t} act={nowAct} compact />
      <NextLine next={next} t={t} compact />
      {now && !nowAct && (
        <div style={{ display: 'flex', gap: 6, marginTop: 'auto' }}>
          <button onClick={() => window.LFToday.recordAction(now, 'done')} style={{ ...iconBtn, flex: 1, background: '#166534', border: 'none', color: '#eafff0', fontWeight: 700 }}>✓ Done</button>
          <button onClick={() => window.LFToday.recordAction(now, 'skip')} style={{ ...iconBtn, flex: 1 }}>↷ Skip</button>
        </div>
      )}
    </div>
  );
}

function TodayFloatHost() {
  const { pip } = useToday();
  if (!pip) return null;
  return ReactDOM.createPortal(<TodayFloat />, pip.document.body);
}

window.TodayScreen = TodayScreen;
window.TodayFloatHost = TodayFloatHost;
