import { useMemo } from 'react';

const TACTIC_ORDER = [
  'Reconnaissance',
  'Resource Dev',
  'Initial Access',
  'Execution',
  'Persistence',
  'Priv Escalation',
  'Defense Evasion',
  'Credential Access',
  'Discovery',
  'Lateral Movement',
  'Collection',
  'C2',
  'Exfiltration',
  'Impact',
];

const CELL_STYLES = [
  'bg-white/5',        // 0 — not seen
  'bg-ap-blue/40',     // 1 — low
  'bg-ap-yellow/50',   // 2 — medium
  'bg-ap-red/70',      // 3 — high
];

const LEGEND = [
  { label: 'None', style: 'bg-white/5' },
  { label: 'Low', style: 'bg-ap-blue/40' },
  { label: 'Med', style: 'bg-ap-yellow/50' },
  { label: 'High', style: 'bg-ap-red/70' },
];

function HeatCell({ technique, value }) {
  const bg = CELL_STYLES[value] ?? CELL_STYLES[0];

  return (
    <div
      className={`w-7 h-7 ${bg} border border-white/5 transition-colors hover:border-ap-silver-dim cursor-default`}
      title={`${technique} (${value})`}
    />
  );
}

export default function MitreHeatmap({ data = {} }) {
  // Build a stable ordered structure from the data prop
  const { tactics, maxRows } = useMemo(() => {
    const ordered = TACTIC_ORDER
      .filter((t) => data[t] != null)
      .map((tactic) => ({
        tactic,
        techniques: Object.entries(data[tactic]).map(([name, value]) => ({
          name,
          value: Math.max(0, Math.min(3, Number(value) || 0)),
        })),
      }));

    const max = ordered.reduce(
      (m, t) => Math.max(m, t.techniques.length),
      0,
    );

    return { tactics: ordered, maxRows: max };
  }, [data]);

  return (
    <div className="panel h-full flex flex-col">
      {/* Panel header */}
      <div className="panel-header">
        <span className="dot" />
        <span>MITRE ATT&CK Coverage</span>
      </div>

      {/* Scrollable heatmap area */}
      <div className="flex-1 overflow-x-auto overflow-y-auto p-3">
        {tactics.length === 0 ? (
          <div className="px-3 py-6 text-center font-mono text-xs text-ap-silver-dim">
            No MITRE data
          </div>
        ) : (
          <div className="inline-flex gap-px">
            {tactics.map(({ tactic, techniques }) => (
              <div key={tactic} className="flex flex-col items-center gap-px">
                {/* Tactic header — vertical text */}
                <div className="h-24 flex items-end justify-center pb-1">
                  <span
                    className="font-mono text-[9px] text-ap-silver-dim uppercase tracking-wide whitespace-nowrap select-none"
                    style={{
                      writingMode: 'vertical-rl',
                      transform: 'rotate(180deg)',
                    }}
                  >
                    {tactic}
                  </span>
                </div>

                {/* Technique cells */}
                {techniques.map(({ name, value }) => (
                  <HeatCell key={name} technique={name} value={value} />
                ))}

                {/* Pad empty rows so columns align */}
                {Array.from(
                  { length: maxRows - techniques.length },
                  (_, i) => (
                    <div key={`pad-${i}`} className="w-7 h-7" />
                  ),
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Legend */}
      <div className="flex items-center gap-3 px-3 py-2 border-t border-white/10">
        {LEGEND.map(({ label, style }) => (
          <div key={label} className="flex items-center gap-1.5">
            <span className={`inline-block w-3 h-3 ${style} border border-white/10`} />
            <span className="font-mono text-[9px] text-ap-silver-dim uppercase select-none">
              {label}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}
