// Dashboard · single unified canvas for the Manager persona
// (PM / EM / Manager are one role; all widgets live here).
//   row 1: Window State | At-Risk Tickets
//   row 2: Stakeholder commitment tracker (full)
//   row 3: Ticket Forensics Gantt (full)
//   row 4: Meeting Load + Fragmentation | Aged-tickets root-cause
//   row 5: Team load heatmap (full)
//   row 6: ETA calibration · per engineer (full)
// Pre-release defects + Post-PR rework now live on the Trends page.

function Dashboard({ navigate, openSidePanel, openTicketList, role }) {
  // Manager persona sees the full canvas. Self uses self-view.jsx instead.
  const headerWindow = DATA.windowFor(DATA.DEFAULT_WEEKS);

  // Team-load heatmap · window filter ('today' | 'week')
  const [loadMode, setLoadMode] = React.useState('today');

  // Stakeholder commitment tracker · next-N-weeks filter
  const [commitWeeks, setCommitWeeks] = React.useState(4);
  const commitDayCutoff = commitWeeks * 7;
  const dayMs = 86400000;
  const commitmentsFiltered = DATA.commitments.filter(c => {
    const eta = new Date(c.currentEta + 'T00:00:00');
    const daysUntil = Math.round((eta - DATA.TODAY) / dayMs);
    return daysUntil >= 0 && daysUntil <= commitDayCutoff;
  });

  const wipTone = (v, mode) => mode === 'today'
    ? (v > 4 ? 'bad' : v > 2 ? 'warn' : 'good')
    : (v > 8 ? 'bad' : v > 4 ? 'warn' : 'good');
  const meetingsTone = (v, mode) => mode === 'today'
    ? (v > 4 ? 'bad' : v > 2 ? 'warn' : 'good')
    : (v > 20 ? 'bad' : v > 12 ? 'warn' : 'good');
  const focusAccTone = (v, mode) => mode === 'today'
    ? (v >= 4 ? 'good' : v >= 2 ? 'warn' : 'bad')
    : (v >= 20 ? 'good' : v >= 12 ? 'warn' : 'bad');
  const longestTone = (v) => v >= 2 ? 'good' : v >= 1 ? 'warn' : 'bad';

  const heatmapCells = [
    { key: 'wip',      label: 'Tickets',       unit: null,
      fn: (e) => DATA.wipCountFor(e.id, loadMode),
      tone: (v) => wipTone(v, loadMode) },
    { key: 'meetings', label: 'Meetings',      unit: 'h',
      fn: (e) => DATA.meetingHrsFor(e.id, loadMode),
      tone: (v) => meetingsTone(v, loadMode) },
    { key: 'focus',    label: 'Total focus',   unit: 'h',
      fn: (e) => DATA.focusAccumulativeHrs(e.id, loadMode),
      tone: (v) => focusAccTone(v, loadMode) },
    { key: 'longest',  label: 'Deep focus', unit: 'h',
      fn: (e) => DATA.longestFocusHrs(e.id, loadMode),
      tone: (v) => longestTone(v) },
  ];

  return (
    <div className="page page-fade">
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>Dashboard</h1>
          <div className="mono-caps" style={{ marginTop: 4 }}>{headerWindow.dateLabel} · {DATA.viewer.team}</div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <span className="evidence-chip" title="theSitrep shows what happened · not what might happen.">
            <span className="ev-dot" />
            <span>Ground truth · observed only</span>
          </span>
        </div>
      </div>

      <div className="dash-grid">
        <div className="span-2">
          <NowSnapshot openTicketList={openTicketList} navigate={navigate} openSidePanel={openSidePanel} />
        </div>
        <div className="span-2">
          <AtRiskList navigate={navigate} />
        </div>
      </div>

      <div className="section-head">
        <div>
          <div className="section-eyebrow">Commitments · next {commitDayCutoff} days</div>
          <div className="section-title">Stakeholder commitment tracker</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="window-chip" role="group" aria-label="Commitments window">
            {[1, 2, 4, 8].map(w => (
              <button key={w}
                      className={`window-chip-opt ${w === commitWeeks ? 'active' : ''}`}
                      onClick={() => setCommitWeeks(w)}
                      title={`Next ${w * 7} days`}>{w}w</button>
            ))}
          </span>
          <span className="tag mono">{commitmentsFiltered.length} commitments</span>
        </div>
      </div>
      <div className="table-card">
        <table className="table">
          <thead>
            <tr>
              <th>Ticket</th>
              <th>Committed</th><th>Confidence</th><th>At-risk evidence</th>
            </tr>
          </thead>
          <tbody>
            {commitmentsFiltered.length === 0 ? (
              <tr>
                <td colSpan={4} style={{ textAlign: 'center', padding: '18px 12px', color: 'var(--text-3)', fontSize: 12.5 }}>
                  No commitments due in the next {commitDayCutoff} days.
                </td>
              </tr>
            ) : commitmentsFiltered.map(c => {
              const sig = DATA.commitmentSignals(c);
              return (
              <tr key={c.id} className="clickable" onClick={() => openSidePanel({ kind: 'commitment', commitment: c, title: c.label })}>
                <td>
                  <span className="mono" style={{ color: 'var(--text-2)' }}>{c.ticketId}</span>
                  <span style={{ marginLeft: 10 }}>{c.label}</span>
                </td>
                <td className="mono">{c.committedDate.slice(5)}</td>
                <td>
                  <span className={`tag mono tone-${sig.level}`}>{sig.label}</span>
                </td>
                <td style={{ color: sig.level === 'good' ? 'var(--text-3)' : 'var(--text-2)', fontSize: 12 }}>
                  {sig.headline}
                </td>
              </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="dash-grid" style={{ marginTop: 22 }}>
        <div className="span-2">
          <MeetingLoad />
        </div>
      </div>

      <div className="section-head">
        <div>
          <div className="section-eyebrow">Meetings & focus · per engineer</div>
          <div className="section-title">Team load heatmap</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="window-chip" role="group" aria-label="Load window">
            <button className={`window-chip-opt ${loadMode === 'today' ? 'active' : ''}`}
                    onClick={() => setLoadMode('today')}
                    title="Today only">Today</button>
            <button className={`window-chip-opt ${loadMode === 'week' ? 'active' : ''}`}
                    onClick={() => setLoadMode('week')}
                    title="Last 7 days">Last week</button>
          </span>
          <span className="tag mono">{DATA.engineers.length} engineers</span>
          <button className="btn ghost" style={{ fontSize: 11, display: 'inline-flex', alignItems: 'center', gap: 6 }}
                  onClick={() => openSidePanel({ kind: 'heatmap-legend', loadMode, title: 'Legend' })}>
            <Icon name="info" size={12} />
            Legend
          </button>
        </div>
      </div>
      <div className="table-card">
        <table className="heatmap-table">
          <thead>
            <tr>
              <th className="col-name">Developer</th>
              {heatmapCells.map(c => <th key={c.key}>{c.label}</th>)}
            </tr>
          </thead>
          <tbody>
            {DATA.engineers.map(e => (
              <tr key={e.id} className="clickable" onClick={() => navigate('#/dev/' + e.id)}>
                <td className="col-name">
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                    <Avatar initials={e.initials} size={22} />
                    <span>{e.name}</span>
                  </span>
                </td>
                {heatmapCells.map(c => {
                  const v = c.fn(e);
                  const t = c.tone(v);
                  return (
                    <td key={c.key}>
                      <span className={`heatmap-cell ${t ? 'tone-' + t : ''}`}>
                        <span className="hm-num">{v}</span>
                        {c.unit && <span className="hm-unit">{c.unit}</span>}
                      </span>
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
