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

function CalendarPlatform() {
  const [activeTab, setActiveTab] = useState('docket');
  const [modal, setModal] = useState(null);
  const open = (name) => setModal(name);
  const close = () => setModal(null);

  const dl = window.DOCKET_DEADLINES;
  const now = new Date('2026-04-20');
  const critical = dl.filter(d => d.priority === 'critical').length;
  const conflicts = window.ATTORNEYS.filter(a => a.conflicts.length > 0).length;

  const tabs = [
    { id: 'docket',     label: 'Docket' },
    { id: 'views',      label: 'Views' },
    { id: 'schedule',   label: 'Schedule' },
    { id: 'rules',      label: 'Rules' },
    { id: 'practice',   label: 'Practice' },
    { id: 'resources',  label: 'Resources' },
    { id: 'compliance', label: 'Compliance' },
    { id: 'prep',       label: 'Prep' },
    { id: 'analytics',  label: 'Analytics' },
  ];

  const renderTab = () => {
    switch (activeTab) {
      case 'docket':     return <CalDocket />;
      case 'views':      return <CalViewsHub />;
      case 'schedule':   return <window.CalScheduleHub />;
      case 'rules':      return <window.CalRulesHub />;
      case 'practice':   return <window.CalDocketHub onCascade={() => open('cascade')} />;
      case 'resources':  return <CalResourcesHub />;
      case 'compliance': return <window.CalComplianceHub />;
      case 'prep':       return <CalPrepHub />;
      case 'analytics':  return <CalAnalyticsHub />;
      default: return <CalDocket />;
    }
  };

  const renderModal = () => {
    if (!modal) return null;
    switch (modal) {
      case 'cascade': return <window.CalCascadeModal onClose={close} />;
      default: return null;
    }
  };

  // Count alerts
  const alertCount = dl.filter(d => { const days = Math.ceil((new Date(d.date) - now) / 86400000); return days <= 7 && days >= 0; }).length;

  return (
    <div style={cal.container}>
      <div style={cal.header}>
        <div style={cal.headerTitle}>
          <div style={cal.calIcon}>{window.Icons && <window.Icons.Calendar size={16} color="#fff" strokeWidth={1.75} />}</div>
          <div>
            <div style={cal.title}>Calendar Platform</div>
            <div style={cal.subtitle}>Docket Management · Deadline Intelligence · Resource Scheduling</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: T.color.bg.secondary, border: `1px solid ${T.color.border.light}` }}>
            <span style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Deadlines</span>
            <span style={{ fontSize: '14px', fontWeight: 700, color: T.color.text.primary, fontFamily: T.font.mono }}>{dl.length}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: 'rgba(194,48,48,0.04)', border: '1px solid rgba(194,48,48,0.15)' }}>
            <span style={{ fontSize: '10px', fontWeight: 600, color: '#C23030', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Critical</span>
            <span style={{ fontSize: '14px', fontWeight: 700, color: '#C23030', fontFamily: T.font.mono }}>{critical}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: cal.amberBg, border: `1px solid ${cal.amber}20` }}>
            <span style={{ fontSize: '10px', fontWeight: 600, color: cal.amber, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Alerts</span>
            <span style={{ fontSize: '14px', fontWeight: 700, color: cal.amber, fontFamily: T.font.mono }}>{alertCount}</span>
          </div>
          <button style={{ padding: '6px 14px', borderRadius: '6px', background: cal.amber, border: 'none', color: '#fff', fontSize: '12px', fontWeight: 700, cursor: 'pointer', fontFamily: T.font.family }}>+ Deadline</button>
        </div>
      </div>

      <div style={{ ...cal.tabs, overflowX: 'auto' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)} style={{ ...cal.tab, ...(activeTab === t.id ? cal.tabActive : {}), whiteSpace: 'nowrap' }}>
            {t.label}
          </button>
        ))}
      </div>

      <div style={cal.body}>
        {renderTab()}
      </div>
      {renderModal()}
    </div>
  );
}

// ── existing-tab hubs (wrap current flat tabs with DcSubTabs-style switcher) ──
function CalViewsHub() {
  const [sub, setSub] = useState('grid');
  const tabs = [
    { id: 'grid',     label: 'Calendar' },
    { id: 'gantt',    label: 'Gantt' },
    { id: 'chains',   label: 'Chains' },
    { id: 'timeline', label: 'Multi-Matter' },
  ];
  return (
    <div>
      <window.CalSubTabs tabs={tabs} active={sub} onChange={setSub} />
      {sub === 'grid'     && <CalGrid />}
      {sub === 'gantt'    && <CalGantt />}
      {sub === 'chains'   && <CalChains />}
      {sub === 'timeline' && <CalTimeline />}
    </div>
  );
}

function CalResourcesHub() {
  const [sub, setSub] = useState('resources');
  const tabs = [
    { id: 'resources', label: 'Resources',  count: (window.ATTORNEYS || []).length },
    { id: 'workload',  label: 'Workload Forecast' },
    { id: 'conflicts', label: 'Conflicts' },
    { id: 'recurring', label: 'Recurring' },
  ];
  return (
    <div>
      <window.CalSubTabs tabs={tabs} active={sub} onChange={setSub} />
      {sub === 'resources' && <CalResources />}
      {sub === 'workload'  && <window.CalWorkloadHeatmap />}
      {sub === 'conflicts' && <CalConflicts />}
      {sub === 'recurring' && <CalRecurring />}
    </div>
  );
}

function CalPrepHub() {
  const [sub, setSub] = useState('checklists');
  const tabs = [
    { id: 'checklists', label: 'Prep Checklists' },
    { id: 'alerts',     label: 'Alerts' },
    { id: 'calculator', label: 'Deadline Calc' },
  ];
  return (
    <div>
      <window.CalSubTabs tabs={tabs} active={sub} onChange={setSub} />
      {sub === 'checklists' && <CalPrepChecklists />}
      {sub === 'alerts'     && <CalNotifications />}
      {sub === 'calculator' && <CalCalculator />}
    </div>
  );
}

function CalAnalyticsHub() {
  const [sub, setSub] = useState('analytics');
  const tabs = [
    { id: 'analytics', label: 'Deadline Analytics' },
    { id: 'risk',      label: 'Risk' },
    { id: 'extras',    label: 'Milestones & Sync' },
  ];
  return (
    <div>
      <window.CalSubTabs tabs={tabs} active={sub} onChange={setSub} />
      {sub === 'analytics' && <CalAnalytics />}
      {sub === 'risk'      && <CalRiskScore />}
      {sub === 'extras'    && <CalExtras />}
    </div>
  );
}

window.CalendarPlatform = CalendarPlatform;
window.CalViewsHub      = CalViewsHub;
window.CalResourcesHub  = CalResourcesHub;
window.CalPrepHub       = CalPrepHub;
window.CalAnalyticsHub  = CalAnalyticsHub;
