// ─────────────────────────────────────────────────────────────
// Corda · Tasks — caregiving to-dos, each linked to a patient and
// (optionally) a provider and a medication. The associations are
// the point: a task is never floating — it belongs to someone's
// care, and often to a specific doctor or prescription.
//
// Data + shared atoms live here; screens in cal-tasks-screens.jsx.
// ─────────────────────────────────────────────────────────────

// Medications — keyed; mirrors what the visit notes reference.
const CAL_MEDS = {
  donepezil:  { id: 'donepezil',  name: 'Donepezil',  brand: 'Aricept', dose: '10 mg', freq: 'Evening',     patient: 'nana', provider: 'patel' },
  memantine:  { id: 'memantine',  name: 'Memantine',  brand: 'Namenda', dose: '10 mg', freq: 'Twice daily', patient: 'nana', provider: 'patel' },
  lisinopril: { id: 'lisinopril', name: 'Lisinopril', brand: null,      dose: '5 mg',  freq: 'Morning',     patient: 'papa', provider: 'reyes' },
};

// Tasks — bucket drives grouping + due color.
// bucket: 'overdue' | 'today' | 'week' | 'later'
const CAL_TASKS = [
  { id: 't1', title: 'Refill Donepezil prescription', patient: 'nana',
    provider: 'patel', med: 'donepezil', due: '4 days left', bucket: 'overdue', done: false,
    note: 'Mission Bay Pharmacy can refill. Request online or call ahead for pickup.' },
  { id: 't2', title: 'Call Dr. Patel about September follow-up', patient: 'nana',
    provider: 'patel', med: null, due: 'Today', bucket: 'today', done: false,
    note: 'Confirm the early-September re-evaluation and whether the MRI referral went out.' },
  { id: 't3', title: 'Log Papa\u2019s blood pressure readings', patient: 'papa',
    provider: 'reyes', med: 'lisinopril', due: 'Today', bucket: 'today', done: false,
    note: 'Weekly home cuff — Dr. Reyes wants the log before the 6-week re-check.' },
  { id: 't4', title: 'Pick up lab results from Quest', patient: 'papa',
    provider: 'williams', med: null, due: 'Fri, May 29', bucket: 'week', done: false, note: null },
  { id: 't5', title: 'Ask Tomás about flat shoes for walking practice', patient: 'nana',
    provider: 'tomas', med: null, due: 'This week', bucket: 'week', done: false, note: null },
  { id: 't6', title: 'Schedule Papa\u2019s pneumonia booster', patient: 'papa',
    provider: 'williams', med: null, due: 'Early Sept', bucket: 'later', done: false, note: null },
  { id: 't7', title: 'Move Donepezil dosing to evening', patient: 'nana',
    provider: 'patel', med: 'donepezil', due: 'May 7', bucket: 'done', done: true, completed: 'May 7', note: null },
  { id: 't8', title: 'Put down bathroom mat to prevent falls', patient: 'nana',
    provider: null, med: null, due: 'May 4', bucket: 'done', done: true, completed: 'May 4', note: null },
  { id: 't9', title: 'Confirm cardiology referral for Papa', patient: 'papa',
    provider: 'reyes', med: null, due: 'May 2', bucket: 'done', done: true, completed: 'May 2', note: null },
  { id: 't10', title: 'Log Papa’s blood pressure for week one', patient: 'papa',
    provider: 'reyes', med: 'lisinopril', due: 'Apr 30', bucket: 'done', done: true, completed: 'Apr 30', note: null },
  { id: 't11', title: 'Pick up new reading glasses', patient: 'papa',
    provider: 'yang', med: null, due: 'Apr 26', bucket: 'done', done: true, completed: 'Apr 26', note: null },
  { id: 't12', title: 'Send Nana’s updated med list to Dr. Patel', patient: 'nana',
    provider: 'patel', med: 'donepezil', due: 'Apr 22', bucket: 'done', done: true, completed: 'Apr 22', note: null },
  { id: 't13', title: 'Order grab bars for the shower', patient: 'nana',
    provider: null, med: null, due: 'Apr 18', bucket: 'done', done: true, completed: 'Apr 18', note: null },
];

// Due-date color by bucket
const taskDueColor = (bucket) =>
  bucket === 'overdue' ? 'oklch(0.50 0.13 40)'
  : bucket === 'today' ? 'var(--sage-deep)'
  : bucket === 'week'  ? 'var(--ink-2)'
  : 'var(--ink-3)';

// ── Round checkbox ────────────────────────────────────────────
const TaskCheck = ({ done, tone = 'var(--sage-deep)', size = 24 }) => (
  <div style={{
    width: size, height: size, borderRadius: '50%', flexShrink: 0,
    border: done ? 'none' : `1.6px solid var(--hairline)`,
    background: done ? tone : 'transparent',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    boxShadow: done ? 'none' : 'inset 0 1px 1px rgba(40,30,20,.03)',
  }}>
    {done && <Icon name="check" size={size * 0.62} color="#fff" stroke={2.6} />}
  </div>
);

// ── Association chip — patient / provider / medication ────────
// Each links a task to one of the three entities.
const TaskAssocChip = ({ kind, label }) => {
  if (kind === 'patient') return null; // patient shown via the color rail + name pill
  const icon = kind === 'provider' ? 'stethoscope' : 'pill';
  return (
    <span className={kind === 'med' ? 'cc-med-assoc' : undefined} style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '3px 9px 3px 7px', borderRadius: 999,
      background: 'var(--surface-2)', border: '0.5px solid var(--hairline)',
      fontSize: 11.5, fontWeight: 500, color: 'var(--ink-2)', maxWidth: '100%',
    }}>
      <Icon name={icon} size={12} color="var(--ink-3)" />
      <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
    </span>
  );
};

// ── Task row — list item ──────────────────────────────────────
const TaskRow = ({ task, showPatient = true, onToggleDone }) => {
  const p   = CAL_PATIENTS[task.patient];
  const pro = task.provider ? CAL_PROVIDERS[task.provider] : null;
  const med = task.med ? CAL_MEDS[task.med] : null;
  const dueC = taskDueColor(task.bucket);
  const checkTone = task.bucket === 'overdue' ? 'oklch(0.55 0.13 40)' : 'var(--sage-deep)';

  return (
    <div style={{
      display: 'flex', alignItems: 'stretch', gap: 0,
      background: 'var(--surface)', border: '0.5px solid var(--hairline)',
      borderRadius: 16, boxShadow: 'var(--sh-1)', overflow: 'hidden',
      opacity: task.done ? 0.66 : 1,
    }}>
      {/* patient color rail */}
      <div style={{ width: 4, background: p.pip, flexShrink: 0 }} />

      <div style={{ flex: 1, minWidth: 0, padding: '13px 14px 12px', display: 'flex', gap: 12 }}>
        <div style={{ paddingTop: 1 }}>
          {onToggleDone ? (
            <button
              onClick={onToggleDone}
              onPointerDown={(e) => e.stopPropagation()}
              style={{ background: 'transparent', border: 'none', padding: 0, cursor: 'pointer', display: 'flex' }}
              aria-label={task.done ? 'Mark not done' : 'Mark complete'}
            >
              <TaskCheck done={task.done} tone={checkTone} />
            </button>
          ) : (
            <TaskCheck done={task.done} tone={checkTone} />
          )}
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 15, fontWeight: 500, color: task.done ? 'var(--ink-3)' : 'var(--ink)',
            lineHeight: 1.3, letterSpacing: '-0.01em', marginBottom: 8,
            textDecoration: task.done ? 'line-through' : 'none',
            textDecorationColor: 'var(--ink-4)',
          }}>{task.title}</div>

          {/* due + associations */}
          <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 6 }}>
            {!task.done && (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginRight: 1 }}>
                <Icon name="clock" size={12} color={dueC} />
                <span style={{ fontSize: 11.5, fontWeight: 600, color: dueC, letterSpacing: 0.1 }}>{task.due}</span>
              </span>
            )}
            {showPatient && (
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                padding: '2px 9px 2px 3px', borderRadius: 999, background: p.soft,
              }}>
                <CalPatientChip p={p} size={15} />
                <span style={{ fontSize: 11, fontWeight: 600, color: p.deep, letterSpacing: 0.2 }}>{p.name}</span>
              </span>
            )}
            {pro && <TaskAssocChip kind="provider" label={pro.name.replace('Dr. ', 'Dr ')} />}
            {med && <TaskAssocChip kind="med" label={`${med.name} ${med.dose}`} />}
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Section label with count ──────────────────────────────────
const TaskGroupLabel = ({ children, count, tone }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '0 0 11px' }}>
    <span style={{
      fontSize: 11.5, fontWeight: 600, color: tone || 'var(--ink-3)',
      textTransform: 'uppercase', letterSpacing: 0.8,
    }}>{children}</span>
    {count != null && (
      <span style={{
        fontSize: 11, fontWeight: 600, color: 'var(--ink-3)',
        background: 'var(--surface-2)', borderRadius: 999, padding: '1px 7px',
        minWidth: 18, textAlign: 'center',
      }}>{count}</span>
    )}
  </div>
);

Object.assign(window, {
  CAL_MEDS, CAL_TASKS, taskDueColor,
  TaskCheck, TaskAssocChip, TaskRow, TaskGroupLabel,
});
