// ─────────────────────────────────────────────────────────────
// Corda · Tasks access — "Three ways in" + tradeoff + recommendation
// Real Corda screens (390×844) showing each access pattern, plus
// two wide decision cards. Reuses CAL_TASKS / CAL_PATIENTS / TaskRow.
// ─────────────────────────────────────────────────────────────

// ── Bottom nav (parametric: 4-tab or 5-tab) ───────────────────
const TA_TABS = {
  today:     { label: 'Today',     icon: 'home' },
  calendar:  { label: 'Calendar',  icon: 'calendar' },
  tasks:     { label: 'Tasks',     icon: 'checkCheck' },
  visits:    { label: 'Visits',    icon: 'note' },
  providers: { label: 'Providers', icon: 'stethoscope' },
};

const TANav = ({ ids, active, badge }) => (
  <div style={{
    position: 'absolute', bottom: 0, left: 0, right: 0,
    padding: '10px 6px 26px',
    background: 'linear-gradient(to top, var(--bg) 66%, transparent)',
    display: 'flex', justifyContent: 'space-around', alignItems: 'center', zIndex: 20,
  }}>
    {ids.map(id => {
      const it = TA_TABS[id];
      const isActive = active === id;
      const showBadge = badge && badge[id];
      return (
        <div key={id} style={{
          flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
          color: isActive ? 'var(--sage-deep)' : 'var(--ink-3)', position: 'relative',
        }}>
          <div style={{ position: 'relative' }}>
            <Icon name={it.icon} size={22} color={isActive ? 'var(--sage-deep)' : 'var(--ink-3)'} stroke={isActive ? 1.9 : 1.5} />
            {showBadge && (
              <div style={{
                position: 'absolute', top: -5, right: -9, minWidth: 16, height: 16, padding: '0 4px',
                borderRadius: 999, background: 'oklch(0.58 0.13 40)', color: '#fff',
                fontSize: 10, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center',
                border: '1.5px solid var(--bg)',
              }}>{showBadge}</div>
            )}
          </div>
          <span style={{ fontSize: 10.5, fontWeight: isActive ? 600 : 500, letterSpacing: -0.1 }}>{it.label}</span>
        </div>
      );
    })}
  </div>
);

// ── Add task — ghost button for the app header (replaces the FAB) ──
const TAAddTaskBtn = () => (
  <button style={{
    display: 'inline-flex', alignItems: 'center', gap: 6, height: 36, padding: '0 13px 0 10px',
    borderRadius: 999, background: 'transparent', border: '1px solid var(--hairline)',
    cursor: 'pointer', fontFamily: 'inherit', color: 'var(--sage-deep)', whiteSpace: 'nowrap',
  }}>
    <Icon name="plus" size={16} color="var(--sage-deep)" stroke={2.2} />
    <span style={{ fontSize: 13.5, fontWeight: 600, letterSpacing: '-0.01em' }}>Add task</span>
  </button>
);

// ── Patient filter pill (compact, self-contained) ─────────────
const TAPatientPill = ({ active = 'all' }) => {
  const label = active === 'all' ? 'Both' : CAL_PATIENTS[active].full;
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 8, padding: '4px 12px 4px 4px',
      borderRadius: 999, background: 'var(--surface)', border: '0.5px solid var(--hairline)',
    }}>
      {active === 'all' ? (
        <div style={{ display: 'inline-flex' }}>
          <TJChip id="nana" size={26} />
          <div style={{ marginLeft: -9 }}><TJChip id="papa" size={26} /></div>
        </div>
      ) : <TJChip id={active} size={26} />}
      <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{label}</span>
      <Icon name="chevDown" size={13} color="var(--ink-3)" />
    </div>
  );
};

// ── Compact task row for the "needs you today" strip ──────────
const TAStripRow = ({ task, last }) => {
  const p = CAL_PATIENTS[task.patient];
  const overdue = task.bucket === 'overdue';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0',
      borderBottom: last ? 'none' : '0.5px solid var(--hairline-soft)',
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
        border: `1.6px solid ${overdue ? 'oklch(0.62 0.11 40)' : 'var(--hairline)'}`,
      }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)', letterSpacing: '-0.01em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{task.title}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            <Icon name="clock" size={11} color={overdue ? 'oklch(0.55 0.13 40)' : 'var(--ink-3)'} />
            <span style={{ fontSize: 11, fontWeight: 600, color: overdue ? 'oklch(0.55 0.13 40)' : 'var(--ink-3)' }}>{task.due}</span>
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '1px 8px 1px 3px', borderRadius: 999, background: p.soft }}>
            <TJChip id={task.patient} size={14} />
            <span style={{ fontSize: 10.5, fontWeight: 600, color: p.deep }}>{p.name}</span>
          </span>
        </div>
      </div>
    </div>
  );
};

// ── Today greeting header (shared) ────────────────────────────
const TAGreeting = ({ showAdd }) => (
  <div style={{ padding: '8px 22px 16px' }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
      <TAPatientPill active="all" />
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        {showAdd && <TAAddTaskBtn />}
        <IconBtn name="search" tone="soft" />
        <IconBtn name="bell" tone="soft" />
      </div>
    </div>
    <div style={{ fontSize: 11.5, fontWeight: 500, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 4 }}>Tuesday · May 27</div>
    <CalSerifTitle size={30}>Good morning, Jazmyn</CalSerifTitle>
  </div>
);

// today's appointments mini-list
const TATodayAppts = () => {
  const today = CAL_APPTS.filter(a => a.date === '2026-05-27');
  return (
    <div style={{ padding: '4px 22px 0' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
        <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em' }}>Appointments</div>
        <span style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>{today.length} today</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {today.map(a => {
          const p = CAL_PATIENTS[a.patient]; const pro = CAL_PROVIDERS[a.provider];
          return (
            <div key={a.id} style={{
              display: 'flex', alignItems: 'stretch', gap: 12, background: 'var(--surface)',
              border: '0.5px solid var(--hairline)', borderRadius: 14, padding: '12px 14px 12px 0',
            }}>
              <div style={{ width: 4, borderRadius: 999, background: p.pip, marginLeft: -1 }} />
              <div style={{ width: 52, flexShrink: 0, paddingLeft: 6 }}>
                <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>{a.time}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>{a.dur}</div>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '1px 8px 1px 3px', borderRadius: 999, background: p.soft, marginBottom: 3 }}>
                  <TJChip id={a.patient} size={15} />
                  <span style={{ fontSize: 10.5, fontWeight: 600, color: p.deep }}>{p.name}</span>
                </div>
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)' }}>{pro.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{pro.spec} · {a.loc}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// "Needs you today" tasks strip
const TATaskStrip = ({ prominent }) => {
  const urgent = CAL_TASKS.filter(t => !t.done && (t.bucket === 'overdue' || t.bucket === 'today'));
  return (
    <div style={{ padding: '0 22px', marginTop: prominent ? 4 : 22, marginBottom: 22 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
        <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em', display: 'flex', alignItems: 'center', gap: 8 }}>
          Needs you today
          <span style={{ fontSize: 11, fontWeight: 700, color: '#fff', background: 'oklch(0.58 0.13 40)', borderRadius: 999, padding: '1px 7px' }}>{urgent.length}</span>
        </div>
        <span style={{ fontSize: 13, color: 'var(--sage-deep)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 3 }}>
          All tasks <Icon name="chevron" size={13} color="var(--sage-deep)" />
        </span>
      </div>
      <div style={{ background: 'var(--surface)', border: '0.5px solid var(--hairline)', borderRadius: 16, boxShadow: 'var(--sh-1)', padding: '2px 16px' }}>
        {urgent.map((t, i) => <TAStripRow key={t.id} task={t} last={i === urgent.length - 1} />)}
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────
// DIRECTION A · Today with a 5th tab
// ─────────────────────────────────────────────────────────────
const TAScreenTodayTab = () => (
  <Screen hideNav>
    <div style={{ overflow: 'auto', height: '100%', paddingBottom: 96 }}>
      <TAGreeting />
      <TATodayAppts />
      <TATaskStrip />
    </div>
    <TANav ids={['today', 'calendar', 'tasks', 'providers']} active="today" badge={{ tasks: 3 }} />
  </Screen>
);

// Segmented toggle — Open / Completed ───────────────────────
const TASegment = ({ value, onChange, options }) => (
  <div style={{ display: 'flex', gap: 3, padding: 3, background: 'var(--surface-2)', borderRadius: 12 }}>
    {options.map(o => {
      const on = value === o.id;
      return (
        <button key={o.id} onClick={() => onChange(o.id)} style={{
          flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
          height: 36, borderRadius: 9, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
          fontSize: 13.5, fontWeight: 600,
          background: on ? 'var(--surface)' : 'transparent',
          color: on ? 'var(--ink)' : 'var(--ink-3)',
          boxShadow: on ? 'var(--sh-1)' : 'none',
        }}>
          {o.label}
          <span style={{
            fontSize: 11, fontWeight: 600, color: on ? 'var(--ink-3)' : 'var(--ink-4)',
            background: on ? 'var(--surface-2)' : 'transparent', borderRadius: 999,
            padding: '1px 6px', minWidth: 16, textAlign: 'center',
          }}>{o.count}</span>
        </button>
      );
    })}
  </div>
);

// The Tasks tab home (the triage destination)
const TAScreenTasksHome = ({ initialView = 'open' } = {}) => {
  const [view, setView] = React.useState(initialView);
  const open = CAL_TASKS.filter(t => !t.done);
  const done = CAL_TASKS.filter(t => t.done);
  const overdue = open.filter(t => t.bucket === 'overdue');
  const today = open.filter(t => t.bucket === 'today');
  const week = open.filter(t => t.bucket === 'week');
  const may = done.filter(t => t.completed && t.completed.startsWith('May'));
  const apr = done.filter(t => t.completed && t.completed.startsWith('Apr'));
  const Group = ({ label, items, tone }) => items.length ? (
    <div style={{ marginBottom: 18 }}>
      <TaskGroupLabel count={items.length} tone={tone}>{label}</TaskGroupLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>{items.map(t => <TARowToggle key={t.id} task={t} />)}</div>
    </div>
  ) : null;
  const DoneGroup = ({ label, items }) => items.length ? (
    <div style={{ marginBottom: 20 }}>
      <TaskGroupLabel count={items.length}>{label}</TaskGroupLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{items.map(t => <TADoneRow key={t.id} task={t} />)}</div>
    </div>
  ) : null;
  return (
    <Screen navActive="tasks">
      <div style={{ overflow: 'auto', height: '100%', paddingBottom: 96 }}>
        <div style={{ padding: '8px 22px 0' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', minHeight: 40 }}>
            <div style={{ fontSize: 11.5, fontWeight: 500, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.8 }}>
              {view === 'open' ? `${open.length} open · 2 people` : `${done.length} done · last 30 days`}
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <TAAddTaskBtn />
              <IconBtn name="search" tone="soft" />
            </div>
          </div>
          <div style={{ marginTop: 6 }}><CalSerifTitle size={30}>Tasks</CalSerifTitle></div>
        </div>

        {/* Open / Completed switch */}
        <div style={{ padding: '14px 22px 16px' }}>
          <TASegment value={view} onChange={setView}
            options={[{ id: 'open', label: 'Open', count: open.length }, { id: 'done', label: 'Completed', count: done.length }]} />
        </div>

        {view === 'open' ? (
          <>
            <div style={{ padding: '0 22px 18px' }}><TAPatientPill active="all" /></div>
            <div style={{ padding: '0 22px' }}>
              <Group label="Overdue" items={overdue} tone="oklch(0.50 0.13 40)" />
              <Group label="Today" items={today} />
              <Group label="This week" items={week} />
            </div>
          </>
        ) : (
          <div style={{ padding: '0 22px' }}>
            <DoneGroup label="This month" items={may} />
            <DoneGroup label="April" items={apr} />
            <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-4)', padding: '2px 0 0', lineHeight: 1.5 }}>Completed tasks are kept for your records.</div>
          </div>
        )}
      </div>
    </Screen>
  );
};

// ─────────────────────────────────────────────────────────────
// DIRECTION B · Surfaced on Today only (no dedicated tab)
// ─────────────────────────────────────────────────────────────
const TAScreenTodayInline = () => (
  <Screen hideNav>
    <div style={{ overflow: 'auto', height: '100%', paddingBottom: 96 }}>
      <TAGreeting />
      <TATaskStrip prominent />
      <TATodayAppts />
    </div>
    <TANav ids={['today', 'calendar', 'providers']} active="today" />
  </Screen>
);

// ─────────────────────────────────────────────────────────────
// DIRECTION C · Layered — tab + Today strip + global quick-capture
// ─────────────────────────────────────────────────────────────
const TAScreenLayered = () => (
  <Screen hideNav>
    <div style={{ overflow: 'auto', height: '100%', paddingBottom: 96 }}>
      <TAGreeting showAdd />
      <TATaskStrip prominent />
      <TATodayAppts />
    </div>
    <TANav ids={['today', 'calendar', 'tasks', 'providers']} active="today" badge={{ tasks: 3 }} />
  </Screen>
);

// Global quick-capture sheet (mental note on the go)
const TAScreenQuickCapture = () => {
  const provList = Object.values(CAL_PROVIDERS);
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState('');
  const [picked, setPicked] = React.useState(null);
  const results = provList.filter(pr =>
    (pr.name + ' ' + pr.spec).toLowerCase().includes(query.trim().toLowerCase())
  );

  // Due-date picker — May 2026 (May 1 = Friday, today = Wed 27)
  const SDOW = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  const dueLabel = (d) => d === 27 ? 'Today' : d === 28 ? 'Tomorrow' : `${SDOW[(d + 4) % 7]} ${d}`;
  const [dueOpen, setDueOpen] = React.useState(true);
  const [due, setDue] = React.useState(29); // "Friday" from the captured thought
  const dayCells = [...Array(5).fill(null), ...Array.from({ length: 31 }, (_, i) => i + 1), ...Array(6).fill(null)];
  const closeAll = () => { setOpen(false); setDueOpen(false); };

  return (
  <Screen hideNav>
    {/* dimmed Today behind */}
    <div style={{ height: '100%', opacity: 0.4, filter: 'saturate(0.9)', pointerEvents: 'none' }}>
      <TAGreeting />
      <TATodayAppts />
    </div>
    <div style={{ position: 'absolute', inset: 0, background: 'rgba(20,18,14,.34)', zIndex: 40 }} onClick={closeAll} />
    {/* sheet */}
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 50,
      background: 'var(--bg)', borderRadius: '26px 26px 0 0',
      boxShadow: '0 -12px 40px rgba(40,30,20,.18)', padding: '12px 20px 26px',
    }}>
      <div style={{ width: 38, height: 5, borderRadius: 999, background: 'var(--hairline)', margin: '0 auto 16px' }} />
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
        <span style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 24, letterSpacing: '-0.02em', whiteSpace: 'nowrap' }}>Quick add</span>
        <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink-3)' }}>Done</span>
      </div>

      {/* the captured thought */}
      <div style={{ fontSize: 20, fontWeight: 500, color: 'var(--ink)', letterSpacing: '-0.01em', lineHeight: 1.3, paddingBottom: 16, borderBottom: '0.5px solid var(--hairline)' }}>
        Call pharmacy back Friday — refill not ready
        <span style={{ display: 'inline-block', width: 2, height: 21, background: 'var(--sage-deep)', marginLeft: 2, verticalAlign: 'middle', animation: 'cordaCaret 1.05s step-end infinite' }} />
      </div>

      {/* who is it for — one required tap */}
      <div style={{ marginTop: 18 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.7, marginBottom: 9 }}>For</div>
        <div style={{ display: 'flex', gap: 9 }}>
          {['nana', 'papa'].map(id => {
            const p = CAL_PATIENTS[id]; const sel = id === 'nana';
            return (
              <div key={id} style={{
                flex: 1, display: 'flex', alignItems: 'center', gap: 9, padding: '11px 12px', borderRadius: 14,
                background: sel ? p.soft : 'var(--surface)',
                border: sel ? `1.5px solid ${p.pip}` : '0.5px solid var(--hairline)',
              }}>
                <TJChip id={id} size={26} />
                <span style={{ fontSize: 14.5, fontWeight: 600, color: sel ? p.ink : 'var(--ink-2)' }}>{p.full}</span>
                {sel && <Icon name="check" size={15} color={p.deep} style={{ marginLeft: 'auto' }} />}
              </div>
            );
          })}
        </div>
      </div>

      {/* Details — due date (smart-detected) + provider link */}
      <div style={{ marginTop: 18 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.7, marginBottom: 9 }}>Details</div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', position: 'relative' }}>
          {/* Due date — opens a calendar picker */}
          <div style={{ position: 'relative' }}>
            <span onClick={() => { setDueOpen(v => !v); setOpen(false); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 13px', borderRadius: 999, background: 'var(--sage-tint)', border: dueOpen ? '0.5px solid var(--sage-deep)' : '0.5px solid var(--sage-soft)', fontSize: 13, fontWeight: 600, color: 'var(--sage-ink)', cursor: 'pointer', whiteSpace: 'nowrap' }}>
              <Icon name="clock" size={14} color="var(--sage-deep)" /> Due {dueLabel(due)}
            </span>

            {dueOpen && (
              <div style={{
                position: 'absolute', left: 0, bottom: 'calc(100% + 10px)', width: 286, zIndex: 60,
                background: 'var(--surface)', borderRadius: 16, border: '0.5px solid var(--hairline)',
                boxShadow: '0 12px 32px rgba(40,30,20,.16), 0 2px 8px rgba(40,30,20,.08)', padding: '14px', overflow: 'hidden',
              }}>
                {/* quick options */}
                <div style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
                  {[['Today', 27], ['Tomorrow', 28], ['Friday', 29]].map(([lbl, d]) => {
                    const on = due === d;
                    return (
                      <span key={d} onClick={() => { setDue(d); setDueOpen(false); }} style={{
                        flex: 1, textAlign: 'center', padding: '7px 0', borderRadius: 10, cursor: 'pointer',
                        fontSize: 12.5, fontWeight: 600,
                        background: on ? 'var(--sage-deep)' : 'var(--surface-2)',
                        color: on ? '#fff' : 'var(--ink-2)',
                      }}>{lbl}</span>
                    );
                  })}
                </div>
                {/* month header */}
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', textAlign: 'center', marginBottom: 8 }}>May 2026</div>
                {/* weekday labels */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)' }}>
                  {['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((d, i) => (
                    <div key={i} style={{ textAlign: 'center', fontSize: 10, fontWeight: 600, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.4, paddingBottom: 4 }}>{d}</div>
                  ))}
                </div>
                {/* day grid */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 1 }}>
                  {dayCells.map((d, i) => {
                    if (d === null) return <div key={i} />;
                    const on = due === d; const today = d === 27;
                    return (
                      <div key={i} onClick={() => { setDue(d); setDueOpen(false); }} style={{ display: 'flex', justifyContent: 'center', padding: '1px 0' }}>
                        <div style={{
                          width: 32, height: 32, borderRadius: 999, cursor: 'pointer',
                          display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative',
                          background: on ? 'var(--sage-deep)' : 'transparent',
                        }}>
                          <span style={{ fontSize: 13, fontWeight: on || today ? 600 : 500, color: on ? '#fff' : 'var(--ink-2)' }}>{d}</span>
                          {today && !on && <span style={{ position: 'absolute', bottom: 4, width: 4, height: 4, borderRadius: 999, background: 'var(--sage-deep)' }} />}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}
          </div>

          {/* Provider link — opens a searchable combobox */}
          {picked ? (
            <span onClick={() => { setOpen(true); setDueOpen(false); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 9px 8px 13px', borderRadius: 999, background: 'var(--sage-tint)', border: '0.5px solid var(--sage-soft)', fontSize: 13, fontWeight: 600, color: 'var(--sage-ink)', cursor: 'pointer', whiteSpace: 'nowrap' }}>
              <Icon name="stethoscope" size={14} color="var(--sage-deep)" /> {picked.name}
              <span onClick={(e) => { e.stopPropagation(); setPicked(null); }} style={{ display: 'inline-flex', width: 17, height: 17, borderRadius: 999, background: 'var(--sage-soft)', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="close" size={10} color="var(--sage-deep)" />
              </span>
            </span>
          ) : (
            <span onClick={() => { setOpen(true); setDueOpen(false); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 13px', borderRadius: 999, background: open ? 'var(--surface-2)' : 'var(--surface)', border: '0.5px solid var(--hairline)', fontSize: 13, fontWeight: 500, color: 'var(--ink-2)', cursor: 'pointer', whiteSpace: 'nowrap' }}>
              <Icon name="stethoscope" size={14} color="var(--ink-3)" /> Add provider
            </span>
          )}

          {/* combobox popover (opens upward) */}
          {open && (
            <div style={{
              position: 'absolute', left: 0, bottom: 'calc(100% + 10px)', width: 300, zIndex: 60,
              background: 'var(--surface)', borderRadius: 16, border: '0.5px solid var(--hairline)',
              boxShadow: '0 12px 32px rgba(40,30,20,.16), 0 2px 8px rgba(40,30,20,.08)', overflow: 'hidden',
            }}>
              {/* search field */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '12px 14px', borderBottom: '0.5px solid var(--hairline)' }}>
                <Icon name="search" size={16} color="var(--ink-3)" />
                <span style={{ flex: 1, fontSize: 14.5, fontWeight: 500, color: query ? 'var(--ink)' : 'var(--ink-4)' }}>{query || 'Search providers'}</span>
                <span style={{ width: 2, height: 18, background: 'var(--sage-deep)', animation: 'cordaCaret 1s steps(2) infinite' }} />
              </div>
              {/* results */}
              <div style={{ maxHeight: 232, overflow: 'auto', padding: '6px' }}>
                {results.length === 0 && (
                  <div style={{ padding: '18px 12px', textAlign: 'center', fontSize: 13, color: 'var(--ink-3)' }}>No providers match.</div>
                )}
                {results.map(pr => (
                  <div key={pr.id} onClick={() => { setPicked(pr); setOpen(false); }} style={{
                    display: 'flex', alignItems: 'center', gap: 11, padding: '9px 10px', borderRadius: 11, cursor: 'pointer',
                    background: picked && picked.id === pr.id ? 'var(--sage-tint)' : 'transparent',
                  }}>
                    <Avatar name={pr.name} size={32} tone={pr.tone} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{pr.name}</div>
                      <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{pr.spec}</div>
                    </div>
                    {picked && picked.id === pr.id && <Icon name="check" size={16} color="var(--sage-deep)" />}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>

      <button style={{
        marginTop: 20, width: '100%', height: 52, borderRadius: 15, border: 'none',
        background: 'var(--sage-deep)', color: '#fff', fontSize: 15.5, fontWeight: 600, fontFamily: 'inherit',
      }}>Add task</button>
    </div>
  </Screen>
  );
};

// Contextual "add task" inside a visit (the follow-up path)
const TAScreenAddFromVisit = () => {
  const n = CAL_NOTES[0]; const p = CAL_PATIENTS.nana; const pro = CAL_PROVIDERS.patel;
  return (
    <Screen hideNav bg="var(--bg)">
      <div style={{ padding: '8px 18px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', minHeight: 40 }}>
        <IconBtn name="back" />
        <div style={{ width: 38, height: 38, borderRadius: 999, background: 'var(--sage-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="edit" size={16} color="#fff" />
        </div>
      </div>
      <div style={{ overflow: 'auto', height: 'calc(100% - 48px)', padding: '14px 26px 30px' }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.8 }}>{pro.spec} · {n.type}</div>
        <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 34, letterSpacing: '-0.025em', color: 'var(--ink)', marginTop: 8 }}>{pro.name}</div>
        <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 11px 3px 3px', borderRadius: 999, background: p.soft }}>
            <TJChip id="nana" size={20} />
            <span style={{ fontSize: 12, fontWeight: 600, color: p.deep }}>{p.full}</span>
          </span>
          <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>Thu, May 21</span>
        </div>
        <div style={{ marginTop: 22, marginBottom: 18, width: 28, height: 2, borderRadius: 2, background: 'var(--sage-deep)' }} />
        <div style={{ fontSize: 15.5, lineHeight: 1.7, color: 'var(--ink)' }}>
          Cognition stable since last visit. Tolerating Donepezil well.
          <span style={{ background: 'var(--sage-tint)', borderRadius: 4, padding: '1px 3px', boxShadow: '0 0 0 4px var(--sage-tint)' }}> Move the MRI referral; re-evaluate in early September.</span>
        </div>

        {/* contextual task composer that appeared from the selection */}
        <div style={{
          marginTop: 26, background: 'var(--surface)', borderRadius: 18, border: '0.5px solid var(--hairline)',
          boxShadow: 'var(--sh-2)', padding: '16px 16px 14px', position: 'relative',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
            <div style={{ width: 30, height: 30, borderRadius: 9, background: 'var(--sage-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="checkCheck" size={16} color="var(--sage-deep)" />
            </div>
            <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', whiteSpace: 'nowrap' }}>New task from this visit</span>
          </div>
          <div style={{ fontSize: 15.5, fontWeight: 500, color: 'var(--ink)', lineHeight: 1.35, paddingBottom: 12, borderBottom: '0.5px solid var(--hairline-soft)' }}>
            Confirm MRI referral &amp; book September re-eval
            <span style={{ display: 'inline-block', width: 2, height: 18, background: 'var(--sage-deep)', marginLeft: 2, verticalAlign: 'middle', animation: 'cordaCaret 1.05s step-end infinite' }} />
          </div>
          {/* auto-linked — the payoff of context */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 13, marginBottom: 9 }}>
            <Icon name="check" size={13} color="var(--sage-deep)" />
            <span style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--sage-deep)', textTransform: 'uppercase', letterSpacing: 0.7 }}>Linked from this visit</span>
          </div>
          <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 11px 4px 3px', borderRadius: 999, background: p.soft, whiteSpace: 'nowrap' }}>
              <TJChip id="nana" size={16} /><span style={{ fontSize: 11.5, fontWeight: 600, color: p.deep }}>Nana</span>
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 11px', borderRadius: 999, background: 'var(--surface-2)', border: '0.5px solid var(--hairline)', fontSize: 11.5, fontWeight: 600, color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>
              <Icon name="stethoscope" size={12} color="var(--ink-3)" /> Dr. Patel
            </span>
          </div>
          <button style={{ marginTop: 14, width: '100%', height: 46, borderRadius: 13, border: 'none', background: 'var(--ink)', color: 'var(--bg)', fontSize: 14.5, fontWeight: 600, fontFamily: 'inherit' }}>
            Save to Tasks
          </button>
        </div>
      </div>
    </Screen>
  );
};

// ─────────────────────────────────────────────────────────────
// TRADEOFF MATRIX (wide)
// ─────────────────────────────────────────────────────────────
const TARate = ({ level }) => {
  const map = {
    good:    ['oklch(0.55 0.09 155)', 'var(--sage-tint)', 'Strong'],
    partial: ['oklch(0.62 0.10 75)', 'var(--amber-soft)', 'Partial'],
    poor:    ['oklch(0.58 0.12 40)', 'var(--clay-soft)', 'Weak'],
  };
  const [c, bg, label] = map[level];
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '5px 11px 5px 8px', borderRadius: 999, background: bg }}>
      <span style={{ width: 9, height: 9, borderRadius: '50%', background: c }} />
      <span style={{ fontSize: 12.5, fontWeight: 600, color: c }}>{label}</span>
    </span>
  );
};

function TATradeoff() {
  const rows = [
    { job: 'Glance — "what needs me today?"', note: 'Morning & evening read across both', a: 'partial', b: 'good', c: 'good' },
    { job: 'Capture on the go — "don\u2019t forget"', note: 'On a call, between meetings', a: 'poor', b: 'poor', c: 'good' },
    { job: 'Capture in a visit', note: 'Follow-ups the second they\u2019re said', a: 'poor', b: 'poor', c: 'good' },
    { job: 'Triage — sit-down, everything open', note: 'Tick off, reschedule, plan tomorrow', a: 'good', b: 'partial', c: 'good' },
    { job: 'Nav cost', note: 'Crowding the 4-tab bar', a: 'partial', b: 'good', c: 'partial' },
  ];
  const cols = [
    { key: 'a', t: 'A · A 5th tab', d: 'Tasks joins the nav bar.' },
    { key: 'b', t: 'B · On Today only', d: 'A section + badge, no tab.' },
    { key: 'c', t: 'C · Layered', d: 'Tab + strip + quick-capture.', rec: true },
  ];
  return (
    <div className="w-app" style={{ width: 1180, height: 720, background: 'var(--bg)', boxSizing: 'border-box', padding: '48px 52px', fontFamily: 'var(--font-sans)' }}>
      <TJEyebrow color="var(--sage-deep)">The decision</TJEyebrow>
      <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 44, letterSpacing: '-0.025em', color: 'var(--ink)', marginTop: 8 }}>Three ways in, scored against the day</div>

      <div style={{ marginTop: 30, background: 'var(--surface)', borderRadius: 22, border: '0.5px solid var(--hairline)', boxShadow: 'var(--sh-1)', overflow: 'hidden' }}>
        {/* header row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1fr', borderBottom: '0.5px solid var(--hairline)' }}>
          <div style={{ padding: '20px 24px' }}>
            <TJEyebrow style={{ fontSize: 11 }}>The job to be done</TJEyebrow>
          </div>
          {cols.map(c => (
            <div key={c.key} style={{ padding: '18px 22px', background: c.rec ? 'var(--sage-tint)' : 'transparent', borderLeft: '0.5px solid var(--hairline-soft)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap' }}>
                <span style={{ fontSize: 15.5, fontWeight: 600, color: 'var(--ink)' }}>{c.t}</span>
                {c.rec && <span style={{ fontSize: 9.5, fontWeight: 700, color: '#fff', background: 'var(--sage-deep)', borderRadius: 999, padding: '2px 7px', letterSpacing: 0.5 }}>PICK</span>}
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 3, whiteSpace: 'nowrap' }}>{c.d}</div>
            </div>
          ))}
        </div>
        {/* body rows */}
        {rows.map((r, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1fr', borderBottom: i < rows.length - 1 ? '0.5px solid var(--hairline-soft)' : 'none' }}>
            <div style={{ padding: '16px 24px' }}>
              <div style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--ink)' }}>{r.job}</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>{r.note}</div>
            </div>
            {['a', 'b', 'c'].map(k => (
              <div key={k} style={{ padding: '16px 22px', display: 'flex', alignItems: 'center', background: k === 'c' ? 'var(--sage-tint)' : 'transparent', borderLeft: '0.5px solid var(--hairline-soft)' }}>
                <TARate level={r[k]} />
              </div>
            ))}
          </div>
        ))}
      </div>

      <div style={{ marginTop: 22, fontSize: 14.5, color: 'var(--ink-2)', lineHeight: 1.6, maxWidth: 980 }}>
        A tab nails triage but can’t serve capture; an inline strip gives the glance but neither capture nor deep triage.
        Only the layered model answers every moment in Jazmyn’s day — at the price of one extra tab, which Tasks earns as the app’s single action-center among otherwise read-mostly tabs.
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// RECOMMENDATION (wide)
// ─────────────────────────────────────────────────────────────
function TARecommendation() {
  const layers = [
    { tag: 'Glance', icon: 'home', t: '"Needs you today" on Today', d: 'A compact strip with an urgent count — the at-a-glance layer for morning & evening. Taps through to the home.', moment: 'Morning · ping' },
    { tag: 'Home', icon: 'checkCheck', t: 'A dedicated Tasks tab', d: 'The triage destination: everything open, grouped by urgency, sliceable by Nana or Papa. Where she sits down and plans.', moment: 'Evening' },
    { tag: 'Capture', icon: 'plus', t: 'Quick-add, everywhere', d: 'A global "+" reachable from any screen for mental notes — plus an in-context "add task" inside a visit that auto-links the patient & doctor.', moment: 'On a call · in a visit' },
  ];
  return (
    <div className="w-app" style={{ width: 1180, height: 640, background: 'var(--ink)', boxSizing: 'border-box', padding: '48px 52px', fontFamily: 'var(--font-sans)', color: 'var(--bg)' }}>
      <TJEyebrow color="var(--sage)">Recommendation</TJEyebrow>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 8 }}>
        <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 46, letterSpacing: '-0.025em', color: 'var(--bg)', lineHeight: 1 }}>
          Layer it: glance, home, capture.
        </div>
        <div style={{ fontSize: 14, color: 'rgba(244,241,234,0.7)', maxWidth: 320, lineHeight: 1.55, textAlign: 'right' }}>
          Tasks gets a tab <em style={{ fontFamily: 'var(--font-serif)' }}>and</em> a capture path that travels with her — each layer answers a different moment.
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18, marginTop: 36 }}>
        {layers.map((l, i) => (
          <div key={i} style={{ background: 'rgba(244,241,234,0.05)', border: '0.5px solid rgba(244,241,234,0.14)', borderRadius: 20, padding: '24px 22px', position: 'relative' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ width: 44, height: 44, borderRadius: 13, background: 'var(--sage)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name={l.icon} size={22} color="var(--ink)" stroke={2} />
              </div>
              <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--sage)', letterSpacing: 1, textTransform: 'uppercase' }}>{l.tag}</span>
            </div>
            <div style={{ fontSize: 19, fontWeight: 600, color: 'var(--bg)', marginTop: 18, letterSpacing: '-0.01em', lineHeight: 1.2 }}>{l.t}</div>
            <div style={{ fontSize: 13.5, color: 'rgba(244,241,234,0.72)', marginTop: 10, lineHeight: 1.55 }}>{l.d}</div>
            <div style={{ marginTop: 16, paddingTop: 14, borderTop: '0.5px solid rgba(244,241,234,0.14)', fontSize: 12, color: 'rgba(244,241,234,0.55)', display: 'flex', alignItems: 'center', gap: 7 }}>
              <Icon name="clock" size={13} color="var(--sage)" /> Serves: {l.moment}
            </div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 30, display: 'flex', alignItems: 'center', gap: 14, padding: '18px 22px', background: 'rgba(244,241,234,0.06)', borderRadius: 16 }}>
        <div style={{ width: 34, height: 34, borderRadius: 999, background: 'var(--sage)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="check" size={18} color="var(--ink)" stroke={2.4} />
        </div>
        <div style={{ fontSize: 14.5, color: 'rgba(244,241,234,0.85)', lineHeight: 1.55 }}>
          <strong style={{ color: 'var(--bg)' }}>On the 5th tab:</strong> yes. With Today, Calendar, Visits & Providers all read-mostly, Tasks is the one place Jazmyn <em style={{ fontFamily: 'var(--font-serif)' }}>acts</em> — that earns permanent real estate. Five is the practical ceiling; we stop here.
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Task row with a working checkbox — tap the circle to complete.
// ─────────────────────────────────────────────────────────────
const TARowToggle = ({ task, showPatient = true }) => {
  const [done, setDone] = React.useState(!!task.done);
  return <TaskRow task={{ ...task, done }} showPatient={showPatient} onToggleDone={() => setDone(d => !d)} />;
};

// ── Completed-task row (archive list item) ───────────────────
const TADoneRow = ({ task }) => {
  const p = CAL_PATIENTS[task.patient];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: 'var(--surface)', border: '0.5px solid var(--hairline)', borderRadius: 14 }}>
      <TaskCheck done tone="var(--sage-deep)" size={22} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14.5, fontWeight: 500, color: 'var(--ink-3)', textDecoration: 'line-through', textDecorationColor: 'var(--ink-4)', lineHeight: 1.3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{task.title}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 5 }}>
          <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>Completed {task.completed}</span>
          <span style={{ width: 3, height: 3, borderRadius: 999, background: 'var(--ink-4)' }} />
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: p.pip }} />
            <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{p.name}</span>
          </span>
        </div>
      </div>
      <button style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '6px 10px', borderRadius: 999, border: '0.5px solid var(--hairline)', background: 'var(--surface)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 600, color: 'var(--ink-3)' }}>
        <Icon name="refill" size={12} color="var(--ink-3)" /> Undo
      </button>
    </div>
  );
};

// ── Archive / completed screen ───────────────────────────────
const TAScreenArchive = () => {
  const done = CAL_TASKS.filter(t => t.done);
  const may = done.filter(t => t.completed && t.completed.startsWith('May'));
  const apr = done.filter(t => t.completed && t.completed.startsWith('Apr'));
  const Section = ({ label, items }) => items.length ? (
    <div style={{ marginBottom: 22 }}>
      <TaskGroupLabel count={items.length}>{label}</TaskGroupLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{items.map(t => <TADoneRow key={t.id} task={t} />)}</div>
    </div>
  ) : null;
  return (
    <Screen hideNav>
      <div style={{ overflow: 'auto', height: '100%', paddingBottom: 96 }}>
        <div style={{ padding: '8px 18px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between', minHeight: 40 }}>
          <IconBtn name="back" />
          <IconBtn name="search" tone="soft" />
        </div>
        <div style={{ padding: '14px 22px 4px' }}>
          <CalSerifTitle size={30}>Completed</CalSerifTitle>
          <div style={{ fontSize: 13.5, color: 'var(--ink-2)', marginTop: 5 }}>{done.length} done · last 30 days</div>
        </div>
        <div style={{ padding: '18px 22px 0' }}>
          <Section label="This month" items={may} />
          <Section label="April" items={apr} />
          <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-4)', padding: '2px 0 0', lineHeight: 1.5 }}>Completed tasks are kept for your records.</div>
        </div>
      </div>
      <TANav ids={['today', 'calendar', 'tasks', 'providers']} active="tasks" />
    </Screen>
  );
};

Object.assign(window, {
  TANav, TAAddTaskBtn, TASegment, TAScreenTodayTab, TAScreenTasksHome, TAScreenTodayInline,
  TAScreenLayered, TAScreenQuickCapture, TAScreenAddFromVisit,
  TARowToggle, TADoneRow, TAScreenArchive,
  TATradeoff, TARecommendation,
});
