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

// ── 8. RECURRING DEADLINES ──
function CalRecurring() {
  const RECURRING = [
    { id: 'RC-1', label: 'DOJ Quarterly Status Report', matter: 'Sterling Pharma FCPA', frequency: 'Quarterly', nextDate: '2026-05-20', assignee: 'S. Chen', rule: 'DOJ Cooperation Agreement', instances: 4, active: true },
    { id: 'RC-2', label: 'Client Billing Review', matter: 'All Matters', frequency: 'Monthly', nextDate: '2026-05-01', assignee: 'M. Kirkland', rule: 'Firm Policy', instances: 12, active: true },
    { id: 'RC-3', label: 'Case Status Report — Pacific Shipping', matter: 'Pacific Shipping Antitrust', frequency: 'Bi-weekly', nextDate: '2026-04-27', assignee: 'S. Chen', rule: 'Client Request', instances: 8, active: true },
    { id: 'RC-4', label: 'Document Review Progress Check', matter: 'Redstone v. Meridian', frequency: 'Weekly', nextDate: '2026-04-24', assignee: 'J. Park', rule: 'Internal', instances: 12, active: true },
    { id: 'RC-5', label: 'Preservation Hold Audit', matter: 'All Matters', frequency: 'Quarterly', nextDate: '2026-07-01', assignee: 'L. Torres', rule: 'Firm Policy — Litigation Hold', instances: 4, active: true },
  ];
  const freqColor = { Weekly: '#3B82F6', 'Bi-weekly': '#0D9488', Monthly: cal.amber, Quarterly: '#A855F7' };

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cal.stat}><span style={cal.statLabel}>Active Series</span><span style={cal.statValue}>{RECURRING.filter(r=>r.active).length}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Total Instances</span><span style={cal.statValue}>{RECURRING.reduce((s,r)=>s+r.instances,0)}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Next Due</span><span style={{ ...cal.statValue, color: cal.amber, fontSize: '16px' }}>Apr 24</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Frequencies</span><span style={{ ...cal.statValue, fontSize: '16px' }}>4 types</span></div>
      </div>

      <div style={cal.card}>
        <div style={cal.cardH}><span>Recurring Deadline Series</span><button style={{...cal.filterBtn,...cal.filterBtnActive,fontSize:'10px'}}>+ New Series</button></div>
        {RECURRING.map(r => (
          <div key={r.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '12px' }}>
            <span style={{ ...cal.tag, background: `${freqColor[r.frequency]}10`, color: freqColor[r.frequency], minWidth: '70px', justifyContent: 'center' }}>{r.frequency}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, color: T.color.text.primary }}>{r.label}</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{r.matter} · {r.rule}</div>
            </div>
            <span style={{ fontSize: '10px', color: T.color.text.secondary }}>{r.assignee}</span>
            <span style={{ fontFamily: T.font.mono, fontSize: '11px', color: T.color.text.tertiary }}>Next: {new Date(r.nextDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</span>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{r.instances} inst.</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── 13. PREP CHECKLIST PER DEADLINE ──
function CalPrepChecklists() {
  const PREP = [
    { deadline: 'Deposition — Controller R. Davis', date: 'May 1', matter: 'Redstone v. Meridian', items: [
      { task: 'Review prior testimony and exhibits', done: true },
      { task: 'Prepare examination outline', done: true },
      { task: 'Identify documents to use during deposition', done: false },
      { task: 'Confirm court reporter and videographer', done: true },
      { task: 'Prep session with team', done: false },
      { task: 'Reserve conference room', done: true },
    ]},
    { deadline: 'Discovery Cutoff', date: 'May 14', matter: 'Redstone v. Meridian', items: [
      { task: 'Verify all discovery responses served', done: false },
      { task: 'Confirm all depositions completed', done: false },
      { task: 'Check for outstanding subpoenas', done: false },
      { task: 'File any remaining discovery motions', done: false },
      { task: 'Compile discovery index', done: false },
    ]},
    { deadline: 'Trial Date', date: 'May 2', matter: 'Thornton Estate', items: [
      { task: 'Final witness prep sessions', done: false },
      { task: 'Exhibit binders prepared and numbered', done: true },
      { task: 'Technology setup tested in courtroom', done: false },
      { task: 'Opening statement finalized', done: true },
      { task: 'Jury instructions submitted', done: false },
      { task: 'Trial bag packed (supplies, copies, devices)', done: false },
    ]},
    { deadline: 'Pretrial Conference', date: 'Jun 2', matter: 'Redstone v. Meridian', items: [
      { task: 'Proposed exhibit list filed', done: false },
      { task: 'Motions in limine filed', done: false },
      { task: 'Joint pretrial statement drafted', done: false },
      { task: 'Witness list finalized', done: false },
    ]},
  ];

  const [expandedIdx, setExpandedIdx] = useState(0);

  return (
    <div>
      {PREP.map((p, i) => {
        const done = p.items.filter(x => x.done).length;
        const total = p.items.length;
        const pct = Math.round((done / total) * 100);
        const isOpen = expandedIdx === i;
        return (
          <div key={i} style={cal.card}>
            <div style={{ ...cal.cardH, cursor: 'pointer' }} onClick={() => setExpandedIdx(isOpen ? null : i)}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span style={{ fontWeight: 600, color: T.color.text.primary }}>{p.deadline}</span>
                <span style={{ ...cal.tag, background: cal.amberBg, color: cal.amber }}>{p.date}</span>
                <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{p.matter}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span style={{ ...cal.tag, background: pct === 100 ? 'rgba(34,197,94,0.08)' : T.color.bg.secondary, color: pct === 100 ? T.color.status.active : T.color.text.secondary }}>{done}/{total}</span>
                <span style={{ fontSize: '14px', color: T.color.text.tertiary }}>{isOpen ? '▴' : '▾'}</span>
              </div>
            </div>
            {isOpen && (
              <div>
                <div style={{ padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}` }}>
                  <div style={{ height: '4px', borderRadius: '2px', background: T.color.border.light }}>
                    <div style={{ width: `${pct}%`, height: '100%', borderRadius: '2px', background: pct === 100 ? T.color.status.active : cal.amber }} />
                  </div>
                </div>
                {p.items.map((item, j) => (
                  <div key={j} style={{ padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12px' }}>
                    <span style={{ fontSize: '14px', color: item.done ? T.color.status.active : T.color.text.tertiary }}>{item.done ? 'ok' : ''}</span>
                    <span style={{ color: item.done ? T.color.text.tertiary : T.color.text.primary, textDecoration: item.done ? 'line-through' : 'none' }}>{item.task}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ── 10. MATTER MILESTONES + 14. HISTORICAL PERFORMANCE + 9. EXTERNAL SYNC + 15. JURISDICTION + 7. DELEGATION ──
function CalExtras() {
  // Milestones
  const MILESTONES = [
    { matter: 'Redstone v. Meridian', milestones: [
      { label: 'Complaint Filed', date: 'Jan 5', done: true },
      { label: 'Answer Received', date: 'Feb 28', done: true },
      { label: 'Discovery Opened', date: 'Mar 1', done: true },
      { label: 'Expert Disclosed', date: 'Apr 2', done: true },
      { label: 'Discovery Closes', date: 'May 14', done: false },
      { label: 'Pretrial Conference', date: 'Jun 2', done: false },
      { label: 'Trial', date: 'Jul 15', done: false },
    ]},
    { matter: 'Thornton Estate', milestones: [
      { label: 'Petition Filed', date: 'Jan 15', done: true },
      { label: 'Objections Filed', date: 'Feb 20', done: true },
      { label: 'Expert Reports', date: 'Apr 23', done: false },
      { label: 'Trial', date: 'May 2', done: false },
    ]},
  ];

  // Historical performance
  const HISTORY = [
    { attorney: 'M. Kirkland', total: 42, onTime: 40, late: 2, avgDaysEarly: 2.1 },
    { attorney: 'S. Chen', total: 35, onTime: 34, late: 1, avgDaysEarly: 1.8 },
    { attorney: 'L. Torres', total: 48, onTime: 46, late: 2, avgDaysEarly: 1.5 },
    { attorney: 'R. Vasquez', total: 28, onTime: 28, late: 0, avgDaysEarly: 3.2 },
    { attorney: 'A. Petrov', total: 22, onTime: 21, late: 1, avgDaysEarly: 1.2 },
    { attorney: 'J. Park', total: 31, onTime: 30, late: 1, avgDaysEarly: 1.7 },
  ];
  const firmOnTime = HISTORY.reduce((s, h) => s + h.onTime, 0);
  const firmTotal = HISTORY.reduce((s, h) => s + h.total, 0);

  return (
    <div>
      {/* Matter milestones */}
      <div style={cal.card}>
        <div style={cal.cardH}><span>Matter Milestones</span></div>
        {MILESTONES.map((m, mi) => (
          <div key={mi} style={{ borderBottom: mi < MILESTONES.length - 1 ? `1px solid ${T.color.border.light}` : 'none' }}>
            <div style={{ padding: '8px 16px', fontSize: '12px', fontWeight: 600, color: T.color.text.primary, background: T.color.bg.secondary }}>{m.matter}</div>
            <div style={{ padding: '8px 16px', display: 'flex', gap: '0', position: 'relative' }}>
              {m.milestones.map((ms, i) => (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '4px', position: 'relative' }}>
                  {i < m.milestones.length - 1 && <div style={{ position: 'absolute', top: '3px', left: '50%', width: '100%', height: '2px', background: ms.done ? T.color.status.active : T.color.border.light, zIndex: 0 }} />}
                  <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: ms.done ? T.color.status.active : T.color.border.medium, zIndex: 1, border: '2px solid #fff' }} />
                  <span style={{ fontSize: '8px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{ms.date}</span>
                  <span style={{ fontSize: '8px', fontWeight: 500, color: ms.done ? T.color.text.secondary : T.color.text.primary, textAlign: 'center', lineHeight: 1.2 }}>{ms.label}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        {/* Historical performance */}
        <div style={cal.card}>
          <div style={cal.cardH}>
            <span>Deadline Performance — YTD</span>
            <span style={{ ...cal.tag, background: 'rgba(34,197,94,0.08)', color: T.color.status.active }}>{Math.round(firmOnTime / firmTotal * 100)}% on-time</span>
          </div>
          {HISTORY.map((h, i) => (
            <div key={i} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '12px' }}>
              <span style={{ width: '90px', fontWeight: 500, color: T.color.text.primary }}>{h.attorney}</span>
              <div style={{ flex: 1, height: '6px', borderRadius: '3px', background: T.color.border.light }}>
                <div style={{ width: `${(h.onTime / h.total) * 100}%`, height: '100%', borderRadius: '3px', background: h.late === 0 ? T.color.status.active : cal.amber }} />
              </div>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.status.active }}>{h.onTime}/{h.total}</span>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: h.late > 0 ? '#C23030' : T.color.text.tertiary }}>{h.late} late</span>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>avg {h.avgDaysEarly}d early</span>
            </div>
          ))}
        </div>

        {/* Sync + Jurisdiction */}
        <div>
          {/* External sync */}
          <div style={cal.card}>
            <div style={cal.cardH}><span>Calendar Integrations</span></div>
            {[
              { name: 'Outlook 365', status: 'Connected', sync: 'Real-time', icon: '◰' },
              { name: 'Google Calendar', status: 'Available', sync: '—', icon: '▦' },
              { name: 'iCal Export', status: 'Active', sync: 'On-demand', icon: '◈' },
              { name: 'Court ECF Alerts', status: 'Connected', sync: 'Auto-import', icon: '◆' },
            ].map((s, i) => (
              <div key={i} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '12px' }}>
                <span style={{ fontSize: '14px' }}>{s.icon}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 500, color: T.color.text.primary }}>{s.name}</div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>Sync: {s.sync}</div>
                </div>
                <span style={{ ...cal.tag, background: s.status === 'Connected' ? 'rgba(34,197,94,0.08)' : s.status === 'Active' ? cal.amberBg : T.color.bg.secondary, color: s.status === 'Connected' ? T.color.status.active : s.status === 'Active' ? cal.amber : T.color.text.tertiary }}>{s.status}</span>
              </div>
            ))}
          </div>

          {/* Jurisdiction switcher */}
          <div style={cal.card}>
            <div style={cal.cardH}><span>Active Jurisdictions</span></div>
            {[
              { court: 'U.S. District Court, S.D.N.Y.', matters: 3, rules: 9 },
              { court: 'U.S. District Court, E.D.N.Y.', matters: 1, rules: 8 },
              { court: 'Delaware Court of Chancery', matters: 1, rules: 6 },
              { court: 'Federal (General)', matters: 7, rules: 12 },
            ].map((j, i) => (
              <div key={i} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '12px' }}>
                <span style={{ flex: 1, fontWeight: 500, color: T.color.text.primary }}>{j.court}</span>
                <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{j.matters} matters</span>
                <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: cal.amber }}>{j.rules} rules</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CalRecurring, CalPrepChecklists, CalExtras });
