export interface CohortWeekData {
  cohort_week: string;
  weeks: Record<string, number | null>;
}

interface Props {
  data: CohortWeekData[];
}

const WEEK_COLS = [0, 1, 2, 4, 8, 12];

function cellColor(rate: number | null | undefined): string {
  if (rate === null || rate === undefined) return 'bg-muted/30 text-muted-foreground';
  if (rate >= 40) return 'bg-success/10 text-success';
  if (rate >= 20) return 'bg-warning/10 text-warning';
  return 'bg-destructive/10 text-destructive';
}

export function CohortRetentionMatrix({ data }: Props) {
  if (data.length === 0) {
    return <p className="text-sm text-muted-foreground">No cohort data yet.</p>;
  }

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-xs">
        <thead>
          <tr>
            <th className="text-left pb-2 pr-3 text-muted-foreground">Cohort Week</th>
            {WEEK_COLS.map((w) => (
              <th key={w} className="text-center pb-2 px-1 text-muted-foreground">
                Wk {w}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {data.map((row) => (
            <tr key={row.cohort_week}>
              <td className="pr-3 py-1 text-muted-foreground">{row.cohort_week}</td>
              {WEEK_COLS.map((w) => {
                const rate = row.weeks[`week_${w}`];
                return (
                  <td key={w} className={`text-center px-1 py-1 rounded ${cellColor(rate)}`}>
                    {rate !== null && rate !== undefined ? `${rate}%` : '—'}
                  </td>
                );
              })}
            </tr>
          ))}
        </tbody>
      </table>
      <p className="text-xs text-muted-foreground mt-2">Target: week-4 ≥ 40% (green)</p>
    </div>
  );
}
