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

// ── DOCKET CALENDAR ──
function CalDocket() {
  const [filter, setFilter] = useState('All');
  const [matterFilter, setMatterFilter] = useState('All');
  const [hovered, setHovered] = useState(null);
  const [expanded, setExpanded] = useState(null);
  const dl = window.DOCKET_DEADLINES;

  const matters = ['All', ...new Set(dl.map(d => d.matter))];
  const types = ['All', 'court-deadline', 'brief', 'motion', 'discovery', 'deposition', 'hearing', 'trial'];

  const filtered = useMemo(() => {
    let items = dl;
    if (filter !== 'All') items = items.filter(i => i.type === filter);
    if (matterFilter !== 'All') items = items.filter(i => i.matter === matterFilter);
    return items.sort((a, b) => a.date.localeCompare(b.date));
  }, [filter, matterFilter]);

  const now = new Date('2026-04-20');
  const daysUntil = (date) => Math.ceil((new Date(date) - now) / (1000 * 60 * 60 * 24));

  const priorityColor = { critical: '#C23030', high: '#D97706', medium: '#3B82F6', low: '#6E7D9E' };
  const typeIcons = { 'court-deadline': '', brief: '▤', motion: '◈', discovery: '▦', deposition: '◔', hearing: '◰', trial: '' };
  const statusColor = { due: '#C23030', drafting: '#D97706', scheduled: '#3B82F6', upcoming: '#6E7D9E' };

  const criticalCount = dl.filter(d => d.priority === 'critical').length;
  const thisWeek = dl.filter(d => daysUntil(d.date) >= 0 && daysUntil(d.date) <= 7).length;
  const overdue = dl.filter(d => daysUntil(d.date) < 0).length;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cal.stat}><span style={cal.statLabel}>Total Deadlines</span><span style={cal.statValue}>{dl.length}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Critical</span><span style={{ ...cal.statValue, color: '#C23030' }}>{criticalCount}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>This Week</span><span style={{ ...cal.statValue, color: cal.amber }}>{thisWeek}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Overdue</span><span style={{ ...cal.statValue, color: overdue > 0 ? '#C23030' : T.color.status.active }}>{overdue}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Matters</span><span style={cal.statValue}>{matters.length - 1}</span></div>
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '12px', alignItems: 'center', flexWrap: 'wrap' }}>
        <select style={{ ...cal.filterBtn, padding: '4px 8px' }} value={matterFilter} onChange={e => setMatterFilter(e.target.value)}>
          {matters.map(m => <option key={m} value={m}>{m}</option>)}
        </select>
        {types.map(t => (
          <button key={t} style={{ ...cal.filterBtn, ...(filter === t ? cal.filterBtnActive : {}) }} onClick={() => setFilter(t)}>{t === 'All' ? 'All Types' : t}</button>
        ))}
      </div>

      <div style={cal.card}>
        {filtered.map((d, i) => {
          const days = daysUntil(d.date);
          const isOpen = expanded === d.id;
          const urgent = days <= 3 && days >= 0;
          const past = days < 0;
          return (
            <div key={d.id} style={{ borderBottom: `1px solid ${T.color.border.light}` }}>
              <div style={{ padding: '10px 16px', display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer', background: hovered === i ? T.color.bg.hover : urgent ? 'rgba(194,48,48,0.02)' : 'transparent', transition: 'background 0.1s' }}
                onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}
                onClick={() => setExpanded(isOpen ? null : d.id)}>
                {/* Days countdown */}
                <div style={{ minWidth: '48px', textAlign: 'center' }}>
                  <div style={{ fontSize: '18px', fontWeight: 700, fontFamily: T.font.mono, color: past ? '#C23030' : days <= 3 ? '#C23030' : days <= 14 ? cal.amber : T.color.text.primary }}>{past ? 'Past' : days}</div>
                  <div style={{ fontSize: '9px', color: T.color.text.tertiary }}>{past ? '' : 'days'}</div>
                </div>
                {/* Type icon */}
                <div style={{ width: '28px', height: '28px', borderRadius: '6px', background: `${priorityColor[d.priority]}10`, border: `1px solid ${priorityColor[d.priority]}20`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '13px', flexShrink: 0 }}>
                  {typeIcons[d.type] || '●'}
                </div>
                {/* Content */}
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: '13px', color: T.color.text.primary }}>{d.label}</div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '1px' }}>{d.matter} · {d.rule}</div>
                </div>
                {/* Date */}
                <span style={{ fontFamily: T.font.mono, fontSize: '11px', color: T.color.text.tertiary }}>{new Date(d.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</span>
                {/* Assignee */}
                <span style={{ fontSize: '10px', color: T.color.text.secondary }}>{d.assignee}</span>
                {/* Priority */}
                <span style={{ ...cal.tag, background: `${priorityColor[d.priority]}10`, color: priorityColor[d.priority] }}>{d.priority}</span>
                {/* Status */}
                <span style={{ ...cal.tag, background: `${statusColor[d.status]}10`, color: statusColor[d.status] }}>{d.status}</span>
              </div>
              {isOpen && (
                <div style={{ padding: '8px 16px 12px 92px', background: T.color.bg.secondary, fontSize: '11px' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px 16px' }}>
                    <div><span style={{ color: T.color.text.tertiary }}>Rule: </span><span style={{ fontWeight: 500 }}>{d.rule}</span></div>
                    <div><span style={{ color: T.color.text.tertiary }}>Assignee: </span><span style={{ fontWeight: 500 }}>{d.assignee}</span></div>
                    {d.chainParent && <div><span style={{ color: T.color.text.tertiary }}>Depends on: </span><span style={{ fontWeight: 500, color: cal.amber }}>{window.DOCKET_DEADLINES.find(x => x.id === d.chainParent)?.label || d.chainParent}</span></div>}
                    {d.chainChildren.length > 0 && <div><span style={{ color: T.color.text.tertiary }}>Triggers: </span><span style={{ fontWeight: 500, color: '#3B82F6' }}>{d.chainChildren.map(c => window.DOCKET_DEADLINES.find(x => x.id === c)?.label || c).join(', ')}</span></div>}
                    {d.notes && <div style={{ gridColumn: '1/3' }}><span style={{ color: T.color.text.tertiary }}>Notes: </span>{d.notes}</div>}
                  </div>
                  {/* Linked Tasks */}
                  {window.DEADLINE_TO_TASKS && window.DEADLINE_TO_TASKS[d.id] && window.DEADLINE_TO_TASKS[d.id].length > 0 && (
                    <div style={{ marginTop: '8px', paddingTop: '8px', borderTop: `1px solid ${T.color.border.light}` }}>
                      <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Linked Tasks</div>
                      {window.DEADLINE_TO_TASKS[d.id].map(taskId => {
                        const task = window.TASKS.find(t => t.id === taskId);
                        if (!task) return null;
                        const statusC = { 'To Do': '#4A5A80', 'In Progress': '#2563EB', 'In Review': '#B8860B', 'Done': '#1B7A4A' };
                        return (
                          <div key={taskId} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '4px 0' }}>
                            <span style={{ width: '5px', height: '5px', borderRadius: '50%', background: statusC[task.status] || '#4A5A80', flexShrink: 0 }} />
                            <span style={{ fontWeight: 500, color: T.color.text.primary }}>{task.title}</span>
                            <span style={{ ...cal.tag, background: `${statusC[task.status]}14`, color: statusC[task.status] }}>{task.status}</span>
                            <span style={{ fontSize: '10px', color: T.color.text.tertiary, marginLeft: 'auto' }}>{task.assignee}</span>
                          </div>
                        );
                      })}
                    </div>
                  )}
                  {/* Linked Evidence (for Redstone matter) */}
                  {window.EVIDENCE_DATA && window.EVIDENCE_DATA[d.matterId] && (
                    (() => {
                      const evItems = window.EVIDENCE_DATA[d.matterId]?.vault?.filter(e =>
                        e.aiTags?.some(tag => d.label.toLowerCase().includes(tag.toLowerCase())) ||
                        (d.type === 'deposition' && e.type === 'Testimony') ||
                        (d.type === 'brief' && e.type === 'Expert' && d.label.toLowerCase().includes('msj'))
                      ).slice(0, 3);
                      if (!evItems || evItems.length === 0) return null;
                      return (
                        <div style={{ marginTop: '8px', paddingTop: '8px', borderTop: `1px solid ${T.color.border.light}` }}>
                          <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Related Evidence</div>
                          {evItems.map(ev => (
                            <div key={ev.id} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '4px 0' }}>
                              <span style={{ width: '18px', height: '18px', borderRadius: '3px', background: '#6B21A810', color: '#6B21A8', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '9px', fontWeight: 700, flexShrink: 0 }}>◈</span>
                              <span style={{ fontWeight: 500, color: T.color.text.primary, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ev.name}</span>
                              <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{ev.bates}</span>
                            </div>
                          ))}
                        </div>
                      );
                    })()
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── DEADLINE CHAIN ENGINE ──
function CalChains() {
  const dl = window.DOCKET_DEADLINES.filter(d => d.matterId === 'M-2024-0312');
  const now = new Date('2026-04-20');
  const daysUntil = (date) => Math.ceil((new Date(date) - now) / (1000 * 60 * 60 * 24));

  // Build chain tree for Redstone
  const roots = dl.filter(d => !d.chainParent);
  const getChildren = (id) => dl.filter(d => d.chainParent === id);

  const priorityColor = { critical: '#C23030', high: '#D97706', medium: '#3B82F6', low: '#6E7D9E' };

  const renderNode = (node, depth = 0) => {
    const children = getChildren(node.id);
    const days = daysUntil(node.date);
    return (
      <div key={node.id}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '8px 16px', paddingLeft: `${16 + depth * 32}px`, borderBottom: `1px solid ${T.color.border.light}` }}>
          {depth > 0 && <span style={{ color: T.color.border.medium, fontSize: '12px' }}>└</span>}
          <div style={{ width: '6px', height: '6px', borderRadius: '50%', background: priorityColor[node.priority], flexShrink: 0 }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: '12px', color: T.color.text.primary }}>{node.label}</div>
            <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{node.rule}</div>
          </div>
          <span style={{ fontFamily: T.font.mono, fontSize: '11px', color: days <= 7 ? '#C23030' : T.color.text.tertiary }}>{new Date(node.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</span>
          <span style={{ fontSize: '10px', fontFamily: T.font.mono, fontWeight: 700, color: days <= 3 ? '#C23030' : days <= 14 ? cal.amber : T.color.text.secondary }}>{days}d</span>
          <span style={{ ...cal.tag, background: `${priorityColor[node.priority]}10`, color: priorityColor[node.priority] }}>{node.priority}</span>
        </div>
        {children.map(c => renderNode(c, depth + 1))}
      </div>
    );
  };

  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' }}>◆ Deadline Chain Analysis</div>
          The Discovery Cutoff (May 14) is the critical node — it gates the MSJ Opposition, Motions in Limine, and ultimately the Trial Date. Any slip on discovery cascades through 4 downstream deadlines. The Pretrial Brief and Jury Instructions run on a parallel track but converge at Trial.
        </div>
      </div>

      <div style={cal.card}>
        <div style={cal.cardH}><span>Redstone v. Meridian — Deadline Chain</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>Critical path highlighted</span></div>
        {roots.map(r => renderNode(r))}
      </div>
    </div>
  );
}

// ── MULTI-MATTER TIMELINE ──
function CalTimeline() {
  const dl = window.DOCKET_DEADLINES;
  const now = new Date('2026-04-20');
  const matterColors = {
    'Redstone v. Meridian': '#C23030',
    'Pacific Shipping Antitrust': '#3B82F6',
    'Thornton Estate': '#A855F7',
    'Blackwell IP': '#0D9488',
    'Chen v. Atlas': '#D97706',
    'Marshall Employment': '#6E7D9E',
    'Sterling Pharma FCPA': '#06B6D4',
  };
  const matters = [...new Set(dl.map(d => d.matter))];
  const sorted = [...dl].sort((a, b) => a.date.localeCompare(b.date));

  // Group by week
  const weeks = {};
  sorted.forEach(d => {
    const date = new Date(d.date);
    const weekStart = new Date(date);
    weekStart.setDate(date.getDate() - date.getDay() + 1);
    const key = weekStart.toISOString().slice(0, 10);
    if (!weeks[key]) weeks[key] = [];
    weeks[key].push(d);
  });

  return (
    <div>
      {/* Swim lanes header */}
      <div style={cal.card}>
        <div style={cal.cardH}><span>Multi-Matter Deadline View</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{dl.length} deadlines across {matters.length} matters</span></div>
        {/* Legend */}
        <div style={{ padding: '8px 16px', display: 'flex', gap: '12px', flexWrap: 'wrap', borderBottom: `1px solid ${T.color.border.light}` }}>
          {matters.map(m => (
            <div key={m} style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
              <div style={{ width: '8px', height: '8px', borderRadius: '2px', background: matterColors[m] || '#6E7D9E' }} />
              <span style={{ fontSize: '10px', color: T.color.text.secondary }}>{m}</span>
            </div>
          ))}
        </div>
        {/* Weekly groups */}
        {Object.entries(weeks).map(([weekKey, items]) => {
          const weekDate = new Date(weekKey);
          const weekEnd = new Date(weekDate); weekEnd.setDate(weekEnd.getDate() + 6);
          const isCurrentWeek = now >= weekDate && now <= weekEnd;
          return (
            <div key={weekKey}>
              <div style={{ padding: '6px 16px', background: isCurrentWeek ? cal.amberBg : T.color.bg.secondary, fontSize: '10px', fontWeight: 600, color: isCurrentWeek ? cal.amber : T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', display: 'flex', justifyContent: 'space-between' }}>
                <span>Week of {weekDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</span>
                {isCurrentWeek && <span style={{ color: cal.amber }}>← Current Week</span>}
                <span>{items.length} deadline{items.length > 1 ? 's' : ''}</span>
              </div>
              {items.map(d => (
                <div key={d.id} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '12px' }}>
                  <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary, minWidth: '44px' }}>{new Date(d.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</span>
                  <div style={{ width: '3px', height: '24px', borderRadius: '2px', background: matterColors[d.matter] || '#6E7D9E', flexShrink: 0 }} />
                  <div style={{ flex: 1 }}>
                    <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', color: T.color.text.secondary }}>{d.assignee}</span>
                  <span style={{ ...cal.tag, background: `${matterColors[d.matter]}10`, color: matterColors[d.matter] || '#6E7D9E' }}>{d.type}</span>
                </div>
              ))}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { CalDocket, CalChains, CalTimeline });
