// ─── Roles (PM-060 Life OS) ───
// Each role lists its open tasks grouped by quadrant, urgent-important first.
// Quadrant is DERIVED (his rule: never a field) from priority + due date:
//   Q1 = High, due in 2 days or less (overdue included)
//   Q2 = High, due later or undated
//   Q3 = Medium or Low with a due date
//   Q4 = Medium or Low, no due date
// Weekly % = done this week ÷ (done this week + open due this week), Mon-Sun.
// A task's role comes from window.roleIdOf (its own role, its old mode's role,
// else its project's default); tasks with none sit under Unassigned.
// Streak counters arrive with the habit sync (PM-066, op streaks_put).

const RQ_LABEL = { 1: 'Q1 · high, due ≤ 2 days', 2: 'Q2 · high, later', 3: 'Q3 · dated', 4: 'Q4 · undated' };

function rolesIsoDay(d) { return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; }
function rolesWeek(now = new Date()) {
  const d = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const start = new Date(d); start.setDate(d.getDate() - ((d.getDay() + 6) % 7));     // Monday
  const end = new Date(start); end.setDate(start.getDate() + 7);                      // next Monday
  const last = new Date(end); last.setDate(end.getDate() - 1);
  return { startMs: start.getTime(), endMs: end.getTime(), startISO: rolesIsoDay(start), lastISO: rolesIsoDay(last) };
}
function rolesQuadrant(t, todayISO) {
  const pri = t.priority || 'medium';
  if (pri === 'high') {
    if (t.dueDate && (Date.parse(t.dueDate + 'T00:00:00') - Date.parse(todayISO + 'T00:00:00')) / 86400000 <= 2) return 1;
    return 2;
  }
  return t.dueDate ? 3 : 4;
}

function RolesScreen({ phone, onBack }) {
  const [projects] = window.useLFState('projects', []);
  window.useLFState('projectRoles', null);   // re-render when project defaults change (Settings → Edit roles)
  const [showEmpty, setShowEmpty] = React.useState(false);

  const todayISO = rolesIsoDay(new Date());
  const wk = rolesWeek();
  const roles = [...(window.MODES || []), window.UNASSIGNED_ROLE];
  const by = {};
  roles.forEach((r) => { by[r.id] = { role: r, open: [], doneWk: 0, openDueWk: 0 }; });

  (projects || []).forEach((p) => {
    if (p.archived || p.status === 'archived') return;
    (p.branches || []).forEach((m) => {
      if (m.archived) return;
      (m.leaves || []).forEach((t) => {
        const rid = window.roleIdOf(t.mode, p.id);
        const g = by[rid] || by.unassigned;
        const doneAt = Number(t.done_changed_at) || 0;
        if (t.done) { if (doneAt >= wk.startMs && doneAt < wk.endMs) g.doneWk++; return; }
        if (t.dueDate && t.dueDate >= wk.startISO && t.dueDate <= wk.lastISO) g.openDueWk++;
        g.open.push({ p, m, t, q: rolesQuadrant(t, todayISO) });
      });
    });
  });

  const PRI = { high: 0, medium: 1, low: 2 };
  const sortRows = (a, b) => (a.q - b.q)
    || ((a.t.dueDate || '9999') < (b.t.dueDate || '9999') ? -1 : (a.t.dueDate || '9999') > (b.t.dueDate || '9999') ? 1 : 0)
    || ((PRI[a.t.priority || 'medium'] ?? 1) - (PRI[b.t.priority || 'medium'] ?? 1))
    || String(a.t.label || '').localeCompare(String(b.t.label || ''));

  const sections = roles.map((r) => by[r.id]).filter((g) => g.open.length || g.doneWk || g.openDueWk);
  const empty = roles.filter((r) => !r.hidden && r.id !== 'unassigned' && !sections.includes(by[r.id]));

  return (
    <div style={{ height: phone ? '100dvh' : '100%', overflowY: 'auto', background: '#050505' }}>
      <div style={{ maxWidth: phone ? 560 : 1400, margin: '0 auto', padding: phone ? 'calc(44px + env(safe-area-inset-top)) 16px 40px' : '4px 0 40px' }}>
        {phone && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
            <button onClick={onBack} style={rBtn}>‹ Today</button>
            <div style={{ fontSize: 20, fontWeight: 800, color: '#e8e8e8' }}>Roles</div>
          </div>
        )}
        <div style={{ fontSize: 12, color: '#6b6b6b', marginBottom: 12 }}>
          Week of {wk.startISO} · % = done this week ÷ (done + open due this week)
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: phone ? 'minmax(0, 1fr)' : 'repeat(auto-fill, minmax(min(360px, 100%), 1fr))', gap: 14, alignItems: 'start' }}>
          {sections.map((g) => <RoleCard key={g.role.id} g={g} sortRows={sortRows} />)}
        </div>
        {empty.length > 0 && (
          <div style={{ marginTop: 16, fontSize: 12, color: '#555' }}>
            <button onClick={() => setShowEmpty((v) => !v)} style={{ ...rBtn, minHeight: 28, fontSize: 12 }}>{showEmpty ? 'Hide' : 'Show'} roles with no tasks ({empty.length})</button>
            {showEmpty && <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 8 }}>{empty.map((r) => (
              <span key={r.id} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: '#777' }}><span style={{ width: 8, height: 8, borderRadius: 999, background: r.color }} />{r.label}</span>
            ))}</div>}
          </div>
        )}
      </div>
    </div>
  );
}

// Q1 always shows in full; longer quadrants show 5 and fold the rest, so a
// role with 90 open tasks stays a glance, not a wall.
const RQ_FOLD = 5;
function RoleCard({ g, sortRows }) {
  const r = g.role;
  const den = g.doneWk + g.openDueWk;
  const pct = den ? Math.round((g.doneWk / den) * 100) : null;
  const [unfold, setUnfold] = React.useState({});
  const sorted = [...g.open].sort(sortRows);
  const seen = {}; const hidden = {};
  const rows = sorted.filter(({ q }) => {
    seen[q] = (seen[q] || 0) + 1;
    if (q === 1 || unfold[q] || seen[q] <= RQ_FOLD) return true;
    hidden[q] = (hidden[q] || 0) + 1; return false;
  });
  const lastOfQ = {}; rows.forEach((row, i) => { lastOfQ[row.q] = i; });
  let lastQ = 0;
  return (
    <div style={{ minWidth: 0, borderRadius: 14, background: '#0b0b0c', border: '1px solid #181818', borderTop: `3px solid ${r.color}`, padding: '12px 14px' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span style={{ fontSize: 15, fontWeight: 700, color: '#e8e8e8', flex: 1, minWidth: 0 }}>{r.label}</span>
        <span style={{ fontSize: 12, color: '#777', flexShrink: 0 }}>{g.open.length} open</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
        <div style={{ flex: 1, height: 5, borderRadius: 5, background: '#1a1a1a', overflow: 'hidden' }}>
          <div style={{ width: (pct || 0) + '%', height: '100%', background: r.color }} />
        </div>
        <span style={{ fontSize: 11, color: '#8a8a8a', fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>
          {pct == null ? 'nothing due this week' : `${pct}% · ${g.doneWk}/${den}`}
        </span>
      </div>
      <div style={{ marginTop: 6 }}>
        {rows.map(({ p, m, t, q }, i) => {
          const head = q !== lastQ; lastQ = q;
          const uc = window.urgencyColor ? window.urgencyColor(t.dueDate) : null;
          const dl = window.formatDueLabel ? window.formatDueLabel(t.dueDate) : (t.dueDate || '');
          return (
            <React.Fragment key={t.id}>
              {head && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '10px 0 4px' }}>
                  <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.1em', color: '#5a5a5a', textTransform: 'uppercase', flexShrink: 0 }}>{RQ_LABEL[q]}</span>
                  <span style={{ flex: 1, height: 1, background: '#1c1c1c' }} />
                </div>
              )}
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '5px 2px' }}>
                <button onClick={() => window.setTaskDoneCascade(p.id, m.id, t.id, true)} aria-label="Mark done" title="Mark done"
                  style={{ width: 18, height: 18, borderRadius: 999, border: '1.5px solid #3a3a3a', background: 'transparent', cursor: 'pointer', flexShrink: 0, padding: 0 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, color: '#dcdcdc', lineHeight: 1.3 }}>{t.label}</div>
                  <div style={{ fontSize: 10.5, color: '#555', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name} · {m.label}</div>
                </div>
                {t.dueDate && <span style={{ fontSize: 11, fontWeight: 700, color: uc || '#6b6b6b', flexShrink: 0 }}>{dl}</span>}
              </div>
              {lastOfQ[q] === i && hidden[q] > 0 && (
                <button onClick={() => setUnfold((u) => ({ ...u, [q]: true }))}
                  style={{ margin: '2px 0 4px 28px', padding: '4px 0', background: 'transparent', border: 'none', color: '#777', fontSize: 12, fontFamily: 'inherit', cursor: 'pointer' }}>+ {hidden[q]} more</button>
              )}
            </React.Fragment>
          );
        })}
        {!rows.length && <div style={{ fontSize: 12, color: '#555', marginTop: 8 }}>No open tasks.</div>}
      </div>
    </div>
  );
}
const rBtn = { minHeight: 36, padding: '0 12px', borderRadius: 10, border: '1px solid #262626', background: '#101010', color: '#cfcfcf', fontSize: 14, fontFamily: 'inherit', cursor: 'pointer' };

window.RolesScreen = RolesScreen;
