import { useMemo, useState } from 'react';
import { X, Check } from 'lucide-react';
import AdaptationPreview from '@/components/universal/AdaptationPreview';
import { computeAdaptation, analyseCoverCompatibility } from '@/lib/adaptation';
import { pieceToLayer, layerImageMap } from '@/lib/canvasDemo';

const LABEL = { good: ['Best match', 'border-emerald-400/40 bg-emerald-400/10 text-emerald-300'], adaptable: ['Good fit', 'border-cyan-400/40 bg-cyan-400/10 text-cyan-200'], limited: ['Needs adjustment', 'border-amber-400/40 bg-amber-400/10 text-amber-200'], requires_processing: ['Limited space', 'border-slate-500 bg-slate-800/60 text-slate-300'] };

export default function CompareCovers({ open, onClose, covers, pieces, focalId, design, strategy }) {
  const [picked, setPicked] = useState(() => (Array.isArray(covers) ? covers : []).slice(0, 3).map(c => c.id));
  if (!open) return null;
  const list = (Array.isArray(covers) ? covers : []).filter(c => picked.includes(c.id)).slice(0, 3);
  const layers = pieces.map(p => pieceToLayer(p, focalId));
  const layerImages = layerImageMap(pieces);
  const ranked = list.map(c => ({ c, comp: analyseCoverCompatibility({ design, cover: c }) })).sort((a, b) => rank(a.comp) - rank(b.comp));
  const best = ranked[0]?.c.id;

  return (
    <div className="fixed inset-0 z-50">
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />
      <div className="absolute inset-x-2 top-10 bottom-2 mx-auto max-w-5xl overflow-y-auto rounded-2xl border border-white/10 bg-[#0a0e13] p-4">
        <header className="mb-3 flex items-center justify-between">
          <h2 className="font-heading text-lg font-semibold text-white">Compare covers</h2>
          <button onClick={onClose} className="icon-button"><X size={16} /></button>
        </header>
        <p className="mb-3 text-xs text-slate-400">Up to three fitted previews. The master design is unchanged across all of them.</p>
        <div className="mb-3 flex flex-wrap gap-1.5">
          {(Array.isArray(covers) ? covers : []).map(c => (
            <button key={c.id} onClick={() => setPicked(s => s.includes(c.id) ? s.filter(x => x !== c.id) : [...s, c.id].slice(0, 3))} className={`chip ${picked.includes(c.id) ? 'chip-active' : ''}`}>{picked.includes(c.id) && <Check size={11} />} {c.name}</button>
          ))}
        </div>
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {ranked.map(({ c, comp }) => {
            const adaptation = computeAdaptation({ design, layers, cover: c, strategy, mirror: 'none' });
            const [label, cls] = LABEL[comp.level] || LABEL.requires_processing;
            return (
              <article key={c.id} className={`panel p-3 ${best === c.id ? 'border-cyan-400/50' : ''}`}>
                <div className="mb-2 flex items-center justify-between">
                  <span className="truncate text-xs font-semibold text-white">{c.name}</span>
                  <span className={`rounded-full border px-2 py-0.5 text-[9px] font-semibold ${cls}`}>{label}</span>
                </div>
                <AdaptationPreview cover={c} adaptation={adaptation} layerImages={layerImages} demo />
                <p className="mt-2 text-[10px] text-slate-400">{c.limbType} · {c.side}</p>
              </article>
            );
          })}
        </div>
      </div>
    </div>
  );
}

const rank = (comp) => ({ good: 0, adaptable: 1, limited: 2, requires_processing: 3 }[comp.level] ?? 4);