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

const dashStyles = {
  container: {
    flex: 1,
    overflow: 'auto',
    background: T.color.bg.primary,
    padding: '20px',
  },
  header: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: '20px',
  },
  greeting: {
    fontSize: T.font.size.xl,
    fontWeight: T.font.weight.bold,
    color: T.color.text.primary,
    letterSpacing: T.font.tracking.tight,
  },
  subtitle: {
    fontSize: T.font.size.base,
    color: T.color.text.tertiary,
    marginTop: '2px',
  },
  statsRow: {
    display: 'grid',
    gridTemplateColumns: 'repeat(5, 1fr)',
    gap: '12px',
    marginBottom: '20px',
  },
  mainGrid: {
    display: 'grid',
    gridTemplateColumns: '1fr 320px',
    gap: '16px',
  },
  // Matters table
  filterRow: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
  },
  filterBtn: {
    padding: '4px 10px',
    borderRadius: T.radius.md,
    border: `1px solid ${T.color.border.light}`,
    background: T.color.bg.card,
    fontSize: T.font.size.xs,
    fontWeight: T.font.weight.medium,
    color: T.color.text.secondary,
    cursor: 'pointer',
    fontFamily: T.font.family,
    transition: 'all 0.1s',
  },
  filterBtnActive: {
    background: T.color.navy800,
    color: T.color.ivory100,
    borderColor: T.color.navy700,
  },
  tableRow: {
    display: 'contents',
    cursor: 'pointer',
  },
  // Right sidebar panels
  rightPanel: {
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  },
  panel: {
    background: T.color.bg.card,
    border: `1px solid ${T.color.border.light}`,
    borderRadius: T.radius.lg,
    overflow: 'hidden',
  },
  panelHeader: {
    padding: '12px 16px',
    borderBottom: `1px solid ${T.color.border.light}`,
    fontSize: T.font.size.sm,
    fontWeight: T.font.weight.semibold,
    color: T.color.text.primary,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  deadlineItem: {
    padding: '8px 16px',
    borderBottom: `1px solid ${T.color.border.light}`,
    display: 'flex',
    gap: '10px',
    alignItems: 'flex-start',
    fontSize: T.font.size.sm,
    transition: 'background 0.1s',
    cursor: 'default',
  },
  deadlineDate: {
    fontSize: T.font.size.xs,
    fontWeight: T.font.weight.semibold,
    color: T.color.text.tertiary,
    minWidth: '48px',
    fontFamily: T.font.mono,
    paddingTop: '1px',
  },
  activityItem: {
    padding: '10px 16px',
    borderBottom: `1px solid ${T.color.border.light}`,
    display: 'flex',
    gap: '10px',
    alignItems: 'flex-start',
    fontSize: T.font.size.sm,
  },
  activityDot: {
    width: '6px',
    height: '6px',
    borderRadius: '50%',
    background: T.color.navy300,
    marginTop: '5px',
    flexShrink: 0,
  },
  activityTime: {
    fontSize: T.font.size.xs,
    color: T.color.text.tertiary,
    fontFamily: T.font.mono,
    minWidth: '28px',
    flexShrink: 0,
  },
};

function formatCurrency(val) {
  if (val >= 1000000) return '$' + (val / 1000000).toFixed(1) + 'M';
  if (val >= 1000) return '$' + (val / 1000).toFixed(0) + 'K';
  return '$' + val;
}

function Dashboard({ onOpenMatter }) {
  const [statusFilter, setStatusFilter] = useState('All');
  const [sortBy, setSortBy] = useState('lastActivity');
  const [hoveredRow, setHoveredRow] = useState(null);

  const matters = window.MATTERS;
  const deadlines = window.DEADLINES;
  const activity = window.RECENT_ACTIVITY;

  const statuses = ['All', 'Active', 'Discovery', 'Trial Prep', 'Settlement', 'Appeal'];
  const filtered = useMemo(() => {
    let m = statusFilter === 'All' ? matters : matters.filter(x => x.status === statusFilter);
    return m;
  }, [statusFilter]);

  const totalBilled = matters.reduce((s, m) => s + m.billed, 0);
  const totalBudget = matters.reduce((s, m) => s + m.budget, 0);
  const urgentDeadlines = deadlines.filter(d => d.urgent).length;

  return (
    <div style={dashStyles.container}>
      {/* Header */}
      <div style={dashStyles.header}>
        <div>
          <div style={dashStyles.greeting}>Good morning, Counselor</div>
          <div style={dashStyles.subtitle}>Sunday, April 20, 2026 — {matters.length} active matters</div>
        </div>
        <div style={{ display: 'flex', gap: '8px' }}>
          <button
            style={{...window.sharedStyles.btn, ...window.sharedStyles.btnPrimary}}
            onMouseEnter={e => e.currentTarget.style.opacity = '0.9'}
            onMouseLeave={e => e.currentTarget.style.opacity = '1'}
          >+ New Matter</button>
        </div>
      </div>

      {/* Stats */}
      <div style={dashStyles.statsRow}>
        <StatCard label="Active Matters" value="47" delta="3 this month" deltaType="up" />
        <StatCard label="Billed YTD" value={formatCurrency(totalBilled)} delta="12% vs prior year" deltaType="up" />
        <StatCard label="Realization Rate" value="91%" delta="2.4% improvement" deltaType="up" />
        <StatCard label="Pending Deadlines" value={urgentDeadlines.toString()} delta="Next 7 days" deltaType="" />
        <StatCard label="Docs in Review" value="342" delta="18 flagged by AI" deltaType="" />
      </div>

      {/* Main content grid */}
      <div style={dashStyles.mainGrid}>
        {/* Matters Table */}
        <div style={window.sharedStyles.tableContainer}>
          <div style={window.sharedStyles.tableHeader}>
            <span style={window.sharedStyles.tableTitle}>Matters</span>
            <div style={dashStyles.filterRow}>
              {statuses.map(s => (
                <button
                  key={s}
                  onClick={() => setStatusFilter(s)}
                  style={{
                    ...dashStyles.filterBtn,
                    ...(statusFilter === s ? dashStyles.filterBtnActive : {}),
                  }}
                >{s}</button>
              ))}
            </div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={window.sharedStyles.th}>Matter</th>
                <th style={{...window.sharedStyles.th, width: '100px'}}>Status</th>
                <th style={{...window.sharedStyles.th, width: '80px'}}>Lead</th>
                <th style={{...window.sharedStyles.th, width: '110px'}}>Billed / Budget</th>
                <th style={{...window.sharedStyles.th, width: '70px'}}>Docs</th>
                <th style={{...window.sharedStyles.th, width: '70px'}}>Due</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((m, i) => (
                <tr
                  key={m.id}
                  onClick={() => onOpenMatter(m)}
                  onMouseEnter={() => setHoveredRow(m.id)}
                  onMouseLeave={() => setHoveredRow(null)}
                  style={{
                    cursor: 'pointer',
                    background: hoveredRow === m.id ? T.color.bg.hover : 'transparent',
                    transition: 'background 0.1s',
                  }}
                >
                  <td style={window.sharedStyles.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <PriorityDot level={m.priority} />
                      <div>
                        <div style={{ fontWeight: T.font.weight.medium, fontSize: T.font.size.base, lineHeight: 1.3 }}>{m.name}</div>
                        <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{m.id} · {m.type}</div>
                      </div>
                    </div>
                  </td>
                  <td style={window.sharedStyles.td}><StatusTag status={m.status} /></td>
                  <td style={{...window.sharedStyles.td, fontSize: T.font.size.sm, color: T.color.text.secondary}}>{m.lead}</td>
                  <td style={window.sharedStyles.td}>
                    <div style={{ fontSize: T.font.size.sm, fontWeight: T.font.weight.medium }}>{formatCurrency(m.billed)}</div>
                    <MiniBar value={m.billed} max={m.budget} color={m.billed/m.budget > 0.85 ? T.color.status.warning : T.color.navy500} />
                  </td>
                  <td style={{...window.sharedStyles.td, fontSize: T.font.size.sm, fontFamily: T.font.mono, color: T.color.text.secondary}}>
                    {m.docs.toLocaleString()}
                  </td>
                  <td style={{...window.sharedStyles.td, fontSize: T.font.size.sm, color: T.color.text.secondary}}>
                    {new Date(m.dueDate).toLocaleDateString('en-US', {month:'short', day:'numeric'})}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Right panel: Deadlines + Activity */}
        <div style={dashStyles.rightPanel}>
          {/* Deadlines */}
          <div style={dashStyles.panel}>
            <div style={dashStyles.panelHeader}>
              <span>Upcoming Deadlines</span>
              <span style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, fontWeight: T.font.weight.normal }}>View all →</span>
            </div>
            {deadlines.slice(0, 6).map((d, i) => (
              <div
                key={i}
                style={{
                  ...dashStyles.deadlineItem,
                  background: d.urgent ? 'rgba(194,48,48,0.02)' : 'transparent',
                }}
              >
                <span style={{
                  ...dashStyles.deadlineDate,
                  color: d.urgent ? T.color.status.critical : T.color.text.tertiary,
                }}>{d.date}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: T.font.weight.medium, color: T.color.text.primary }}>{d.label}</div>
                  <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, marginTop: '1px' }}>{d.matter}</div>
                </div>
                {d.urgent && <span style={{ fontSize: '8px', color: T.color.status.critical }}>●</span>}
              </div>
            ))}
          </div>

          {/* Recent Activity */}
          <div style={dashStyles.panel}>
            <div style={dashStyles.panelHeader}>
              <span>Recent Activity</span>
              <span style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, fontWeight: T.font.weight.normal }}>View all →</span>
            </div>
            {activity.map((a, i) => (
              <div key={i} style={dashStyles.activityItem}>
                <span style={dashStyles.activityTime}>{a.time}</span>
                <div style={dashStyles.activityDot} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: T.font.weight.medium, color: T.color.text.primary }}>{a.action}</div>
                  <div style={{ color: T.color.text.secondary, marginTop: '1px' }}>{a.detail}</div>
                  <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, marginTop: '2px' }}>{a.matter} · {a.user}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
