/* Person deep-dive modal + Task templates */

function PersonModal({ userId, allTasks, onClose, onOpenTask }) {
  if (!userId) return null;
  const u = userById(userId);
  if (!u) return null;

  const myTasks = allTasks.filter(t => t.assignees.includes(userId));
  const myOpen  = myTasks.filter(t => t.statusId !== 6);
  const myOverdue = myOpen.filter(t => t.dueDate && dayDelta(t.dueDate) < 0);
  const myToday   = myOpen.filter(t => t.dueDate && dayDelta(t.dueDate) === 0);
  const totalEstWeek = myOpen.filter(t => t.dueDate && dayDelta(t.dueDate) >= 0 && dayDelta(t.dueDate) <= 7).reduce((s, t) => s + (t.estimateMins || 0), 0);
  const totalLog = myTasks.reduce((s, t) => s + (t.actualMins || 0), 0);

  // 7-day schedule
  const days = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(TODAY); d.setDate(d.getDate() + i);
    const iso = d.toISOString().slice(0, 10);
    return { d, iso, tasks: myOpen.filter(t => t.dueDate === iso) };
  });

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.45)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 230, padding: 32,
    }}>
      <div onClick={e => e.stopPropagation()} className="fadein shadow-pop" style={{
        background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
        borderRadius: 16, width: 780, maxHeight: '86vh', overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
      }}>
        {/* Hero */}
        <div style={{
          padding: '24px 26px',
          background: `linear-gradient(135deg, ${u.colour}22, transparent 60%)`,
          borderBottom: '1px solid rgb(var(--rule))',
          display: 'flex', alignItems: 'center', gap: 18,
        }}>
          <Avatar user={u} size={64} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <h2 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: '-0.025em' }}>{u.name}</h2>
            <p style={{ margin: '2px 0 0', fontSize: 13, color: 'rgb(var(--muted))' }}>{u.role} · Harley Mindcare</p>
            <div style={{ marginTop: 10, display: 'flex', gap: 6 }}>
              <button className="btn btn-secondary" style={{ fontSize: 11.5, padding: '4px 12px' }}>Message</button>
              <button className="btn btn-secondary" style={{ fontSize: 11.5, padding: '4px 12px' }}>Assign…</button>
            </div>
          </div>
          <button onClick={onClose} style={{ fontSize: 22, color: 'rgb(var(--muted))', padding: '0 8px', borderRadius: 6, lineHeight: 1, alignSelf: 'flex-start' }}>×</button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
          {/* KPI strip */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 22 }}>
            <PKpi n={myOpen.length}      l="Open"        c={u.colour} />
            <PKpi n={myToday.length}     l="Due today"   c="rgb(var(--accent))" />
            <PKpi n={myOverdue.length}   l="Overdue"     c="rgb(var(--brick))" />
            <PKpi n={fmtMins(totalEstWeek) || '0m'} l="This week est." c="rgb(var(--forest))" isText />
          </div>

          {/* 7-day schedule */}
          <h3 style={{ margin: '0 0 10px', fontSize: 13, fontWeight: 700, color: 'rgb(var(--muted))', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Next 7 days</h3>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 8, marginBottom: 24 }}>
            {days.map(({ d, iso, tasks }) => {
              const isToday = d.toDateString() === TODAY.toDateString();
              return (
                <div key={iso} style={{
                  padding: 10,
                  background: isToday ? 'rgb(var(--accent-soft) / 0.5)' : 'rgb(var(--paper-2) / 0.5)',
                  borderRadius: 10, minHeight: 90,
                  border: '1px solid ' + (isToday ? 'rgb(var(--accent) / 0.3)' : 'rgb(var(--rule))'),
                }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
                    <span style={{ fontSize: 10.5, fontWeight: 700, color: isToday ? 'rgb(var(--accent))' : 'rgb(var(--muted))', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{d.toLocaleDateString('en-GB', { weekday: 'short' })}</span>
                    <span style={{ fontSize: 11, color: 'rgb(var(--muted))', fontFamily: 'JetBrains Mono, monospace' }}>{d.getDate()}</span>
                  </div>
                  {tasks.length === 0 && <span style={{ fontSize: 10, color: 'rgb(var(--rule-2))' }}>—</span>}
                  {tasks.slice(0, 3).map(t => (
                    <button key={t.id} onClick={() => { onOpenTask(t.id); onClose(); }} style={{
                      display: 'block', width: '100%', textAlign: 'left',
                      fontSize: 10.5, padding: '3px 6px',
                      background: 'rgb(var(--surface))',
                      borderRadius: 4, marginBottom: 3,
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                      fontWeight: 500, color: 'rgb(var(--ink-2))',
                    }}>{t.title}</button>
                  ))}
                  {tasks.length > 3 && <span style={{ fontSize: 9.5, color: 'rgb(var(--muted))' }}>+{tasks.length - 3} more</span>}
                </div>
              );
            })}
          </div>

          {/* Active tasks */}
          <h3 style={{ margin: '0 0 10px', fontSize: 13, fontWeight: 700, color: 'rgb(var(--muted))', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Active tasks · {myOpen.length}</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {myOpen.slice(0, 8).map(t => {
              const sp = spaceById(t.spaceId);
              return (
                <button key={t.id} onClick={() => { onOpenTask(t.id); onClose(); }} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  width: '100%', textAlign: 'left', padding: '9px 12px',
                  background: 'rgb(var(--paper-2) / 0.4)', borderRadius: 8,
                  transition: 'background .12s',
                }}
                  onMouseEnter={e => e.currentTarget.style.background = 'rgb(var(--paper-2))'}
                  onMouseLeave={e => e.currentTarget.style.background = 'rgb(var(--paper-2) / 0.4)'}>
                  <PriorityDot p={t.priority} />
                  <span style={{ flex: 1, fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: 'rgb(var(--ink))' }}>{t.title}</span>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color: 'rgb(var(--muted))' }}>
                    <span style={{ width: 6, height: 6, background: sp.colour, borderRadius: 2 }} />{sp.prefix}
                  </span>
                  {t.dueDate && <DueChip iso={t.dueDate} />}
                </button>
              );
            })}
            {myOpen.length === 0 && <p style={{ fontSize: 12.5, color: 'rgb(var(--muted))', fontStyle: 'italic', textAlign: 'center', padding: 16 }}>Nothing on their plate right now.</p>}
          </div>
        </div>
      </div>
    </div>
  );
}

function PKpi({ n, l, c, isText }) {
  return (
    <div style={{
      padding: '12px 14px',
      background: 'rgb(var(--paper-2) / 0.5)',
      borderRadius: 10,
    }}>
      <div className="num" style={{ fontSize: isText ? 18 : 22, fontWeight: 700, color: c, letterSpacing: '-0.025em', lineHeight: 1 }}>{n}</div>
      <div style={{ fontSize: 10.5, fontWeight: 600, color: 'rgb(var(--muted))', marginTop: 4, letterSpacing: '0.05em', textTransform: 'uppercase' }}>{l}</div>
    </div>
  );
}

/* ─────────── Task templates ─────────── */
const TASK_TEMPLATES = [
  {
    id: 'new-referral',
    name: 'New referral intake',
    desc: 'Triage a fresh referral end-to-end',
    glyph: '➜', tint: 'rgb(var(--accent))',
    spaceId: 1, type: 'referral', priority: 'high',
    titlePlaceholder: 'Triage referral — [patient name]',
    tags: [],
    checklist: [
      'Identity & GP details verified',
      'Consent recorded',
      'Initial risk screen completed',
      'Allocated to clinician',
      'Acknowledgement letter sent',
      'First assessment booked',
    ],
    estimateMins: 45,
  },
  {
    id: 'discharge',
    name: 'Discharge summary',
    desc: 'Close-out a course of treatment',
    glyph: '✓', tint: 'rgb(var(--forest))',
    spaceId: 2, type: 'task', priority: 'medium',
    titlePlaceholder: 'Discharge — [patient name]',
    tags: [2],
    checklist: [
      'Final session notes complete',
      'PHQ-9 / GAD-7 follow-up scored',
      'GP letter drafted',
      'Letter signed off by clinical lead',
      'Final invoice raised',
      'Patient record archived',
    ],
    estimateMins: 40,
  },
  {
    id: 'insurance-followup',
    name: 'Insurance follow-up',
    desc: 'Chase outstanding claim through provider',
    glyph: '£', tint: 'rgb(var(--warm))',
    spaceId: 3, type: 'task', priority: 'high',
    titlePlaceholder: 'Chase [insurer] — [patient]',
    tags: [3],
    checklist: [
      'EOB on file',
      'Provider relations contacted',
      'Response logged',
      'Escalation needed?',
      'Invoice resent or paid',
    ],
    estimateMins: 25,
  },
  {
    id: 'safeguarding',
    name: 'Safeguarding escalation',
    desc: 'Risk amber/red — protocol triggered',
    glyph: '⚠', tint: 'rgb(var(--brick))',
    spaceId: 2, type: 'incident', priority: 'urgent',
    titlePlaceholder: 'Risk follow-up — [patient]',
    tags: [4, 1],
    checklist: [
      'Patient or trusted contact reached',
      'Co-clinician notified',
      'Safety plan refreshed',
      'Logged in safeguarding register',
      'Manager informed',
      '24h review scheduled',
    ],
    estimateMins: 60,
  },
  {
    id: 'audit-prep',
    name: 'Quarterly audit prep',
    desc: 'Gather evidence for an upcoming audit',
    glyph: '⌬', tint: 'rgb(var(--navy))',
    spaceId: 4, type: 'audit', priority: 'medium',
    titlePlaceholder: 'Q[?] audit — evidence pack',
    tags: [],
    checklist: [
      'Access logs exported',
      'DSAR tracker reconciled',
      'Retention proofs bundled',
      'Sub-processor list refreshed',
      'Incident log reviewed',
      'Findings circulated',
    ],
    estimateMins: 480,
  },
  {
    id: 'rota',
    name: 'Monthly rota',
    desc: 'Cover preferences + publish',
    glyph: '☰', tint: 'rgb(var(--accent))',
    spaceId: 5, type: 'admin', priority: 'medium',
    titlePlaceholder: '[Month] rota — collect & publish',
    tags: [],
    checklist: [
      'Survey sent to clinicians',
      'Conflicts identified',
      'Cover gaps resolved',
      'Rota drafted',
      'Approval from clinical lead',
      'Published to team',
    ],
    estimateMins: 90,
  },
];

function TemplatePicker({ open, onClose, onPick }) {
  if (!open) return null;
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const h = () => setTick(t => t + 1);
    window.addEventListener('taskhub-templates-changed', h);
    return () => window.removeEventListener('taskhub-templates-changed', h);
  }, []);
  const templates = getTaskTemplates();
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.4)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 220, padding: 32,
    }}>
      <div onClick={e => e.stopPropagation()} className="fadein shadow-pop" style={{
        background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
        borderRadius: 16, width: 780, maxHeight: '82vh', overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ padding: '18px 24px', borderBottom: '1px solid rgb(var(--rule))', display: 'flex', alignItems: 'center' }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>New task from template</h3>
            <p style={{ margin: '3px 0 0', fontSize: 12.5, color: 'rgb(var(--muted))' }}>Pre-built clinical workflows · pick one to start from</p>
          </div>
          <span style={{ flex: 1 }} />
          <button onClick={onClose} style={{ fontSize: 22, color: 'rgb(var(--muted))', padding: '0 8px', borderRadius: 6, lineHeight: 1 }}>×</button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: 20, display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
          <button onClick={() => onPick(null)} style={{
            textAlign: 'left', padding: 16,
            background: 'rgb(var(--surface))',
            border: '1.5px dashed rgb(var(--rule-2))', borderRadius: 12,
            transition: 'border-color .12s, box-shadow .12s',
          }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = 'rgb(var(--accent))'; e.currentTarget.style.boxShadow = '0 0 0 3px rgb(var(--accent) / 0.12)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'rgb(var(--rule-2))'; e.currentTarget.style.boxShadow = 'none'; }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10,
              background: 'rgb(var(--paper-2))', color: 'rgb(var(--muted))',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 16, marginBottom: 10,
            }}>+</div>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'rgb(var(--ink))' }}>Blank task</div>
            <div style={{ fontSize: 12, color: 'rgb(var(--muted))', marginTop: 3 }}>Start from scratch.</div>
          </button>
          {templates.map(t => (
            <button key={t.id} onClick={() => onPick(t)} style={{
              textAlign: 'left', padding: 16,
              background: 'rgb(var(--surface))',
              border: '1px solid rgb(var(--rule))', borderRadius: 12,
              transition: 'border-color .12s, box-shadow .12s',
            }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = t.tint; e.currentTarget.style.boxShadow = `0 0 0 3px ${t.tint}1f`; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'rgb(var(--rule))'; e.currentTarget.style.boxShadow = 'none'; }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10,
                background: t.tint + '14', color: t.tint,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 16, fontWeight: 700, marginBottom: 10,
              }}>{t.glyph}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: 'rgb(var(--ink))' }}>{t.name}</div>
                <span style={{ fontSize: 10, fontWeight: 600, color: 'rgb(var(--muted))', padding: '1px 7px', background: 'rgb(var(--paper-2))', borderRadius: 999 }}>{t.checklist.length} steps</span>
              </div>
              <div style={{ fontSize: 12, color: 'rgb(var(--muted))', marginTop: 3 }}>{t.desc}</div>
              <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: 'rgb(var(--muted))' }}>
                <span>{spaceById(t.spaceId)?.name}</span>
                <span>·</span>
                <PriorityDot p={t.priority} /> {t.priority}
                <span>·</span>
                <span>{fmtMins(t.estimateMins)}</span>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

window.TASK_TEMPLATES = TASK_TEMPLATES;

function getTaskTemplates() {
  try {
    const stored = JSON.parse(localStorage.getItem('tashhub-task-templates') || 'null');
    if (Array.isArray(stored)) return stored;
  } catch (e) {}
  return TASK_TEMPLATES;
}
function saveTaskTemplates(arr) {
  try { localStorage.setItem('tashhub-task-templates', JSON.stringify(arr)); } catch (e) {}
  window.dispatchEvent(new Event('taskhub-templates-changed'));
}
Object.assign(window, { PersonModal, TemplatePicker, getTaskTemplates, saveTaskTemplates });
