if (layout === "stepsHorizontal") {
    const margin=16, gap=6;
    const boxW=(size - margin*2 - gap*(count-1))/count, boxH=38, y= size*0.45;
    return (
      <svg width="100%" viewBox={`0 0 ${size} ${size}`}>
        {Array.from({length: count}, (_,i)=>{
          const x = margin + i*(boxW+gap);
          return (
            <g key={i}>
              <rect x={x} y={y} width={boxW} height={boxH} rx="8" fill={i%2?colorB:colorA} stroke="#fff" strokeWidth="1"/>
              <text x={x+8} y={y+14} fontSize="10" fill="#fff" fontWeight="700">{String(i+1).padStart(2,"0")}</text>
            </g>
          );
        })}
        <line x1={margin} y1={y+boxH+6} x2={size-margin} y2={y+boxH+6} stroke="#CBD5E1" strokeWidth="1"/>
      </svg>
    );
  }

  if (layout === "mindmap") {
    const perSide = Math.ceil(count/2);
    const leftX = 20, rightX = size-80;
    const topY = 30, stepY = (size-60)/(perSide-1 || 1);
    return (
      <svg width="100%" viewBox={`0 0 ${size} ${size}`}>
        <ellipse cx={cx} cy={cy} rx={34} ry={24} fill="#0F172A" stroke="#fff" strokeWidth="1"/>
        {/* left */}
        {Array.from({length: perSide}, (_,j)=>{
          const y = topY + j*stepY;
          return (
            <g key={`L${j}`}>
              <line x1={cx-10} y1={cy} x2={leftX+60} y2={y+16} stroke="#94A3B8" strokeWidth="1.2"/>
              <rect x={leftX} y={y} width={60} height={24} rx="6" fill={j%2?colorB:colorA} stroke="#fff" strokeWidth="1"/>
            </g>
          );
        })}
        {/* right */}
        {Array.from({length: perSide}, (_,j)=>{
          const y = topY + j*stepY;
          return (
            <g key={`R${j}`}>
              <line x1={cx+10} y1={cy} x2={rightX} y2={y+16} stroke="#94A3B8" strokeWidth="1.2"/>
              <rect x={rightX} y={y} width={60} height={24} rx="6" fill={j%2?colorB:colorA} stroke="#fff" strokeWidth="1"/>
            </g>
          );
        })}
      </svg>
    );
  }

  // circularList
  const pts = Array.from({length: count}, (_,i)=> {
    const a = (Math.PI*2*i)/count - Math.PI/2;
    return { x: cx + R*Math.cos(a), y: cy + R*Math.sin(a) };
  });
  return (
    <svg width="100%" viewBox={`0 0 ${size} ${size}`}>
      <circle cx={cx} cy={cy} r={R} fill="none" stroke="#CBD5E1" strokeWidth="1.2"/>
      {pts.map((p,i)=>(
        <circle key={i} cx={p.x} cy={p.y} r={dot/2} fill={i%2?colorB:colorA} stroke="#fff" strokeWidth="1"/>
      ))}
    </svg>
  );
}

export default function InfographicsLibrary() {
  const brand = useBrandKit();
  const [size, setSize] = useLocalStorage<Size>("ig.size","16x9");
  // selection + per-card color overrides
  const [selected, setSelected] = useState<Record<string, boolean>>({});
  const [overrides, setOverrides] = useState<Record<string, {a: string; b: string}>>({});

  const accents = [
    brand.colors.primary || "#0EA5E9",
    brand.colors.accent  || "#F59E0B",
    brand.colors.neutral || "#64748B",
    "#8B5CF6", "#22C55E", "#EF4444"
  ];

  function toggle(id: string) {
    setSelected(s => ({...s, [id]: !s[id]}));
  }

  function setColor(id: string, key: "a"|"b", value: string) {
    setOverrides(o => ({...o, [id]: {...(o[id] || {a: accents[0], b: accents[2]}), [key]: value}}));
  }

  async function quickDownload(item: LibraryItem) {
    const colors = [
      overrides[item.id]?.a || accents[item.colorAIdx ?? 0] || accents[0],
      overrides[item.id]?.b || accents[item.colorBIdx ?? 2] || accents[2]
    ];
    const payload = {
      size,
      layout: item.layout,
      count: item.count,
      centerTitle: (item.layout === "hubSpoke" || item.layout === "mindmap") ? "Topic" : undefined,
      labels: item.defaultLabels,
      notes: item.defaultNotes || [],
      colors, // use 2-colors: server cycles as needed
      brand: { fonts: { heading: brand.fonts?.heading || "Inter", body: brand.fonts?.body || "Inter" }, accents },
      iconsSvg: Array.from({length: item.count}, ()=>null),
      assets: { logoDataUrl: null, logoPlacement: "none", logoScale: 1 }
    };
    const res = await fetch("/api/infographics/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
    if (!res.ok) { alert("Generate failed"); return; }
    const blob = await res.blob();
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = `${item.name}.pptx`; a.click();
    URL.revokeObjectURL(url);
  }

  function addSelectedToTemplate() {
    // Flatten selected cards into pt.infographicsDetailed
    const key = "pt.infographicsDetailed";
    const prev = JSON.parse(localStorage.getItem(key) || "[]");

    const picks = LIBRARY.filter(i => selected[i.id]).map(i => {
      const colors = [
        overrides[i.id]?.a || accents[i.colorAIdx ?? 0] || accents[0],
        overrides[i.id]?.b || accents[i.colorBIdx ?? 2] || accents[2]
      ];
      return {
        layout: i.layout,
        count: i.count,
        centerTitle: (i.layout === "hubSpoke" || i.layout === "mindmap") ? "Topic" : undefined,
        labels: i.defaultLabels,
        notes: i.defaultNotes || [],
        // The template builder’s detailed renderer uses brand accents; include colors as hint
        colorsHint: colors,
      };
    });

    localStorage.setItem(key, JSON.stringify([...prev, ...picks]));
    alert(`${picks.length} page(s) added to your Presentation Template.`);
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Infographics Library</h1>
        <div className="flex items-center gap-2">
          <div className="hidden sm:flex gap-2">
            {(["16x9","4x3"] as Size[]).map(s=>(
              <button key={s} onClick={()=>setSize(s)}
                className={`px-3 py-1.5 rounded-lg border text-sm ${size===s?"bg-white/10 border-white/20":"border-white/10 hover:bg-white/5"}`}>
                {s}
              </button>
            ))}
          </div>
          <button onClick={addSelectedToTemplate} className="px-4 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white">
            Add Selected to Template
          </button>
        </div>
      </div>