/* Workspace Dashboard — a richer landing page for spaces, statuses, queues, members */

function WorkspaceDashboard({ allTasks, onView, onSelectTask, onFilterBy }) {
  const stats = React.useMemo(() => ({
    active:    allTasks.filter(t => t.statusId !== 6 && !t.snoozedUntil).length,
    overdue:   allTasks.filter(t => t.dueDate && dayDelta(t.dueDate) < 0 && t.statusId !== 6).length,
    today:     allTasks.filter(t => t.dueDate && dayDelta(t.dueDate) === 0).length,
    done:      allTasks.filter(t => t.statusId === 6).length,
    members:   D.users.length,
    spaces:    D.spaces.length,
  }), [allTasks]);

  // Status mix data
  const statusMix = D.statuses.map(s => ({
    ...s, count: allTasks.filter(t => t.statusId === s.id).length,
  }));
  const totalForMix = statusMix.reduce((s, r) => s + r.count, 0) || 1;

  return (
    <div style={{ flex: 1, overflowY: 'auto', background: 'rgb(var(--bg))' }}>
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '28px 32px 60px' }}>

        {/* Header */}
        <header style={{ marginBottom: 24 }}>
          <p style={{ margin: 0, fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', color: 'rgb(var(--accent))', textTransform: 'uppercase' }}>Workspace</p>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 4 }}>
            <div>
              <h1 style={{ margin: 0, fontSize: 30, fontWeight: 700, letterSpacing: '-0.025em' }}>Harley Mindcare</h1>
              <p style={{ margin: '6px 0 0', fontSize: 14, color: 'rgb(var(--muted))', maxWidth: 580 }}>
                Everything that lives in this workspace — spaces, statuses, queues, and the people behind them. Click any tile to drill in.
              </p>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => onView('settings')} className="btn btn-secondary" style={{ fontSize: 12.5 }}>⚙ Settings</button>
              <button className="btn btn-accent" style={{ fontSize: 12.5 }}>+ Invite member</button>
            </div>
          </div>
        </header>

        {/* KPI strip */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 12, marginBottom: 24 }}>
          <Kpi label="Active"   n={stats.active}   c="rgb(var(--accent))" soft="rgb(var(--accent-soft))" onClick={() => onView('all')} />
          <Kpi label="Today"    n={stats.today}    c="rgb(var(--warm))"   soft="rgb(var(--warm-soft))"   onClick={() => onView('my-day')} />
          <Kpi label="Overdue"  n={stats.overdue}  c="rgb(var(--brick))"  soft="rgb(var(--brick-soft))"  onClick={() => onView('planned')} />
          <Kpi label="Done"     n={stats.done}     c="rgb(var(--forest))" soft="rgb(var(--forest-soft))" onClick={() => onView('archived')} />
          <Kpi label="Members"  n={stats.members}  c="rgb(var(--navy))"   soft="rgb(var(--navy-soft))"   onClick={() => onView('settings')} />
          <Kpi label="Spaces"   n={stats.spaces}   c="rgb(var(--berry))"  soft="rgb(var(--berry-soft))" />
        </div>

        {/* Spaces grid */}
        <Section title="Spaces" sub="Click a space to scope every view to it." action={<button className="btn btn-secondary" style={{ fontSize: 11.5 }}>+ New space</button>}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
            {D.spaces.map(sp => {
              const tasks = allTasks.filter(t => t.spaceId === sp.id);
              const open  = tasks.filter(t => t.statusId !== 6).length;
              const overdue = tasks.filter(t => t.dueDate && dayDelta(t.dueDate) < 0 && t.statusId !== 6).length;
              const sMix  = D.statuses.map(s => ({ ...s, n: tasks.filter(t => t.statusId === s.id).length }));
              const total = tasks.length || 1;
              return (
                <button key={sp.id} onClick={() => { onFilterBy?.('spaces', sp.id); onView('all'); }} style={{
                  textAlign: 'left', padding: 16,
                  background: 'rgb(var(--surface))',
                  border: '1px solid rgb(var(--rule))', borderRadius: 14,
                  boxShadow: 'var(--sh-sm)',
                  transition: 'box-shadow .14s, border-color .14s, transform .06s',
                  position: 'relative', overflow: 'hidden',
                }}
                  onMouseEnter={e => { e.currentTarget.style.boxShadow = 'var(--sh-md)'; e.currentTarget.style.borderColor = sp.colour + '60'; }}
                  onMouseLeave={e => { e.currentTarget.style.boxShadow = 'var(--sh-sm)'; e.currentTarget.style.borderColor = 'rgb(var(--rule))'; }}>
                  <span style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 4, background: sp.colour }} />
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                    <div style={{
                      width: 38, height: 38, borderRadius: 10,
                      background: sp.colour + '14', color: sp.colour,
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      fontWeight: 700, fontSize: 16,
                    }}>{sp.name.charAt(0)}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 700, color: 'rgb(var(--ink))', letterSpacing: '-0.01em' }}>{sp.name}</div>
                      <div style={{ fontSize: 11, color: 'rgb(var(--muted))', fontFamily: 'JetBrains Mono, monospace' }}>{sp.prefix} · {sp.visibility} · {sp.sla ? `SLA ${sp.sla}d` : 'no SLA'}</div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 10 }}>
                    <span><span className="num" style={{ fontSize: 22, fontWeight: 700, color: 'rgb(var(--ink))', letterSpacing: '-0.02em' }}>{open}</span> <span style={{ fontSize: 11, color: 'rgb(var(--muted))' }}>open</span></span>
                    {overdue > 0 && <span style={{ fontSize: 11, fontWeight: 700, color: 'rgb(var(--brick))', background: 'rgb(var(--brick-soft))', padding: '2px 8px', borderRadius: 999 }}>⚠ {overdue}</span>}
                  </div>
                  {/* Status mix bar */}
                  <div style={{ display: 'flex', height: 6, borderRadius: 999, overflow: 'hidden', background: 'rgb(var(--paper-2))' }}>
                    {sMix.map(s => s.n > 0 && (
                      <span key={s.id} style={{ flex: s.n, background: s.colour }} title={`${s.title} · ${s.n}`} />
                    ))}
                  </div>
                </button>
              );
            })}
          </div>
        </Section>

        {/* Status + queues row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 28 }}>
          <Section title="Global statuses" sub="Across every space.">
            <div style={{ background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', borderRadius: 12, padding: 16, boxShadow: 'var(--sh-sm)' }}>
              {/* Donut */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 14 }}>
                <StatusDonut data={statusMix} total={totalForMix} />
                <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {statusMix.map(s => (
                    <button key={s.id} onClick={() => { onFilterBy?.('statuses', s.id); onView('all'); }}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 8,
                        fontSize: 12, padding: '4px 8px', borderRadius: 6,
                        textAlign: 'left',
                      }}
                      onMouseEnter={e => e.currentTarget.style.background = 'rgb(var(--paper-2))'}
                      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                      <span className="pip" style={{ background: s.colour }} />
                      <span style={{ flex: 1, color: 'rgb(var(--ink-2))', fontWeight: 500 }}>{s.title}</span>
                      <span className="num" style={{ fontWeight: 700, color: 'rgb(var(--ink))' }}>{s.count}</span>
                      <span style={{ fontSize: 10.5, color: 'rgb(var(--muted))', width: 32, textAlign: 'right' }}>{Math.round((s.count/totalForMix)*100)}%</span>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </Section>

          <Section title="Queues" sub="Team inboxes.">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {D.queues.map(q => (
                <button key={q.id} onClick={() => { onFilterBy?.('queues', q.id); onView('all'); }} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '12px 14px',
                  background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
                  borderRadius: 12, boxShadow: 'var(--sh-sm)', textAlign: 'left',
                  transition: 'box-shadow .14s, border-color .14s',
                }}
                  onMouseEnter={e => { e.currentTarget.style.boxShadow = 'var(--sh-md)'; e.currentTarget.style.borderColor = q.colour + '60'; }}
                  onMouseLeave={e => { e.currentTarget.style.boxShadow = 'var(--sh-sm)'; e.currentTarget.style.borderColor = 'rgb(var(--rule))'; }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 10,
                    background: q.colour + '14', color: q.colour,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 14, fontWeight: 700,
                  }}>{q.name.charAt(0)}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700, color: 'rgb(var(--ink))' }}>{q.name}</div>
                    <div style={{ fontSize: 11, color: 'rgb(var(--muted))' }}>{q.members} members</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="num" style={{ fontSize: 18, fontWeight: 700, color: q.colour, letterSpacing: '-0.02em' }}>{q.count}</div>
                    <div style={{ fontSize: 10, color: 'rgb(var(--muted))', letterSpacing: '0.04em', textTransform: 'uppercase', fontWeight: 600 }}>open</div>
                  </div>
                </button>
              ))}
            </div>
          </Section>
        </div>

        {/* Members + tags row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
          <Section title="Members" sub={`${D.users.length} clinicians and admins`}>
            <div style={{ background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', borderRadius: 12, boxShadow: 'var(--sh-sm)', overflow: 'hidden' }}>
              {D.users.map((u, i) => {
                const open = allTasks.filter(t => t.assignees.includes(u.id) && t.statusId !== 6).length;
                return (
                  <div key={u.id} style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '10px 14px',
                    borderTop: i === 0 ? 'none' : '1px solid rgb(var(--rule) / 0.7)',
                  }}>
                    <Avatar user={u} size={28} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>{u.name}</div>
                      <div style={{ fontSize: 11, color: 'rgb(var(--muted))' }}>{u.role}</div>
                    </div>
                    <button onClick={() => onFilterBy?.('assignees', u.id)} style={{
                      fontSize: 11, fontWeight: 600, padding: '3px 10px',
                      background: open > 0 ? u.colour + '14' : 'rgb(var(--paper-2))',
                      color: open > 0 ? u.colour : 'rgb(var(--muted))',
                      borderRadius: 999,
                    }}>{open} open</button>
                  </div>
                );
              })}
            </div>
          </Section>

          <Section title="Tags" sub="Cross-cutting labels.">
            <div style={{ background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', borderRadius: 12, padding: 16, boxShadow: 'var(--sh-sm)' }}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {D.tags.map(t => (
                  <button key={t.id} onClick={() => { onFilterBy?.('tags', t.id); onView('all'); }}
                    style={{
                      display: 'inline-flex', alignItems: 'center', gap: 6,
                      padding: '4px 12px', fontSize: 12, fontWeight: 500,
                      background: t.colour + '14', color: t.colour,
                      borderRadius: 999,
                      transition: 'background-color .12s',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = t.colour + '26'}
                    onMouseLeave={e => e.currentTarget.style.background = t.colour + '14'}>
                    <span style={{ width: 6, height: 6, background: t.colour, borderRadius: '50%' }} />
                    {t.name}
                    <span style={{ opacity: 0.65, fontWeight: 600 }}>{t.count}</span>
                  </button>
                ))}
              </div>
              <p style={{ margin: '16px 0 0', fontSize: 11.5, color: 'rgb(var(--muted))' }}>Tags work as filters across every view — click any chip to scope what you see.</p>
            </div>
          </Section>
        </div>

      </div>
    </div>
  );
}

function Kpi({ label, n, c, soft, onClick }) {
  return (
    <button onClick={onClick} style={{
      textAlign: 'left', padding: '14px 16px',
      background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
      borderRadius: 12, boxShadow: 'var(--sh-sm)', position: 'relative', overflow: 'hidden',
      transition: 'box-shadow .14s, border-color .14s',
      cursor: onClick ? 'pointer' : 'default',
    }}
      onMouseEnter={e => { if (onClick) { e.currentTarget.style.boxShadow = 'var(--sh-md)'; e.currentTarget.style.borderColor = c + '40'; }}}
      onMouseLeave={e => { if (onClick) { e.currentTarget.style.boxShadow = 'var(--sh-sm)'; e.currentTarget.style.borderColor = 'rgb(var(--rule))'; }}}>
      <span style={{ position: 'absolute', top: 0, left: 0, width: 18, height: 3, background: c }} />
      <p style={{ margin: 0, fontSize: 11, fontWeight: 600, color: 'rgb(var(--muted))', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</p>
      <p className="num" style={{ margin: '4px 0 0', fontSize: 26, fontWeight: 700, color: c, letterSpacing: '-0.025em', lineHeight: 1 }}>{n}</p>
    </button>
  );
}

function StatusDonut({ data, total }) {
  let start = 0;
  const cx = 60, cy = 60, r = 44;
  return (
    <svg viewBox="0 0 120 120" width="120" height="120" style={{ flexShrink: 0 }}>
      {data.filter(d => d.count > 0).map(row => {
        const frac = row.count / total;
        const a0 = start * Math.PI * 2 - Math.PI / 2;
        const a1 = (start + frac) * Math.PI * 2 - Math.PI / 2;
        const x0 = cx + r * Math.cos(a0), y0 = cy + r * Math.sin(a0);
        const x1 = cx + r * Math.cos(a1), y1 = cy + r * Math.sin(a1);
        const large = frac > 0.5 ? 1 : 0;
        const d = `M ${cx},${cy} L ${x0},${y0} A ${r},${r} 0 ${large} 1 ${x1},${y1} Z`;
        start += frac;
        return <path key={row.id} d={d} fill={row.colour} stroke="rgb(var(--surface))" strokeWidth="2" />;
      })}
      <circle cx={cx} cy={cy} r={26} fill="rgb(var(--surface))" />
      <text x={cx} y={cy - 2} textAnchor="middle" style={{ fontSize: 16, fontWeight: 700, fill: 'rgb(var(--ink))' }}>{total}</text>
      <text x={cx} y={cy + 12} textAnchor="middle" style={{ fontSize: 8.5, fill: 'rgb(var(--muted))', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>tasks</text>
    </svg>
  );
}

function Section({ title, sub, children, action }) {
  return (
    <section style={{ marginBottom: 28 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 12 }}>
        <h2 style={{ margin: 0, fontSize: 17, fontWeight: 700, letterSpacing: '-0.02em' }}>{title}</h2>
        {sub && <p style={{ margin: 0, fontSize: 12.5, color: 'rgb(var(--muted))' }}>{sub}</p>}
        <span style={{ flex: 1 }} />
        {action}
      </div>
      {children}
    </section>
  );
}

window.WorkspaceDashboard = WorkspaceDashboard;
