const { useState, useMemo } = React;
const T = window.ArbiterTokens;

// ── 4. NOTIFICATION / ALERT SYSTEM ──
function CalNotifications() {
  const dl = window.DOCKET_DEADLINES;
  const now = new Date('2026-04-20');
  const daysUntil = (d) => Math.ceil((new Date(d) - now) / 86400000);

  const alerts = useMemo(() => {
    const a = [];
    dl.forEach(d => {
      const days = daysUntil(d.date);
      if (days < 0) a.push({ ...d, alertType: 'overdue', severity: 'critical', message: `OVERDUE by ${Math.abs(days)} days` });
      else if (days === 0) a.push({ ...d, alertType: 'today', severity: 'critical', message: 'Due TODAY' });
      else if (days <= 3) a.push({ ...d, alertType: '3-day', severity: 'high', message: `Due in ${days} day${days>1?'s':''}` });
      else if (days <= 7) a.push({ ...d, alertType: '7-day', severity: 'medium', message: `Due in ${days} days` });
    });
    return a.sort((a,b) => a.date.localeCompare(b.date));
  }, []);

  const sevColor = { critical: '#C23030', high: '#D97706', medium: '#3B82F6' };
  const [dismissed, setDismissed] = useState(new Set());

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cal.stat}><span style={cal.statLabel}>Active Alerts</span><span style={{ ...cal.statValue, color: '#C23030' }}>{alerts.length - dismissed.size}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Overdue</span><span style={{ ...cal.statValue, color: '#C23030' }}>{alerts.filter(a=>a.alertType==='overdue').length}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Due Today</span><span style={{ ...cal.statValue, color: '#D97706' }}>{alerts.filter(a=>a.alertType==='today').length}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Next 7 Days</span><span style={{ ...cal.statValue, color: '#3B82F6' }}>{alerts.filter(a=>a.alertType==='7-day'||a.alertType==='3-day').length}</span></div>
      </div>

      {/* Alert config */}
      <div style={cal.card}>
        <div style={cal.cardH}><span>Alert Rules</span></div>
        <div style={{ padding: '10px 16px', display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '8px' }}>
          {[{label:'7-Day Warning',active:true},{label:'3-Day Warning',active:true},{label:'Same-Day Alert',active:true},{label:'Overdue Escalation',active:true}].map((r,i) => (
            <div key={i} style={{ padding: '8px 10px', borderRadius: '6px', border: `1px solid ${r.active ? cal.amber : T.color.border.light}20`, background: r.active ? cal.amberBg : T.color.bg.secondary, display: 'flex', alignItems: 'center', gap: '6px' }}>
              <div style={{ width: '14px', height: '14px', borderRadius: '3px', border: `1px solid ${r.active ? cal.amber : T.color.border.light}`, background: r.active ? cal.amber : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '9px', color: '#fff' }}>{r.active ? 'ok' : ''}</div>
              <span style={{ fontSize: '10px', fontWeight: 500, color: r.active ? cal.amber : T.color.text.tertiary }}>{r.label}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Active alerts */}
      <div style={cal.card}>
        <div style={cal.cardH}><span>Active Alerts</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{alerts.length - dismissed.size} active</span></div>
        {alerts.filter(a => !dismissed.has(a.id)).map(a => (
          <div key={a.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, borderLeft: `3px solid ${sevColor[a.severity]}`, display: 'flex', alignItems: 'center', gap: '10px', background: `${sevColor[a.severity]}03` }}>
            <span style={{ fontSize: '14px', color: sevColor[a.severity] }}>{a.severity === 'critical' ? '!' : '◆'}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: '12px', color: T.color.text.primary }}>{a.label}</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{a.matter} · {a.assignee} · {a.rule}</div>
            </div>
            <span style={{ ...cal.tag, background: `${sevColor[a.severity]}10`, color: sevColor[a.severity] }}>{a.message}</span>
            <button onClick={() => setDismissed(p => new Set([...p, a.id]))} style={{ ...cal.filterBtn, fontSize: '9px', padding: '2px 8px' }}>Dismiss</button>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── 6. AUTO CONFLICT DETECTION ──
function CalConflicts() {
  const dl = window.DOCKET_DEADLINES;
  const attorneys = window.ATTORNEYS;

  // Detect conflicts: same assignee, same date or within 24h
  const conflicts = useMemo(() => {
    const c = [];
    const byAssignee = {};
    dl.forEach(d => { if (!byAssignee[d.assignee]) byAssignee[d.assignee] = []; byAssignee[d.assignee].push(d); });
    Object.entries(byAssignee).forEach(([name, deadlines]) => {
      for (let i = 0; i < deadlines.length; i++) {
        for (let j = i + 1; j < deadlines.length; j++) {
          const diff = Math.abs(new Date(deadlines[i].date) - new Date(deadlines[j].date)) / 86400000;
          if (diff <= 1) {
            c.push({ attorney: name, d1: deadlines[i], d2: deadlines[j], sameDayConflict: diff === 0, severity: diff === 0 ? 'critical' : 'warning' });
          }
        }
      }
    });
    return c;
  }, []);

  // Workload risk: more than 2 deadlines in a week
  const workloadRisks = useMemo(() => {
    const risks = [];
    const byAssignee = {};
    dl.forEach(d => { if (!byAssignee[d.assignee]) byAssignee[d.assignee] = []; byAssignee[d.assignee].push(d); });
    Object.entries(byAssignee).forEach(([name, deadlines]) => {
      // Check weekly clusters
      const sorted = [...deadlines].sort((a, b) => a.date.localeCompare(b.date));
      for (let i = 0; i < sorted.length; i++) {
        const weekEnd = new Date(new Date(sorted[i].date).getTime() + 7 * 86400000);
        const cluster = sorted.filter(d => new Date(d.date) >= new Date(sorted[i].date) && new Date(d.date) <= weekEnd);
        if (cluster.length >= 3) {
          risks.push({ attorney: name, count: cluster.length, weekOf: sorted[i].date, items: cluster });
          break; // one risk per attorney
        }
      }
    });
    return risks;
  }, []);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cal.stat}><span style={cal.statLabel}>Schedule Conflicts</span><span style={{ ...cal.statValue, color: '#C23030' }}>{conflicts.length}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Workload Risks</span><span style={{ ...cal.statValue, color: cal.amber }}>{workloadRisks.length}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Attorneys Affected</span><span style={cal.statValue}>{new Set([...conflicts.map(c=>c.attorney), ...workloadRisks.map(r=>r.attorney)]).size}</span></div>
      </div>

      {/* Conflicts */}
      <div style={cal.card}>
        <div style={{ ...cal.cardH, background: 'rgba(194,48,48,0.03)' }}><span style={{ color: '#C23030' }}>! Schedule Conflicts</span></div>
        {conflicts.length === 0 && <div style={{ padding: '20px 16px', textAlign: 'center', fontSize: '12px', color: T.color.text.tertiary }}>No scheduling conflicts detected.</div>}
        {conflicts.map((c, i) => (
          <div key={i} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, borderLeft: `3px solid ${c.severity === 'critical' ? '#C23030' : cal.amber}` }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
              <span style={{ fontWeight: 700, fontSize: '12px', color: T.color.text.primary }}>{c.attorney}</span>
              <span style={{ ...cal.tag, background: c.sameDayConflict ? 'rgba(194,48,48,0.08)' : cal.amberBg, color: c.sameDayConflict ? '#C23030' : cal.amber }}>
                {c.sameDayConflict ? 'Same-Day Conflict' : 'Adjacent-Day Conflict'}
              </span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
              {[c.d1, c.d2].map((d, j) => (
                <div key={j} style={{ padding: '6px 10px', borderRadius: '6px', background: T.color.bg.secondary, fontSize: '11px' }}>
                  <div style={{ fontWeight: 500, color: T.color.text.primary }}>{d.label}</div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{d.matter} · {new Date(d.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Workload risks */}
      <div style={cal.card}>
        <div style={{ ...cal.cardH, background: cal.amberBg }}><span style={{ color: cal.amber }}>◆ Workload Concentration Risks</span></div>
        {workloadRisks.length === 0 && <div style={{ padding: '20px 16px', textAlign: 'center', fontSize: '12px', color: T.color.text.tertiary }}>No workload concentration risks detected.</div>}
        {workloadRisks.map((r, i) => (
          <div key={i} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}` }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
              <span style={{ fontWeight: 700, fontSize: '12px', color: T.color.text.primary }}>{r.attorney}</span>
              <span style={{ ...cal.tag, background: cal.amberBg, color: cal.amber }}>{r.count} deadlines in 7 days</span>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>Week of {new Date(r.weekOf).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</span>
            </div>
            <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
              {r.items.map(d => (
                <span key={d.id} style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '10px', background: T.color.bg.secondary, color: T.color.text.secondary }}>{d.label} ({new Date(d.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })})</span>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── 12. RISK SCORING PER DEADLINE ──
function CalRiskScore() {
  const dl = window.DOCKET_DEADLINES;
  const now = new Date('2026-04-20');

  const scored = useMemo(() => {
    return dl.map(d => {
      const days = Math.ceil((new Date(d.date) - now) / 86400000);
      const timeScore = days <= 0 ? 100 : days <= 3 ? 90 : days <= 7 ? 70 : days <= 14 ? 50 : days <= 30 ? 30 : 10;
      const priorityScore = { critical: 40, high: 30, medium: 20, low: 10 }[d.priority] || 10;
      const chainScore = d.chainChildren.length * 15;
      const total = Math.min(timeScore + priorityScore + chainScore, 100);
      return { ...d, riskScore: total, timeScore, priorityScore, chainScore, daysLeft: days };
    }).sort((a, b) => b.riskScore - a.riskScore);
  }, []);

  const riskColor = (s) => s >= 80 ? '#C23030' : s >= 60 ? '#D97706' : s >= 40 ? '#3B82F6' : T.color.status.active;

  return (
    <div>
      <div style={{ ...cal.card, marginBottom: '16px' }}>
        <div style={{ padding: '12px 16px', background: cal.amberBg, fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.5 }}>
          <div style={{ fontSize: '10px', fontWeight: 600, color: cal.amber, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>◆ AI Risk Scoring</div>
          Risk = Time Pressure (days remaining) + Priority Weight + Downstream Impact (chain dependents). Scores above 80 require immediate action. Scores 60–80 need active monitoring.
        </div>
      </div>

      <div style={cal.card}>
        <div style={cal.cardH}><span>Deadlines Ranked by Risk</span></div>
        <div style={{ display: 'grid', gridTemplateColumns: '50px 1fr 60px 60px 60px 60px', padding: '6px 16px', background: T.color.bg.secondary, borderBottom: `1px solid ${T.color.border.light}`, fontSize: '9px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', gap: '8px' }}>
          <span>Risk</span><span>Deadline</span><span>Time</span><span>Priority</span><span>Chain</span><span>Days</span>
        </div>
        {scored.map(d => {
          const rc = riskColor(d.riskScore);
          return (
            <div key={d.id} style={{ display: 'grid', gridTemplateColumns: '50px 1fr 60px 60px 60px 60px', padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px', alignItems: 'center', gap: '8px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                <div style={{ width: '28px', height: '28px', borderRadius: '50%', background: `${rc}10`, border: `2px solid ${rc}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '11px', fontWeight: 700, fontFamily: T.font.mono, color: rc }}>{d.riskScore}</div>
              </div>
              <div>
                <div style={{ fontWeight: 500, color: T.color.text.primary }}>{d.label}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{d.matter}</div>
              </div>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.secondary }}>{d.timeScore}</span>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.secondary }}>{d.priorityScore}</span>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: d.chainScore > 0 ? cal.amber : T.color.text.tertiary }}>{d.chainScore}</span>
              <span style={{ fontSize: '11px', fontFamily: T.font.mono, fontWeight: 700, color: d.daysLeft <= 3 ? '#C23030' : d.daysLeft <= 7 ? cal.amber : T.color.text.secondary }}>{d.daysLeft}d</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { CalNotifications, CalConflicts, CalRiskScore });
