// AUTOMATION PLATFORM — My Queue + Analytics tabs
const Tauq = window.ArbiterTokens;

function AutoMyQueue({ data }) {
  const au = window.__au;
  // "Me" = L. Torres (matches other platforms' convention)
  const ME = 'L. Torres';
  const myTasks = data.tasks.filter(t => t.assignee === ME);
  const myActive = myTasks.filter(t => t.status !== 'Completed' && t.status !== 'Cancelled');
  const myOverdue = myActive.filter(t => t.dueDate < '2026-04-20');
  const myDueThisWeek = myActive.filter(t => t.dueDate >= '2026-04-20' && t.dueDate <= '2026-04-26');
  const myRuns = data.workflowRuns.filter(r => r.startedBy === ME);
  const mySucceeded = myTasks.filter(t => t.status === 'Completed').length;

  return (
    <div>
      <AuHero
        accent={au.lime} bg={au.limeBg}
        title={`My queue — ${ME}`}
        description={<>
          Everything assigned to me across tasks and workflow runs. <b style={{ fontFamily: Tauq.font.mono }}>{myActive.length}</b> open · <b style={{ color: au.amber, fontFamily: Tauq.font.mono }}>{myDueThisWeek.length}</b> due this week · <b style={{ color: au.crimson, fontFamily: Tauq.font.mono }}>{myOverdue.length}</b> overdue.
        </>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>My open tasks</span><span style={{ ...au.statValue, color: au.cobalt }}>{myActive.length}</span><span style={{ ...au.statDelta, color: Tauq.color.text.tertiary }}>{myTasks.length} total</span></div>
        <div style={au.stat}><span style={au.statLabel}>Due this week</span><span style={{ ...au.statValue, color: au.amber }}>{myDueThisWeek.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Overdue</span><span style={{ ...au.statValue, color: au.crimson }}>{myOverdue.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>My runs</span><span style={au.statValue}>{myRuns.length}</span><span style={{ ...au.statDelta, color: Tauq.color.text.tertiary }}>active workflows</span></div>
        <div style={au.stat}><span style={au.statLabel}>Completed YTD</span><span style={{ ...au.statValue, color: au.emerald }}>{mySucceeded}</span></div>
      </div>

      {myOverdue.length > 0 && (
        <div style={{ ...au.card, borderColor: 'rgba(185,28,28,0.22)' }}>
          <div style={{ ...au.cardH, color: au.crimson, background: 'rgba(185,28,28,0.04)' }}>! Overdue — requires immediate attention</div>
          <div>
            {myOverdue.map(t => (
              <div key={t.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${Tauq.color.border.light}`, borderLeft: `3px solid ${au.crimson}`, display: 'flex', gap: '16px', alignItems: 'center' }}>
                <span style={{ fontFamily: Tauq.font.mono, fontSize: '11px', color: au.crimson, fontWeight: 700, minWidth: '90px' }}>{t.dueDate}</span>
                <span style={{ ...au.tag, background: au.priorityColor(t.priority).bg, color: au.priorityColor(t.priority).color, minWidth: '40px', justifyContent: 'center' }}>{t.priority}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: '12px', fontWeight: 600, color: Tauq.color.text.primary }}>{t.title}</div>
                  <div style={{ fontSize: '10px', color: Tauq.color.text.tertiary, marginTop: '2px' }}>{t.matter} · {t.workflow || 'ad-hoc'}</div>
                </div>
                <span style={{ ...au.tag, background: au.statusColor(t.status).bg, color: au.statusColor(t.status).color }}>{t.status}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>My task queue — {myActive.length} open</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}>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>
              {myActive.map(t => {
                const ss = au.statusColor(t.status);
                const pc = au.priorityColor(t.priority);
                return (
                  <tr key={t.id}>
                    <td style={{ ...au.td, fontFamily: Tauq.font.mono, color: au.lime, fontWeight: 700 }}>{t.id}</td>
                    <td style={{ ...au.td, fontWeight: 600, color: Tauq.color.text.primary, maxWidth: '280px' }}>{t.title}</td>
                    <td style={{ ...au.td, fontSize: '11px', color: Tauq.color.text.secondary, maxWidth: '160px' }}>{t.matter}</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: Tauq.font.mono, fontSize: '11px' }}>{t.dueDate}</td>
                    <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauq.font.mono, fontSize: '11px', color: Tauq.color.text.secondary }}>{t.spentHours}/{t.estHours}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>My active workflow runs</div>
          <div>
            {myRuns.length === 0 && (
              <div style={{ padding: '20px', textAlign: 'center', color: Tauq.color.text.tertiary, fontSize: '12px' }}>No workflow runs started by {ME}.</div>
            )}
            {myRuns.map(r => {
              const ss = au.statusColor(r.status);
              const progColor = r.status === 'Blocked' ? au.crimson : r.status === 'Waiting' ? au.amber : au.lime;
              return (
                <div key={r.id} style={{ padding: '12px 16px', borderBottom: `1px solid ${Tauq.color.border.light}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                    <span style={{ fontSize: '11px', fontFamily: Tauq.font.mono, color: au.lime, fontWeight: 700 }}>{r.id}</span>
                    <span style={{ ...au.tag, background: ss.bg, color: ss.color }}>{r.status}</span>
                  </div>
                  <div style={{ fontSize: '11px', fontWeight: 600, color: Tauq.color.text.primary, fontFamily: Tauq.font.mono }}>{r.workflow}</div>
                  <div style={{ fontSize: '10px', color: Tauq.color.text.tertiary, marginTop: '2px' }}>{r.matter} · {r.currentStep}</div>
                  <div style={{ marginTop: '6px', display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <div style={{ flex: 1, height: '5px', background: Tauq.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${r.progress}%`, height: '100%', background: progColor }} />
                    </div>
                    <span style={{ fontFamily: Tauq.font.mono, fontSize: '10px', color: progColor, fontWeight: 700 }}>{r.progress}%</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

function AutoAnalytics({ data }) {
  const au = window.__au;
  const byWf = data.analytics.runsByWorkflow;
  const maxRuns = Math.max(...byWf.map(w => w.runs));
  const byAssignee = data.analytics.tasksByAssignee;

  return (
    <div>
      <AuHero
        accent={au.violet} bg={au.violetBg}
        title="Analytics — run + task aggregates"
        description={<>
          Platform-wide performance view. Volume by workflow, load by assignee, success trends. <b style={{ fontFamily: Tauq.font.mono }}>{au.num(data.kpis.runsSucceededYtd + data.kpis.runsFailedYtd)}</b> runs YTD at <b style={{ color: au.emerald, fontFamily: Tauq.font.mono }}>{data.kpis.successRatePct}%</b> success.
        </>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Runs YTD</span><span style={au.statValue}>{au.num(data.kpis.runsSucceededYtd + data.kpis.runsFailedYtd)}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Success rate</span><span style={{ ...au.statValue, color: au.emerald }}>{data.kpis.successRatePct}%</span></div>
        <div style={au.stat}><span style={au.statLabel}>Avg run length</span><span style={au.statValue}>{data.kpis.avgRunMinutes} <span style={{ fontSize: '12px', color: Tauq.color.text.tertiary, fontWeight: 500 }}>min</span></span></div>
        <div style={au.stat}><span style={au.statLabel}>Peak / day (14d)</span><span style={{ ...au.statValue, color: au.lime }}>{Math.max(...data.analytics.daily14.map(d => d.runs))}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Triggers fired YTD</span><span style={au.statValue}>{au.num(data.triggers.reduce((s, t) => s + t.firedYtd, 0))}</span></div>
      </div>

      {/* Top workflows by volume */}
      <div style={au.card}>
        <div style={au.cardH}>Runs by workflow — YTD (top 10)</div>
        <div style={{ padding: '14px 16px' }}>
          {byWf.map(w => {
            const rateColor = w.successPct >= 99 ? au.emerald : w.successPct >= 97 ? au.lime : au.amber;
            return (
              <div key={w.workflow} style={{ marginBottom: '12px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                  <span style={{ fontSize: '11px', fontFamily: Tauq.font.mono, fontWeight: 600, color: Tauq.color.text.primary }}>{w.workflow}</span>
                  <span style={{ fontSize: '11px', fontFamily: Tauq.font.mono, color: Tauq.color.text.tertiary }}>
                    <span style={{ color: rateColor, fontWeight: 700 }}>{w.successPct}%</span> · {au.num(w.runs)} runs
                  </span>
                </div>
                <div style={{ height: '8px', background: Tauq.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                  <div style={{ width: `${(w.runs / maxRuns) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${au.limeLight} 0%, ${au.lime} 100%)` }} />
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Tasks by assignee */}
      <div style={au.card}>
        <div style={au.cardH}>Task load by assignee</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>Attorney</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Open</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Completed YTD</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Overdue</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Avg close time</th>
              <th style={au.th}>Workload</th>
            </tr>
          </thead>
          <tbody>
            {byAssignee.map(a => {
              const maxOpen = Math.max(...byAssignee.map(x => x.open));
              const loadColor = a.open > 20 ? au.crimson : a.open > 14 ? au.amber : au.emerald;
              return (
                <tr key={a.name}>
                  <td style={{ ...au.td, fontWeight: 600, color: Tauq.color.text.primary }}>{a.name}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauq.font.mono, color: au.cobalt, fontWeight: 700 }}>{a.open}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauq.font.mono, color: au.emerald, fontWeight: 700 }}>{a.completed}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauq.font.mono, color: a.overdue > 0 ? au.crimson : Tauq.color.text.tertiary, fontWeight: a.overdue > 0 ? 700 : 400 }}>{a.overdue}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauq.font.mono, color: Tauq.color.text.secondary }}>{a.avgCloseHrs}h</td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <div style={{ width: '140px', height: '6px', background: Tauq.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${(a.open / maxOpen) * 100}%`, height: '100%', background: loadColor }} />
                      </div>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.AutoMyQueue   = AutoMyQueue;
window.AutoAnalytics = AutoAnalytics;
