// AUTOMATION — TASKS sub-platform (5 tabs: Dashboard · Kanban · By Matter · By Workflow · Activity)
const { useState: useTspState, useMemo: useTspMemo } = React;
const Ttsp = window.ArbiterTokens;

// ── Kanban view ──────────────────────────────────────────────────────────
function AutoTasksKanban({ data }) {
  const au = window.__au;
  const columns = ['To Do', 'In Progress', 'Waiting', 'Blocked', 'Scheduled', 'Completed'];
  const byStatus = {};
  columns.forEach(c => byStatus[c] = data.tasks.filter(t => t.status === c));

  return (
    <div>
      <AuHero
        accent={au.cobalt} bg={au.cobaltBg}
        title="Tasks — kanban board"
        description={<>Drag-and-drop columns across status. {columns.map(c => `${c}: ${byStatus[c].length}`).join(' · ')}.</>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${columns.length}, 1fr)`, gap: '10px', alignItems: 'flex-start' }}>
        {columns.map(col => {
          const sc = au.statusColor(col);
          const items = byStatus[col];
          return (
            <div key={col} style={{ background: Ttsp.color.bg.card, border: `1px solid ${Ttsp.color.border.light}`, borderRadius: Ttsp.radius.lg, overflow: 'hidden' }}>
              <div style={{ padding: '10px 12px', borderBottom: `1px solid ${Ttsp.color.border.light}`, borderTop: `3px solid ${sc.color}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: '11px', fontWeight: 700, color: sc.color, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{col}</span>
                <span style={{ fontSize: '11px', fontFamily: Ttsp.font.mono, color: sc.color, fontWeight: 700 }}>{items.length}</span>
              </div>
              <div style={{ maxHeight: '620px', overflowY: 'auto' }}>
                {items.length === 0 && (
                  <div role="status" style={{ padding: '16px', textAlign: 'center', fontSize: '10px', color: Ttsp.color.text.tertiary, fontStyle: 'italic' }}>No tasks</div>
                )}
                {items.map(t => {
                  const pc = au.priorityColor(t.priority);
                  const overdue = t.dueDate < '2026-04-20' && col !== 'Completed' && col !== 'Cancelled';
                  return (
                    <div key={t.id} style={{ padding: '10px 12px', borderBottom: `1px solid ${Ttsp.color.border.light}`, borderLeft: `3px solid ${pc.color}`, cursor: 'pointer' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                        <span style={{ fontSize: '10px', fontFamily: Ttsp.font.mono, color: au.lime, fontWeight: 700 }}>{t.id}</span>
                        <span style={{ ...au.tag, background: pc.bg, color: pc.color, fontSize: '9px' }}>{t.priority}</span>
                      </div>
                      <div style={{ fontSize: '11px', fontWeight: 600, color: Ttsp.color.text.primary, lineHeight: 1.35, marginBottom: '6px' }}>{t.title}</div>
                      <div style={{ fontSize: '10px', color: Ttsp.color.text.tertiary, marginBottom: '5px' }}>{t.matter}</div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: '10px', fontFamily: Ttsp.font.mono }}>
                        <span style={{ color: overdue ? au.crimson : Ttsp.color.text.tertiary, fontWeight: overdue ? 700 : 400 }}>{t.dueDate}</span>
                        <span style={{ color: Ttsp.color.text.tertiary }}>{t.assignee}</span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── By Matter ────────────────────────────────────────────────────────────
function AutoTasksByMatter({ data }) {
  const au = window.__au;
  const groups = {};
  data.tasks.forEach(t => {
    const key = t.matter || 'Unassigned';
    if (!groups[key]) groups[key] = [];
    groups[key].push(t);
  });
  const sorted = Object.entries(groups).sort((a, b) => b[1].length - a[1].length);

  return (
    <div>
      <AuHero
        accent={au.violet} bg={au.violetBg}
        title={`Tasks — grouped by matter (${sorted.length})`}
        description={<>Per-matter task load with hour budget vs. spent. Heaviest: <b style={{ color: au.crimson }}>{sorted[0]?.[0] || '—'}</b> with <b style={{ fontFamily: Ttsp.font.mono }}>{sorted[0]?.[1].length || 0}</b> tasks.</>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Matters w/ tasks</span><span style={au.statValue}>{sorted.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Avg tasks / matter</span><span style={au.statValue}>{(data.tasks.length / sorted.length).toFixed(1)}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Heaviest matter</span><span style={{ ...au.statValue, color: au.crimson }}>{sorted[0]?.[1].length || 0}</span><span style={{ ...au.statDelta, color: Ttsp.color.text.tertiary, fontSize: '10px' }}>{sorted[0]?.[0] || '—'}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Total hours budgeted</span><span style={au.statValue}>{data.tasks.reduce((s, t) => s + t.estHours, 0)}h</span></div>
      </div>

      {sorted.map(([matter, tasks]) => {
        const openCount = tasks.filter(t => t.status !== 'Completed' && t.status !== 'Cancelled').length;
        const overdueCount = tasks.filter(t => t.status !== 'Completed' && t.status !== 'Cancelled' && t.dueDate < '2026-04-20').length;
        const totalHrs = tasks.reduce((s, t) => s + t.estHours, 0);
        const spent = tasks.reduce((s, t) => s + t.spentHours, 0);
        return (
          <div key={matter} style={au.card}>
            <div style={au.cardH}>
              <span style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <span style={{ color: Ttsp.color.text.primary, fontWeight: 700, fontSize: '13px' }}>{matter}</span>
                <span style={{ ...au.tag, background: Ttsp.color.bg.secondary, color: Ttsp.color.text.secondary }}>{tasks.length} tasks</span>
                {overdueCount > 0 && <span style={{ ...au.tag, background: 'rgba(185,28,28,0.08)', color: au.crimson }}>{overdueCount} overdue</span>}
              </span>
              <span style={{ fontSize: '10px', color: Ttsp.color.text.tertiary, fontFamily: Ttsp.font.mono, fontWeight: 500 }}>
                {openCount} open · {spent}/{totalHrs}h
              </span>
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr>
                  <th style={au.th}>ID</th>
                  <th style={au.th}>Title</th>
                  <th style={au.th}>Assignee</th>
                  <th style={au.th}>Priority</th>
                  <th style={au.th}>Status</th>
                  <th style={au.th}>Due</th>
                  <th style={{ ...au.th, textAlign: 'right' }}>Hrs</th>
                </tr>
              </thead>
              <tbody>
                {tasks.sort((a, b) => a.dueDate.localeCompare(b.dueDate)).map(t => {
                  const ss = au.statusColor(t.status);
                  const pc = au.priorityColor(t.priority);
                  const overdue = t.dueDate < '2026-04-20' && t.status !== 'Completed' && t.status !== 'Cancelled';
                  return (
                    <tr key={t.id}>
                      <td style={{ ...au.td, fontFamily: Ttsp.font.mono, color: au.lime, fontWeight: 700 }}>{t.id}</td>
                      <td style={{ ...au.td, fontWeight: 600, color: Ttsp.color.text.primary, maxWidth: '340px' }}>{t.title}</td>
                      <td style={{ ...au.td, fontSize: '11px', color: Ttsp.color.text.secondary }}>{t.assignee}</td>
                      <td style={au.td}><span style={{ ...au.tag, background: pc.bg, color: pc.color }}>{t.priority}</span></td>
                      <td style={au.td}><span style={{ ...au.tag, background: ss.bg, color: ss.color }}>{t.status}</span></td>
                      <td style={{ ...au.td, fontFamily: Ttsp.font.mono, fontSize: '11px', color: overdue ? au.crimson : Ttsp.color.text.primary, fontWeight: overdue ? 700 : 400 }}>{t.dueDate}</td>
                      <td style={{ ...au.td, textAlign: 'right', fontFamily: Ttsp.font.mono, fontSize: '11px', color: Ttsp.color.text.secondary }}>{t.spentHours}/{t.estHours}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        );
      })}
    </div>
  );
}

// ── By Workflow ──────────────────────────────────────────────────────────
function AutoTasksByWorkflow({ data }) {
  const au = window.__au;
  const groups = {};
  data.tasks.forEach(t => {
    const key = t.workflow || 'Ad-hoc';
    if (!groups[key]) groups[key] = [];
    groups[key].push(t);
  });
  const sorted = Object.entries(groups).sort((a, b) => b[1].length - a[1].length);

  return (
    <div>
      <AuHero
        accent={au.teal} bg={au.tealBg}
        title="Tasks — grouped by workflow"
        description={<>Automation ratio — share of tasks driven by a named workflow vs. ad-hoc. <b style={{ color: au.emerald, fontFamily: Ttsp.font.mono }}>{Math.round((1 - ((groups['Ad-hoc'] || []).length / data.tasks.length)) * 100)}%</b> are workflow-driven.</>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Workflows w/ tasks</span><span style={au.statValue}>{sorted.filter(([k]) => k !== 'Ad-hoc').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Ad-hoc tasks</span><span style={au.statValue}>{(groups['Ad-hoc'] || []).length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Most-used workflow</span><span style={{ ...au.statValue, color: au.lime, fontSize: '14px' }}>{sorted[0]?.[0] || '—'}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Automation ratio</span><span style={{ ...au.statValue, color: au.emerald }}>{Math.round((1 - ((groups['Ad-hoc'] || []).length / data.tasks.length)) * 100)}%</span><span style={{ ...au.statDelta, color: Ttsp.color.text.tertiary }}>workflow-driven</span></div>
      </div>

      {sorted.map(([wf, tasks]) => {
        const openCount = tasks.filter(t => t.status !== 'Completed' && t.status !== 'Cancelled').length;
        return (
          <div key={wf} style={au.card}>
            <div style={au.cardH}>
              <span style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <span style={{ fontFamily: Ttsp.font.mono, color: Ttsp.color.text.primary, fontWeight: 700, fontSize: '13px' }}>{wf}</span>
                <span style={{ ...au.tag, background: Ttsp.color.bg.secondary, color: Ttsp.color.text.secondary }}>{tasks.length} tasks</span>
                {openCount > 0 && <span style={{ ...au.tag, background: au.statusColor('In Progress').bg, color: au.statusColor('In Progress').color }}>{openCount} open</span>}
              </span>
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr>
                  <th style={au.th}>ID</th>
                  <th style={au.th}>Title</th>
                  <th style={au.th}>Matter</th>
                  <th style={au.th}>Assignee</th>
                  <th style={au.th}>Priority</th>
                  <th style={au.th}>Status</th>
                  <th style={au.th}>Due</th>
                </tr>
              </thead>
              <tbody>
                {tasks.map(t => {
                  const ss = au.statusColor(t.status);
                  const pc = au.priorityColor(t.priority);
                  return (
                    <tr key={t.id}>
                      <td style={{ ...au.td, fontFamily: Ttsp.font.mono, color: au.lime, fontWeight: 700 }}>{t.id}</td>
                      <td style={{ ...au.td, fontWeight: 600, color: Ttsp.color.text.primary, maxWidth: '300px' }}>{t.title}</td>
                      <td style={{ ...au.td, fontSize: '11px', color: Ttsp.color.text.secondary, maxWidth: '160px' }}>{t.matter}</td>
                      <td style={{ ...au.td, fontSize: '11px', color: Ttsp.color.text.secondary }}>{t.assignee}</td>
                      <td style={au.td}><span style={{ ...au.tag, background: pc.bg, color: pc.color }}>{t.priority}</span></td>
                      <td style={au.td}><span style={{ ...au.tag, background: ss.bg, color: ss.color }}>{t.status}</span></td>
                      <td style={{ ...au.td, fontFamily: Ttsp.font.mono, fontSize: '11px' }}>{t.dueDate}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        );
      })}
    </div>
  );
}

// ── Tasks Activity ───────────────────────────────────────────────────────
function AutoTasksActivity({ data }) {
  const au = window.__au;
  const taskActivity = data.activity.filter(a => a.action.toLowerCase().includes('task') || a.target.toLowerCase().includes('task') || a.target.match(/^T-/));
  const fallback = taskActivity.length > 0 ? taskActivity : data.activity;

  return (
    <div>
      <AuHero
        accent={au.slate} bg={au.slateBg}
        title="Task activity stream"
        description={<>Task-related events filtered from the platform activity stream. <b style={{ fontFamily: Ttsp.font.mono }}>{fallback.length}</b> entries.</>}
      />
      <div style={au.card}>
        <div style={au.cardH}>
          <span>Task activity stream — {fallback.length}</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: '5px', fontSize: '10px', color: au.emerald, fontWeight: 600 }}><span style={{ width: '6px', height: '6px', background: au.emerald, borderRadius: '50%' }} />LIVE</span>
        </div>
        <div>
          {fallback.map(a => {
            const sev = a.severity === 'warn' ? au.amber : a.severity === 'critical' ? au.crimson : au.lime;
            return (
              <div key={a.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${Ttsp.color.border.light}`, borderLeft: `3px solid ${sev}`, display: 'grid', gridTemplateColumns: '90px 140px 1fr 1fr', gap: '12px', alignItems: 'center' }}>
                <span style={{ fontFamily: Ttsp.font.mono, fontSize: '10px', color: Ttsp.color.text.tertiary }}>{a.time}</span>
                <span style={{ fontSize: '11px', fontWeight: 600, color: Ttsp.color.text.primary }}>{a.actor}</span>
                <span style={{ fontSize: '11px', color: Ttsp.color.text.secondary }}>{a.action}</span>
                <span style={{ fontSize: '11px', color: Ttsp.color.text.primary, fontWeight: 500 }}>{a.target}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── Platform entry ───────────────────────────────────────────────────────
function AutoTasksPlatform() {
  const [subTab, setSubTab] = useTspState('dashboard');
  const au = window.__au;
  const data = window.AUTO_DATA;

  const subTabs = [
    { id: 'dashboard',   label: 'Dashboard' },
    { id: 'kanban',      label: 'Kanban' },
    { id: 'by-matter',   label: 'By Matter' },
    { id: 'by-workflow', label: 'By Workflow' },
    { id: 'activity',    label: 'Activity' },
  ];

  const renderSub = () => {
    switch (subTab) {
      case 'dashboard':   return <AutoTasks           data={data} />;
      case 'kanban':      return <AutoTasksKanban     data={data} />;
      case 'by-matter':   return <AutoTasksByMatter   data={data} />;
      case 'by-workflow': return <AutoTasksByWorkflow data={data} />;
      case 'activity':    return <AutoTasksActivity   data={data} />;
      default:            return <AutoTasks           data={data} />;
    }
  };

  return (
    <div>
      <AuSubNav views={subTabs} active={subTab} onChange={setSubTab} accent={au.lime} />
      {renderSub()}
    </div>
  );
}

window.AutoTasksKanban     = AutoTasksKanban;
window.AutoTasksByMatter   = AutoTasksByMatter;
window.AutoTasksByWorkflow = AutoTasksByWorkflow;
window.AutoTasksActivity   = AutoTasksActivity;
window.AutoTasksPlatform   = AutoTasksPlatform;
