const { useState, useRef, useEffect, useCallback } = React;

// ── Backend API URL ──
const API_URL = window.location.hostname === "localhost" ? "http://localhost:3001" : "";

const FONTS_CSS = `@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,600;0,700;0,800;1,400;1,600&family=DM+Sans:wght@300;400;500;600;700&family=Caveat:wght@400;500;600;700&display=swap');`;

// ═══════════════════════════════════════════════════════
// ─── HAND-DRAWN SVG ICON LIBRARY ─────────────────────
// ═══════════════════════════════════════════════════════
const ICON_SVG = {
  femme: `<path d="M28 14c-3 0-5.5 2.2-5.5 5 0 2.8 2.5 5 5.5 5s5.5-2.2 5.5-5-2.5-5-5.5-5z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M18 38c0-6 4.5-10 10-10s10 4 10 10" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M24 19c2 3 6 3 8 0" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M20 12 Q24 8 28 10 Q28 8 32 12" fill="none" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/>`,
  homme: `<circle cx="28" cy="17" r="6" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M18 38c0-6 4.5-10 10-10s10 4 10 10" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M25 25 L28 30 L31 25" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>`,
  enfant: `<circle cx="28" cy="16" r="5" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M21 36c0-5 3.2-8 7-8s7 3 7 8" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M24 13 Q28 10 32 13" fill="none" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M26 32 L28 36 L30 32" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  nongenre: `<path d="M28 10 L32 18 L40 19 L34 25 L36 34 L28 30 L20 34 L22 25 L16 19 L24 18 Z" fill="none" stroke="#2D2926" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/><circle cx="28" cy="22" r="3" fill="none" stroke="#B8956A" stroke-width="1.5"/><path d="M28 38 L28 46" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M24 42 L32 42" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/>`,
  sablier: `<ellipse cx="28" cy="28" rx="9" ry="16" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M19 20 Q28 24 37 20" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M19 36 Q28 32 37 36" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M19 28 L37 28" stroke="#C4B8A8" stroke-width="1" stroke-dasharray="3,3"/>`,
  rectangle: `<rect x="18" y="12" width="20" height="32" rx="2" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M18 28 L38 28" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  triangle: `<path d="M22 12 L14 44 L42 44 L34 12 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18 28 Q28 26 38 28" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  triangle_inv: `<path d="M14 12 L22 44 L34 44 L42 12 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18 28 Q28 30 38 28" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  rond: `<ellipse cx="28" cy="28" rx="14" ry="16" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M14 28 L42 28" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  metre: `<path d="M8 28 Q8 12 28 8 Q48 12 48 28 Q48 44 28 48 Q8 44 8 28 Z" fill="none" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round"/><path d="M14 16 L14 22" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M20 12 L20 16" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M36 12 L36 16" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M42 16 L42 22" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/>`,
  poitrine: `<ellipse cx="28" cy="20" rx="10" ry="6" fill="none" stroke="#2D2926" stroke-width="2"/><path d="M14 20 L42 20" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M16 18 L16 22" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M40 18 L40 22" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  taille_m: `<path d="M20 16 Q28 14 36 16 L38 40 Q28 42 18 40 Z" fill="none" stroke="#2D2926" stroke-width="2"/><path d="M16 26 L40 26" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M18 24 L18 28" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M38 24 L38 28" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  hanches: `<path d="M18 16 Q18 12 28 12 Q38 12 38 16 L40 36 Q28 40 16 36 Z" fill="none" stroke="#2D2926" stroke-width="2"/><path d="M14 34 L42 34" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M16 32 L16 36" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M40 32 L40 36" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  hauteur: `<path d="M28 8 L28 48" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M24 10 L32 10" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M24 46 L32 46" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M32 18 L36 18" stroke="#2D2926" stroke-width="1" stroke-linecap="round"/><path d="M32 28 L36 28" stroke="#2D2926" stroke-width="1" stroke-linecap="round"/><path d="M32 38 L36 38" stroke="#2D2926" stroke-width="1" stroke-linecap="round"/>`,
  carrure: `<path d="M12 22 L44 22" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M14 18 L14 26" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M42 18 L42 26" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M12 28 Q28 34 44 28" fill="none" stroke="#C4B8A8" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  buste: `<path d="M28 10 L28 40" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M24 12 L32 12" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M24 38 L32 38" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M20 12 Q28 8 36 12" fill="none" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M32 22 L36 22" stroke="#2D2926" stroke-width="1" stroke-linecap="round"/>`,
  bras: `<path d="M18 12 Q12 24 10 44" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><circle cx="10" cy="44" r="3" fill="none" stroke="#2D2926" stroke-width="2"/><path d="M18 12 L18 8" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M14 10 L22 10" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  cou: `<ellipse cx="28" cy="24" rx="10" ry="8" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M18 24 L38 24" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  taille_tag: `<path d="M16 14 L40 14 Q42 14 42 16 L42 36 Q42 38 40 38 L16 38 Q14 38 14 36 L14 16 Q14 14 16 14 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M14 22 L42 22" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/><circle cx="36" cy="18" r="2" fill="#B8956A"/>`,
  robe: `<path d="M22 10 Q24 8 28 8 Q32 8 34 10 L36 18 Q38 28 38 34 L38 46" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M22 10 L20 18 Q18 28 18 34 L18 46" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M18 46 Q28 48 38 46" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M20 22 Q28 20 36 22" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/><line x1="28" y1="22" x2="28" y2="44" stroke="#C4B8A8" stroke-width="1" stroke-dasharray="6,4"/>`,
  haut: `<path d="M20 14 Q24 10 28 10 Q32 10 36 14" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M20 14 L12 20 L16 22 L18 20 L18 36 Q28 38 38 36 L38 20 L40 22 L44 20 L36 14" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M22 18 Q28 16 34 18" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  pantalon: `<path d="M16 14 L12 42 Q12 46 16 46 L24 46 L26 14" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M40 14 L44 42 Q44 46 40 46 L32 46 L30 14" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16 14 L40 14" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M14 28 L42 28" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  jupe: `<path d="M16 14 L12 44 Q28 48 44 44 L40 14 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16 14 L40 14" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M14 28 Q28 26 42 28" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/><line x1="28" y1="14" x2="28" y2="44" stroke="#C4B8A8" stroke-width="1" stroke-dasharray="6,4"/>`,
  veste: `<path d="M20 12 Q24 10 28 10 Q32 10 36 12" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M20 12 L10 18 L8 34 L16 34 L16 44 Q28 46 40 44 L40 34 L48 34 L46 18 L36 12" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M24 14 Q28 18 32 14" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  combinaison: `<path d="M20 10 Q28 8 36 10 L38 24 L40 46 L34 46 L32 26 L24 26 L22 46 L16 46 L18 24 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18 18 Q28 16 38 18" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  lingerie: `<path d="M20 18 Q28 14 36 18 L36 36 Q28 40 20 36 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M24 18 L24 14" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M32 18 L32 14" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M20 26 Q28 24 36 26" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M26 30 Q28 34 30 30" fill="none" stroke="#B8956A" stroke-width="1.2" stroke-linecap="round"/>`,
  accessoire: `<path d="M12 20 L12 40 Q12 44 16 44 L40 44 Q44 44 44 40 L44 20 Q44 16 40 16 L16 16 Q12 16 12 20 Z" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M20 16 Q20 10 28 10 Q36 10 36 16" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M20 28 L36 28" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/><circle cx="28" cy="34" r="2" fill="none" stroke="#B8956A" stroke-width="1.5"/>`,
  boheme: `<path d="M28 10 Q34 16 36 24 Q38 32 28 38 Q18 32 20 24 Q22 16 28 10 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M24 20 Q28 24 32 20" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M26 28 Q28 32 30 28" fill="none" stroke="#B8956A" stroke-width="1.2" stroke-linecap="round"/><circle cx="28" cy="42" r="2" fill="#B8956A" opacity="0.5"/>`,
  minimaliste: `<rect x="14" y="14" width="28" height="28" rx="1" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M14 28 L42 28" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  romantique: `<path d="M28 14 Q40 14 40 24 Q40 32 28 38 Q16 32 16 24 Q16 14 28 14 Z" fill="rgba(184,149,106,0.08)" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round"/><path d="M24 22 Q28 28 32 22" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  streetwear: `<path d="M12 38 L20 14 L36 14 L44 38 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M20 14 L28 8 L36 14" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18 28 L38 28" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  classique: `<path d="M20 12 L36 12 L40 44 L16 44 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M22 12 Q28 8 34 12" fill="none" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><circle cx="28" cy="20" r="3" fill="none" stroke="#B8956A" stroke-width="1.5"/><path d="M28 23 L28 40" stroke="#B8956A" stroke-width="1" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  vintage: `<circle cx="28" cy="24" r="14" fill="none" stroke="#2D2926" stroke-width="2.5"/><circle cx="28" cy="24" r="5" fill="none" stroke="#B8956A" stroke-width="1.5"/><path d="M28 10 L28 14" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M28 34 L28 38" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M14 24 L18 24" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M38 24 L42 24" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M28 42 L32 46" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/>`,
  avantgarde: `<path d="M14 40 L28 10 L42 40" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M28 10 L28 40" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><circle cx="28" cy="26" r="5" fill="none" stroke="#B8956A" stroke-width="1.5"/>`,
  sportwear: `<path d="M16 20 Q28 12 40 20 L42 38 Q28 42 14 38 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M22 28 L28 22 L34 28" fill="none" stroke="#B8956A" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M28 22 L28 36" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/>`,
  couture: `<path d="M28 8 L32 16 L42 18 L34 26 L36 36 L28 30 L20 36 L22 26 L14 18 L24 16 Z" fill="none" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="28" cy="22" r="4" fill="none" stroke="#2D2926" stroke-width="1.5"/>`,
  quotidien: `<circle cx="28" cy="24" r="10" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M28 14 L28 8" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M38 24 L44 24" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M12 24 L18 24" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M28 34 L28 40" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M34 18 L38 14" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M18 18 L14 14" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  bureau: `<path d="M12 16 L44 16 L44 40 L12 40 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M20 16 L20 12 L36 12 L36 16" fill="none" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 24 L44 24" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><circle cx="28" cy="32" r="2" fill="#B8956A"/>`,
  soiree: `<path d="M28 8 Q30 16 36 22 Q30 20 28 28 Q26 20 20 22 Q26 16 28 8 Z" fill="none" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round"/><circle cx="22" cy="36" r="3" fill="none" stroke="#2D2926" stroke-width="1.5"/><circle cx="34" cy="38" r="2" fill="none" stroke="#2D2926" stroke-width="1.5"/><circle cx="28" cy="44" r="2" fill="none" stroke="#2D2926" stroke-width="1"/>`,
  weekend: `<path d="M10 34 Q18 18 28 18 Q38 18 46 34" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M10 34 L46 34" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M28 18 L28 10" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M28 10 L34 12" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M14 40 Q28 44 42 40" fill="none" stroke="#C4B8A8" stroke-width="1.5" stroke-linecap="round"/>`,
  ceremonie: `<path d="M18 40 L18 20 Q18 14 24 14 L28 14" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M38 40 L38 20 Q38 14 32 14 L28 14" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M22 24 Q28 30 34 24" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><circle cx="18" cy="12" r="4" fill="none" stroke="#B8956A" stroke-width="1.5"/><circle cx="38" cy="12" r="4" fill="none" stroke="#B8956A" stroke-width="1.5"/>`,
  sport: `<circle cx="28" cy="16" r="5" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M28 21 L28 34" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M28 26 L18 34" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M28 26 L38 34" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M28 34 L20 46" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M28 34 L36 46" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M20 46 L36 46" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="3,3" stroke-linecap="round"/>`,
  ciseaux: `<path d="M14 14 L26 38" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round"/><path d="M42 14 L30 38" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round"/><path d="M14 14 Q10 10 14 8" fill="none" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round"/><path d="M42 14 Q46 10 42 8" fill="none" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round"/><ellipse cx="28" cy="40" rx="6" ry="4" fill="none" stroke="#B8956A" stroke-width="2"/>`,
  machine: `<path d="M10 34 Q10 12 28 12 Q46 12 46 34" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M10 34 L46 34" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M10 34 L10 42 Q28 46 46 42 L46 34" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M22 20 L22 28" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M28 18 L28 28" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M34 20 L34 28" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  fer: `<path d="M14 44 L14 12 L42 12 L42 44" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 44 L42 44" stroke="#2D2926" stroke-width="2.5"/><path d="M20 12 L20 8" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M28 12 L28 8" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M36 12 L36 8" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/>`,
  mannequin: `<path d="M28 8 L28 42" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M22 42 L34 42" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><circle cx="28" cy="46" r="3" fill="none" stroke="#2D2926" stroke-width="2"/><path d="M20 20 L36 20" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M18 26 L38 26" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M20 32 L36 32" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  surjeteuse: `<path d="M10 28 L20 28 L24 18 L28 36 L32 22 L36 30 L40 28 L46 28" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16 38 L40 38" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  tapis: `<rect x="12" y="20" width="32" height="20" rx="1" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M12 20 L12 40" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round"/><path d="M18 24 L18 36" stroke="#C4B8A8" stroke-width="1" stroke-dasharray="3,3"/><path d="M24 24 L24 36" stroke="#C4B8A8" stroke-width="1" stroke-dasharray="3,3"/><path d="M30 24 L30 36" stroke="#C4B8A8" stroke-width="1" stroke-dasharray="3,3"/><path d="M36 24 L36 36" stroke="#C4B8A8" stroke-width="1" stroke-dasharray="3,3"/>`,
  fermeture: `<path d="M16 12 L40 12 L42 44 L14 44 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M28 18 L28 22" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M28 26 L28 30" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M28 34 L28 38" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/>`,
  bouton: `<circle cx="28" cy="20" r="5" fill="none" stroke="#2D2926" stroke-width="2.5"/><circle cx="28" cy="20" r="2" fill="#2D2926"/><circle cx="28" cy="36" r="5" fill="none" stroke="#2D2926" stroke-width="2.5"/><circle cx="28" cy="36" r="2" fill="#2D2926"/><path d="M14 28 L42 28" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  pince: `<path d="M12 28 Q20 12 28 12 Q36 12 44 28 Q36 44 28 44 Q20 44 12 28 Z" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M18 28 L38 28" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M28 18 L28 38" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  coton: `<path d="M12 16 Q18 14 24 16 Q30 18 36 16 Q42 14 48 16" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M12 24 Q18 22 24 24 Q30 26 36 24 Q42 22 48 24" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M12 32 Q18 30 24 32 Q30 34 36 32 Q42 30 48 32" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M12 40 Q18 38 24 40 Q30 42 36 40 Q42 38 48 40" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><circle cx="18" cy="20" r="2" fill="#B8956A" opacity="0.3"/><circle cx="36" cy="28" r="2" fill="#B8956A" opacity="0.3"/>`,
  lin: `<path d="M28 46 L28 14" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M28 14 L22 8" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M28 14 L34 8" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M28 20 L20 14" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M28 20 L36 14" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M28 28 L22 22" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M28 28 L34 22" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M24 46 L32 46" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/>`,
  soie: `<path d="M12 14 Q28 10 44 14 Q40 28 44 42 Q28 46 12 42 Q16 28 12 14 Z" fill="rgba(184,149,106,0.06)" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M16 20 Q28 18 40 20" fill="none" stroke="#B8956A" stroke-width="1" stroke-linecap="round" opacity="0.5"/><path d="M14 28 Q28 26 42 28" fill="none" stroke="#B8956A" stroke-width="1" stroke-linecap="round" opacity="0.5"/><path d="M16 36 Q28 34 40 36" fill="none" stroke="#B8956A" stroke-width="1" stroke-linecap="round" opacity="0.5"/>`,
  laine: `<path d="M14 14 Q14 10 18 12 Q22 14 22 10 Q26 12 28 10 Q30 12 34 10 Q34 14 38 12 Q42 10 42 14" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M14 14 L14 42 L42 42 L42 14" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M20 20 Q20 24 24 24 Q28 24 28 20 Q28 24 32 24 Q36 24 36 20" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M20 30 Q20 34 24 34 Q28 34 28 30 Q28 34 32 34 Q36 34 36 30" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  jersey: `<rect x="12" y="18" width="32" height="20" rx="1" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M12 24 Q20 22 28 24 Q36 26 44 24" fill="none" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M12 32 Q20 30 28 32 Q36 34 44 32" fill="none" stroke="#2D2926" stroke-width="1.5" stroke-linecap="round"/><path d="M8 28 L12 28" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M44 28 L48 28" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/>`,
  crepe: `<path d="M12 14 Q16 18 20 14 Q24 10 28 14 Q32 10 36 14 Q40 18 44 14" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M12 24 Q16 28 20 24 Q24 20 28 24 Q32 20 36 24 Q40 28 44 24" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M12 34 Q16 38 20 34 Q24 30 28 34 Q32 30 36 34 Q40 38 44 34" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M12 44 Q16 48 20 44 Q24 40 28 44" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><circle cx="20" cy="19" r="1.5" fill="#B8956A" opacity="0.4"/>`,
  jean: `<rect x="12" y="14" width="32" height="28" rx="1" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M18 14 L18 42" stroke="#2D2926" stroke-width="1.5"/><path d="M24 14 L24 42" stroke="#2D2926" stroke-width="1.5"/><path d="M30 14 L30 42" stroke="#2D2926" stroke-width="1.5"/><path d="M36 14 L36 42" stroke="#2D2926" stroke-width="1.5"/><path d="M14 26 L42 26" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="4,3" stroke-linecap="round"/>`,
  velours: `<rect x="12" y="14" width="32" height="28" rx="1" fill="none" stroke="#2D2926" stroke-width="2"/><path d="M14 18 L16 16 L18 18 L20 16 L22 18 L24 16 L26 18 L28 16 L30 18 L32 16 L34 18 L36 16 L38 18 L40 16 L42 18" fill="none" stroke="#C4B8A8" stroke-width="1"/><path d="M14 26 L16 24 L18 26 L20 24 L22 26 L24 24 L26 26 L28 24 L30 26 L32 24 L34 26 L36 24 L38 26 L40 24 L42 26" fill="none" stroke="#C4B8A8" stroke-width="1"/><path d="M12 22 L12 12" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/>`,
  question_mark: `<circle cx="28" cy="28" r="14" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M22 22 Q22 16 28 16 Q34 16 34 22 Q34 26 28 28 L28 32" fill="none" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><circle cx="28" cy="38" r="2" fill="#B8956A"/>`,
  coeur: `<path d="M28 14 Q40 14 40 24 Q40 32 28 40 Q16 32 16 24 Q16 14 28 14 Z" fill="rgba(184,149,106,0.1)" stroke="#B8956A" stroke-width="2.5"/><path d="M24 22 Q28 28 32 22" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  check: `<path d="M12 28 L22 38 L44 16" fill="none" stroke="#B8956A" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`,
  chat: `<path d="M14 38 L14 18 Q14 14 18 14 L38 14 Q42 14 42 18 L42 30 Q42 34 38 34 L22 34 L14 38 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M20 22 L36 22" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M20 28 L30 28" stroke="#C4B8A8" stroke-width="1.5" stroke-linecap="round"/>`,
  micro: `<circle cx="28" cy="28" r="14" fill="none" stroke="#2D2926" stroke-width="2.5"/><circle cx="28" cy="28" r="6" fill="#B8956A" opacity="0.8"/><circle cx="28" cy="28" r="10" fill="none" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="3,3"/>`,
  patron_pdf: `<path d="M16 12 L40 12 Q44 12 44 16 L44 40 Q44 44 40 44 L16 44 Q12 44 12 40 L12 16 Q12 12 16 12 Z" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M12 22 L44 22" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M18 30 L26 30" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M18 36 L34 36" stroke="#C4B8A8" stroke-width="1.5" stroke-linecap="round"/>`,
  livraison: `<path d="M14 18 L14 40 L42 40 L42 18 L28 10 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M22 40 L22 30 L34 30 L34 40" fill="none" stroke="#2D2926" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><circle cx="38" cy="24" r="2" fill="#B8956A" opacity="0.5"/>`,
  budget: `<circle cx="28" cy="28" r="14" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M24 22 Q24 18 28 18 Q32 18 32 22 Q32 26 28 26 Q24 26 24 30 Q24 34 28 34 Q32 34 32 30" fill="none" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M28 14 L28 18" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/><path d="M28 34 L28 42" stroke="#B8956A" stroke-width="1.5" stroke-linecap="round"/>`,
  horloge: `<circle cx="28" cy="28" r="14" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M28 18 L28 28 L36 32" fill="none" stroke="#B8956A" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><circle cx="28" cy="28" r="2" fill="#2D2926"/>`,
  calendrier: `<rect x="12" y="16" width="32" height="28" rx="3" fill="none" stroke="#2D2926" stroke-width="2.5"/><path d="M12 24 L44 24" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M20 12 L20 20" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M36 12 L36 20" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><circle cx="22" cy="32" r="2" fill="#B8956A"/><circle cx="28" cy="32" r="2" fill="#C4B8A8"/><circle cx="34" cy="32" r="2" fill="#C4B8A8"/>`,
  eclair: `<path d="M32 8 L20 28 L28 28 L24 48 L36 24 L28 24 Z" fill="none" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>`,
  infini: `<path d="M28 28 Q20 16 14 28 Q20 40 28 28 Q36 16 42 28 Q36 40 28 28" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><circle cx="14" cy="28" r="2" fill="#B8956A"/><circle cx="42" cy="28" r="2" fill="#B8956A"/>`,
  niveau_debutant: `<path d="M14 40 L28 12 L42 40 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M28 34 L28 28" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><circle cx="28" cy="22" r="2.5" fill="#B8956A"/>`,
  niveau_inter: `<path d="M14 40 L28 12 L42 40 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M20 34 L36 34" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M24 28 L32 28" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/>`,
  niveau_avance: `<path d="M14 40 L28 12 L42 40 Z" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M20 34 L36 34" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M24 28 L32 28" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/><path d="M27 22 L29 22" stroke="#B8956A" stroke-width="2" stroke-linecap="round"/>`,
  niveau_expert: `<path d="M14 40 L28 12 L42 40 Z" fill="rgba(184,149,106,0.06)" stroke="#B8956A" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M22 30 L28 24 L34 30" fill="none" stroke="#B8956A" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><circle cx="28" cy="36" r="2" fill="#B8956A"/>`,
  main: `<path d="M28 10 L28 38" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M22 14 L22 34" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M34 14 L34 34" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M16 20 L16 34" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M40 20 L40 34" stroke="#2D2926" stroke-width="2" stroke-linecap="round"/><path d="M16 34 Q16 44 28 44 Q40 44 40 34" fill="none" stroke="#2D2926" stroke-width="2.5" stroke-linecap="round"/><path d="M22 26 L34 26" stroke="#B8956A" stroke-width="1.5" stroke-dasharray="3,3" stroke-linecap="round"/>`,
};

function Icon({ name, size = 24, style: extraStyle }) {
  const svg = ICON_SVG[name];
  if (!svg) return <span style={{ fontSize: size * 0.8, lineHeight: 1, ...extraStyle }}>{name}</span>;
  return (
    <svg viewBox="0 0 56 56" width={size} height={size}
      style={{ display: "inline-block", verticalAlign: "middle", flexShrink: 0, ...extraStyle }}
      dangerouslySetInnerHTML={{ __html: svg }} />
  );
}

// ── LOGO PATRONIA — Premium brand mark ──
function Logo({ size = "default", light = false }) {
  const s = size === "large" ? 1.4 : size === "small" ? 0.85 : 1;
  const textColor = light ? "#fff" : "#1A1A1A";
  const accentColor = light ? "rgba(255,255,255,0.45)" : "#B8956A";

  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 0, lineHeight: 1, userSelect: "none" }}>
      {/* Pure typographic wordmark — Celine/The Row aesthetic */}
      <span style={{
        fontFamily: "'Playfair Display'", fontSize: 21 * s, fontWeight: 700, color: textColor,
        letterSpacing: "0.12em", textTransform: "uppercase",
      }}>Patron</span>
      <span style={{
        fontFamily: "'Playfair Display'", fontSize: 21 * s, fontWeight: 400, color: textColor,
        letterSpacing: "0.12em", textTransform: "uppercase",
        fontStyle: "italic", marginLeft: 1 * s,
      }}>ia</span>
      {/* Minimal accent dot */}
      <span style={{
        display: "inline-block", width: 4.5 * s, height: 4.5 * s, borderRadius: "50%",
        background: accentColor, marginLeft: 3 * s,
      }} />
    </div>
  );
}

const INSPIRATIONS = [
  { id: 1, title: "Robe portefeuille fluide", style: "Bohème", img: "https://images.unsplash.com/photo-1595777457583-95e059d581b8?w=500&h=700&fit=crop", tags: ["Fluide", "Été", "Élégant"] },
  { id: 2, title: "Blazer oversize structuré", style: "Minimaliste", img: "https://images.unsplash.com/photo-1591369822096-ffd140ec948f?w=500&h=700&fit=crop", tags: ["Structuré", "Bureau", "Moderne"] },
  { id: 3, title: "Jupe plissée midi", style: "Classique", img: "https://images.unsplash.com/photo-1583496661160-fb5886a0uj9a?w=500&h=700&fit=crop", tags: ["Plissé", "Mi-saison", "Féminin"] },
  { id: 4, title: "Top à manches ballon", style: "Romantique", img: "https://images.unsplash.com/photo-1564257631407-4deb1f99d992?w=500&h=700&fit=crop", tags: ["Volume", "Détail", "Printemps"] },
  { id: 5, title: "Pantalon large palazzo", style: "Bohème chic", img: "https://images.unsplash.com/photo-1509631179647-0177331693ae?w=500&h=700&fit=crop", tags: ["Ample", "Confort", "Été"] },
  { id: 6, title: "Trench coat ceinturé", style: "Parisien", img: "https://images.unsplash.com/photo-1548624313-0396c75e4cea?w=500&h=700&fit=crop", tags: ["Classique", "Automne", "Intemporel"] },
  { id: 7, title: "Chemisier à col lavallière", style: "Rétro", img: "https://images.unsplash.com/photo-1551803091-e20673f15770?w=500&h=700&fit=crop", tags: ["Détail", "Élégant", "Bureau"] },
  { id: 8, title: "Combinaison ajustée", style: "Contemporain", img: "https://images.unsplash.com/photo-1515886657613-9f3515b0c78f?w=500&h=700&fit=crop", tags: ["Moderne", "Pratique", "Soirée"] },
];

// ─── AUDIO RECORDER ──────────────────────────────────
function useAudioRecorder() {
  const [isRecording, setIsRecording] = useState(false);
  const [audioURL, setAudioURL] = useState(null);
  const [duration, setDuration] = useState(0);
  const mediaRecorder = useRef(null);
  const chunks = useRef([]);
  const timerRef = useRef(null);

  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      mediaRecorder.current = new MediaRecorder(stream);
      chunks.current = [];
      mediaRecorder.current.ondataavailable = (e) => chunks.current.push(e.data);
      mediaRecorder.current.onstop = () => {
        const blob = new Blob(chunks.current, { type: "audio/webm" });
        setAudioURL(URL.createObjectURL(blob));
        stream.getTracks().forEach(t => t.stop());
      };
      mediaRecorder.current.start();
      setIsRecording(true);
      setDuration(0);
      timerRef.current = setInterval(() => setDuration(d => d + 1), 1000);
    } catch { /* mic unavailable */ }
  };
  const stopRecording = () => {
    if (mediaRecorder.current && isRecording) {
      mediaRecorder.current.stop();
      setIsRecording(false);
      clearInterval(timerRef.current);
    }
  };
  const clearRecording = () => { setAudioURL(null); setDuration(0); };
  return { isRecording, audioURL, duration, startRecording, stopRecording, clearRecording };
}

// ─── AUTRE INPUT (TEXT + AUDIO) ──────────────────────
function AutreInput({ value, onChange, onAudioChange, placeholder }) {
  const { isRecording, audioURL, duration, startRecording, stopRecording, clearRecording } = useAudioRecorder();
  const [mode, setMode] = useState("text");
  const fmt = (s) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;

  useEffect(() => { if (audioURL) onAudioChange?.(audioURL); }, [audioURL]);

  return (
    <div style={{ marginTop: 10, animation: "fadeSlideIn 0.3s ease" }}>
      <div style={{ display: "flex", gap: 6, marginBottom: 8 }}>
        {["text", "audio"].map(m => (
          <button key={m} onClick={() => { setMode(m); if (m === "audio" && !isRecording && !audioURL) startRecording(); }}
            style={{
              flex: 1, padding: "9px 12px", borderRadius: 10,
              border: mode === m ? "2px solid #B8956A" : "2px solid #EDE8E2",
              background: mode === m ? "rgba(184,149,106,0.04)" : "#FDFBF9",
              fontFamily: "'DM Sans'", fontSize: 12, fontWeight: 500, cursor: "pointer",
              color: mode === m ? "#B8956A" : "#888", display: "flex", alignItems: "center", justifyContent: "center", gap: 5,
            }}>
            {m === "text" ? "✏️ Écrire" : isRecording ? `⏺️ ${fmt(duration)}` : audioURL ? "🎤 Enregistré ✓" : "🎤 Dicter"}
          </button>
        ))}
      </div>
      {mode === "text" && (
        <textarea value={value || ""} onChange={e => onChange(e.target.value)} placeholder={placeholder}
          rows={2} style={{
            width: "100%", border: "2px solid #EDE8E2", borderRadius: 12, padding: "10px 14px",
            fontFamily: "'DM Sans'", fontSize: 13, outline: "none", background: "#fff",
            resize: "vertical", lineHeight: 1.5, boxSizing: "border-box",
          }}
          onFocus={e => e.target.style.borderColor = "#B8956A"}
          onBlur={e => e.target.style.borderColor = "#EDE8E2"}
        />
      )}
      {mode === "audio" && isRecording && (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 16px", background: "rgba(184,149,106,0.04)", borderRadius: 12, border: "2px solid rgba(184,149,106,0.12)" }}>
          <div style={{ width: 10, height: 10, borderRadius: "50%", background: "#B8956A", animation: "pulse 1.5s infinite" }} />
          <span style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#B8956A", fontWeight: 500, flex: 1 }}>{fmt(duration)}</span>
          <button onClick={stopRecording} style={{ background: "#B8956A", border: "none", color: "#fff", padding: "7px 16px", borderRadius: 8, fontFamily: "'DM Sans'", fontSize: 12, fontWeight: 600, cursor: "pointer" }}>⏹ Stop</button>
        </div>
      )}
      {mode === "audio" && audioURL && !isRecording && (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 12px", background: "#F8F4F0", borderRadius: 12, border: "2px solid #EDE8E2" }}>
          <audio src={audioURL} controls style={{ flex: 1, height: 32 }} />
          <button onClick={() => { clearRecording(); onAudioChange?.(null); }} style={{ background: "none", border: "none", fontSize: 16, cursor: "pointer", color: "#999" }}>✕</button>
          <button onClick={startRecording} style={{ background: "none", border: "none", fontSize: 12, cursor: "pointer", color: "#B8956A", fontFamily: "'DM Sans'", fontWeight: 500 }}>Refaire</button>
        </div>
      )}
    </div>
  );
}

// ─── MEASUREMENT INPUT ───────────────────────────────
function MeasurementInput({ label, unit, value, onChange, icon, placeholder, tip }) {
  const [focused, setFocused] = useState(false);
  return (
    <div style={{
      background: "#FDFBF9", border: focused ? "2px solid #B8956A" : "2px solid #EDE8E2", borderRadius: 14,
      padding: "10px 14px", display: "flex", alignItems: "center", gap: 10, transition: "border-color 0.2s",
    }}>
      <Icon name={icon} size={22} />
      <div style={{ flex: 1 }}>
        <label style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", fontWeight: 500, display: "block", marginBottom: 2 }}>{label}</label>
        <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
          <input type="number" value={value || ""} onChange={e => onChange(e.target.value)} placeholder={placeholder}
            onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
            style={{ border: "none", outline: "none", fontFamily: "'DM Sans'", fontSize: 16, fontWeight: 600, color: "#2D2926", width: 60, background: "transparent" }} />
          <span style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#BBB" }}>{unit}</span>
        </div>
      </div>
      {tip && <span title={tip} style={{ cursor: "help", opacity: 0.4 }}><Icon name="question_mark" size={16} /></span>}
    </div>
  );
}

// ─── MULTI-SELECT CHIPS ──────────────────────────────
function MultiSelectChips({ options, selected, onToggle }) {
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
      {options.map(opt => {
        const isSelected = selected.includes(opt.value);
        return (
          <button key={opt.value} onClick={() => onToggle(opt.value)}
            style={{
              padding: "8px 16px", borderRadius: 50,
              border: isSelected ? "2px solid #2D2926" : "2px solid #EDE8E2",
              background: isSelected ? "#2D2926" : "#FDFBF9",
              color: isSelected ? "#fff" : "#666",
              fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 500, cursor: "pointer",
              display: "flex", alignItems: "center", gap: 6, transition: "all 0.2s",
            }}>
            <Icon name={opt.icon} size={16} />{opt.label}
          </button>
        );
      })}
    </div>
  );
}

// ─── SLIDER INPUT ────────────────────────────────────
function SliderInput({ label, min, max, step, value, onChange, unit, marks }) {
  return (
    <div style={{ padding: "4px 0" }}>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
        <span style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#666" }}>{label}</span>
        <span style={{ fontFamily: "'DM Sans'", fontSize: 15, fontWeight: 700, color: "#B8956A" }}>{value}{unit}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value}
        onChange={e => onChange(Number(e.target.value))}
        style={{ width: "100%", accentColor: "#B8956A", cursor: "pointer" }} />
      {marks && (
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 4 }}>
          {marks.map(m => <span key={m} style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#BBB" }}>{m}</span>)}
        </div>
      )}
    </div>
  );
}

// ─── STEP INDICATOR ──────────────────────────────────
function StepIndicator({ step, onStepClick }) {
  const steps = [
    { num: 1, label: "Projet" },
    { num: 2, label: "Inspirations" },
    { num: 3, label: "Patron" },
    { num: 4, label: "Finaliser" },
  ];
  return (
    <div style={{ padding: "20px 28px 14px", maxWidth: 480, margin: "0 auto" }}>
      {/* Progress bar */}
      <div style={{ position: "relative", height: 2, background: "#EDE8E2", borderRadius: 2, marginBottom: 12 }}>
        <div style={{
          position: "absolute", left: 0, top: 0, height: "100%", borderRadius: 2,
          width: `${((step - 1) / (steps.length - 1)) * 100}%`,
          background: "linear-gradient(90deg, #1A1A1A, #B8956A)",
          transition: "width 0.5s cubic-bezier(0.4,0,0.2,1)",
        }} />
        {/* Step dots on the bar */}
        {steps.map((s, i) => (
          <div key={s.num}
            onClick={() => s.num <= step && onStepClick(s.num)}
            style={{
              position: "absolute", top: "50%", transform: "translateY(-50%)",
              left: `${(i / (steps.length - 1)) * 100}%`,
              marginLeft: i === 0 ? 0 : i === steps.length - 1 ? -10 : -5,
              cursor: s.num <= step ? "pointer" : "default",
            }}>
            <div style={{
              width: s.num === step ? 12 : 10,
              height: s.num === step ? 12 : 10,
              borderRadius: "50%",
              background: s.num < step ? "#2D2926" : s.num === step ? "#B8956A" : "#D8D2CC",
              border: s.num === step ? "2px solid #fff" : "none",
              boxShadow: s.num === step ? "0 0 0 2px #B8956A, 0 2px 8px rgba(26,26,26,0.15)" : "none",
              transition: "all 0.4s ease",
            }} />
          </div>
        ))}
      </div>
      {/* Labels */}
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        {steps.map(s => (
          <span key={s.num}
            onClick={() => s.num <= step && onStepClick(s.num)}
            style={{
              fontFamily: "'DM Sans'", fontSize: 11,
              fontWeight: s.num === step ? 600 : 400,
              color: s.num === step ? "#B8956A" : s.num < step ? "#2D2926" : "#CCC",
              cursor: s.num <= step ? "pointer" : "default",
              transition: "all 0.3s ease",
              letterSpacing: "0.01em",
              textAlign: s.num === 1 ? "left" : s.num === steps.length ? "right" : "center",
              flex: 1,
            }}>{s.label}</span>
        ))}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// ─── STEP 1: COMPREHENSIVE QUESTIONNAIRE ─────────────
// ═══════════════════════════════════════════════════════
function StepQuestionnaire({ data, setData, onNext }) {
  const [currentQ, setCurrentQ] = useState(0);
  const [autreOpen, setAutreOpen] = useState({});
  const [autreText, setAutreText] = useState({});
  const [autreAudio, setAutreAudio] = useState({});

  const updateData = (key, value) => setData(prev => ({ ...prev, [key]: value }));
  const updateNested = (parent, key, value) => setData(prev => ({ ...prev, [parent]: { ...(prev[parent] || {}), [key]: value } }));
  const toggleMulti = (key, value) => {
    const arr = data[key] || [];
    updateData(key, arr.includes(value) ? arr.filter(v => v !== value) : [...arr, value]);
  };

  // ── ALL QUESTIONS ──────────────────────────────────
  const questions = [
    // ▸ SECTION 1: PROFIL
    {
      key: "genre", section: "Votre profil", sectionIcon: "femme", sectionColor: "#8B6F47",
      label: "Pour qui est ce vêtement ?",
      subtitle: "La base de patronage diffère selon la morphologie",
      type: "cards",
      options: [
        { value: "femme", label: "Femme", icon: "femme", desc: "Morphologie féminine" },
        { value: "homme", label: "Homme", icon: "homme", desc: "Morphologie masculine" },
        { value: "enfant", label: "Enfant", icon: "enfant", desc: "Taille enfant 2-14 ans" },
        { value: "non-genre", label: "Non-genré", icon: "nongenre", desc: "Coupe unisexe" },
      ],
      autrePlaceholder: "Ex: c'est pour ma fille de 16 ans, elle est grande pour son âge...",
    },
    {
      key: "taille_standard", section: "Votre profil", sectionIcon: "femme", sectionColor: "#8B6F47",
      label: "Quelle est votre taille habituelle en prêt-à-porter ?",
      subtitle: "Si vous hésitez entre deux tailles, choisissez la plus grande",
      type: "cards",
      options: [
        { value: "XS", label: "XS", icon: "taille_tag", desc: "34–36" },
        { value: "S", label: "S", icon: "taille_tag", desc: "36–38" },
        { value: "M", label: "M", icon: "taille_tag", desc: "38–40" },
        { value: "L", label: "L", icon: "taille_tag", desc: "40–42" },
        { value: "XL", label: "XL", icon: "taille_tag", desc: "42–44" },
        { value: "XXL+", label: "XXL+", icon: "taille_tag", desc: "46+" },
      ],
      autrePlaceholder: "Ex: je fais du 38 en haut mais du 42 en bas, je dois souvent grader entre les tailles...",
    },
    {
      key: "mensurations", section: "Vos mensurations", sectionIcon: "metre", sectionColor: "#B8956A",
      label: "Vos mensurations précises",
      subtitle: "Prenez vos mesures sur sous-vêtements, mètre ruban bien à plat sans serrer. Ces données sont essentielles pour un patron ajusté.",
      type: "measurements",
      fields: [
        { key: "tour_poitrine", label: "Tour de poitrine", icon: "poitrine", unit: "cm", placeholder: "88", tip: "Au point le plus fort de la poitrine" },
        { key: "tour_taille", label: "Tour de taille", icon: "taille_m", unit: "cm", placeholder: "68", tip: "Au creux naturel de la taille" },
        { key: "tour_hanches", label: "Tour de hanches", icon: "hanches", unit: "cm", placeholder: "96", tip: "Au point le plus fort des hanches" },
        { key: "hauteur_totale", label: "Taille (hauteur)", icon: "hauteur", unit: "cm", placeholder: "165", tip: "Pieds nus, dos contre un mur" },
        { key: "carrure_dos", label: "Carrure dos", icon: "carrure", unit: "cm", placeholder: "38", tip: "D'une emmanchure à l'autre dans le dos" },
        { key: "longueur_buste", label: "Longueur buste", icon: "buste", unit: "cm", placeholder: "42", tip: "De l'épaule à la taille" },
        { key: "longueur_bras", label: "Longueur bras", icon: "bras", unit: "cm", placeholder: "60", tip: "De l'épaule au poignet, bras légèrement plié" },
        { key: "tour_cou", label: "Tour de cou", icon: "cou", unit: "cm", placeholder: "36", tip: "À la base du cou" },
      ],
      autrePlaceholder: "Ex: je ne connais pas toutes mes mensurations, je fais habituellement du 40 en haut et du 42 en bas. J'ai une forte poitrine (bonnet E)...",
    },
    {
      key: "morphologie", section: "Votre profil", sectionIcon: "femme", sectionColor: "#8B6F47",
      label: "Quelle est votre morphologie ?",
      subtitle: "Cela détermine les ajustements du patron (FBA, SBA, épaules, longueur...)",
      type: "cards",
      columns: 3,
      options: [
        { value: "sablier", label: "Sablier", icon: "sablier", desc: "Épaules ≈ hanches, taille marquée" },
        { value: "rectangle", label: "Rectangle", icon: "rectangle", desc: "Silhouette équilibrée, peu de taille" },
        { value: "triangle", label: "Triangle", icon: "triangle", desc: "Hanches plus larges que les épaules" },
        { value: "triangle_inv", label: "Triangle inversé", icon: "triangle_inv", desc: "Épaules plus larges que les hanches" },
        { value: "rond", label: "Rond", icon: "rond", desc: "Rondeurs harmonieuses" },
      ],
      autrePlaceholder: "Ex: j'ai des épaules tombantes, une forte poitrine et je suis petite (1m55)...",
    },
    {
      key: "ajustements", section: "Votre profil", sectionIcon: "femme", sectionColor: "#8B6F47",
      label: "Avez-vous besoin d'ajustements spécifiques ?",
      subtitle: "Sélectionnez tout ce qui s'applique — nous adapterons le patron",
      type: "multi",
      options: [
        { value: "fba", label: "FBA (forte poitrine)", icon: "patron_pdf" },
        { value: "sba", label: "SBA (petite poitrine)", icon: "patron_pdf" },
        { value: "epaules_larges", label: "Épaules larges", icon: "carrure" },
        { value: "epaules_etroites", label: "Épaules étroites", icon: "carrure" },
        { value: "petite", label: "Ajustement petite taille", icon: "hauteur" },
        { value: "grande", label: "Ajustement grande taille", icon: "hauteur" },
        { value: "dos_rond", label: "Dos rond", icon: "rond" },
        { value: "ventre_rond", label: "Ventre rond", icon: "rond" },
        { value: "aucun", label: "Aucun ajustement", icon: "check" },
      ],
      autrePlaceholder: "Ex: j'ai un bras plus court que l'autre suite à un accident, et une hanche plus haute...",
    },

    // ▸ SECTION 2: LE PROJET
    {
      key: "type", section: "Votre projet", sectionIcon: "robe", sectionColor: "#2D6B4F",
      label: "Quel type de vêtement souhaitez-vous créer ?",
      subtitle: "Choisissez la pièce qui vous fait envie",
      type: "cards",
      columns: 3,
      options: [
        { value: "robe", label: "Robe", icon: "robe", desc: "Courte, midi ou longue" },
        { value: "haut", label: "Haut / Blouse", icon: "haut", desc: "Top, chemise, blouse" },
        { value: "pantalon", label: "Pantalon", icon: "pantalon", desc: "Droit, large, slim" },
        { value: "jupe", label: "Jupe", icon: "jupe", desc: "Droite, plissée, évasée" },
        { value: "veste", label: "Veste / Manteau", icon: "veste", desc: "Blazer, trench, parka" },
        { value: "combinaison", label: "Combinaison", icon: "combinaison", desc: "Combi pantalon ou short" },
        { value: "lingerie", label: "Lingerie", icon: "lingerie", desc: "Sous-vêtements, pyjama" },
        { value: "accessoire", label: "Accessoire", icon: "accessoire", desc: "Sac, chapeau, écharpe" },
        { value: "enfant", label: "Vêtement enfant", icon: "enfant", desc: "Tailles enfant" },
      ],
      autrePlaceholder: "Ex: une salopette avec des bretelles croisées dans le dos et des poches plaquées sur le devant...",
    },
    {
      key: "style", section: "Votre projet", sectionIcon: "robe", sectionColor: "#2D6B4F",
      label: "Quel style recherchez-vous ?",
      subtitle: "Cela guidera les inspirations et les détails du patron",
      type: "cards",
      columns: 3,
      options: [
        { value: "boheme", label: "Bohème", icon: "boheme", desc: "Fluide et naturel" },
        { value: "minimaliste", label: "Minimaliste", icon: "minimaliste", desc: "Épuré et moderne" },
        { value: "romantique", label: "Romantique", icon: "romantique", desc: "Féminin et détaillé" },
        { value: "streetwear", label: "Streetwear", icon: "streetwear", desc: "Urbain et cool" },
        { value: "classique", label: "Classique", icon: "classique", desc: "Intemporel et chic" },
        { value: "vintage", label: "Vintage", icon: "vintage", desc: "Rétro 50s-80s" },
        { value: "avant-garde", label: "Avant-garde", icon: "avantgarde", desc: "Créatif et audacieux" },
        { value: "sportwear", label: "Sportswear", icon: "sportwear", desc: "Confort et performance" },
        { value: "couture", label: "Haute couture", icon: "couture", desc: "Raffiné et luxueux" },
      ],
      autrePlaceholder: "Ex: un mix entre vintage années 70 et moderne scandinave, avec des couleurs automnales...",
    },
    {
      key: "occasion", section: "Votre projet", sectionIcon: "robe", sectionColor: "#2D6B4F",
      label: "Pour quelle occasion ?",
      subtitle: "Le contexte influence le tombé, le tissu et les finitions",
      type: "cards",
      options: [
        { value: "quotidien", label: "Quotidien", icon: "quotidien", desc: "Confort au jour le jour" },
        { value: "bureau", label: "Bureau", icon: "bureau", desc: "Professionnel et chic" },
        { value: "soiree", label: "Soirée", icon: "soiree", desc: "Événement spécial" },
        { value: "weekend", label: "Weekend", icon: "weekend", desc: "Détente et loisirs" },
        { value: "ceremonie", label: "Cérémonie", icon: "ceremonie", desc: "Mariage, gala..." },
        { value: "sport", label: "Sport / Actif", icon: "sport", desc: "Mouvement et stretch" },
      ],
      autrePlaceholder: "Ex: un mariage champêtre en plein air fin juin, il fera chaud, je suis invitée (pas la mariée)...",
    },
    {
      key: "personnalisation", section: "Personnalisation", sectionIcon: "ciseaux", sectionColor: "#7B4BAA",
      label: "Quels détails souhaitez-vous ajouter ?",
      subtitle: "Sélectionnez les éléments qui vous plaisent — on les intégrera au patron",
      type: "multi",
      options: [
        { value: "poches", label: "Poches", icon: "pantalon" },
        { value: "col", label: "Col spécial", icon: "haut" },
        { value: "manches_speciales", label: "Manches originales", icon: "bras" },
        { value: "ceinture", label: "Ceinture / Lien", icon: "metre" },
        { value: "boutons", label: "Boutonnage", icon: "bouton" },
        { value: "volants", label: "Volants / Froufrous", icon: "crepe" },
        { value: "decoupe", label: "Découpes originales", icon: "ciseaux" },
        { value: "asymetrie", label: "Asymétrie", icon: "avantgarde" },
        { value: "dos_nu", label: "Dos travaillé", icon: "haut" },
        { value: "fentes", label: "Fentes", icon: "patron_pdf" },
        { value: "doublure", label: "Doublure", icon: "coton" },
        { value: "simple", label: "Rester simple", icon: "minimaliste" },
      ],
      autrePlaceholder: "Ex: je voudrais un col lavallière amovible, des poches dans les coutures côté et un ourlet arrondi...",
    },

    // ▸ SECTION 3: NIVEAU & FAISABILITÉ
    {
      key: "niveau", section: "Niveau & faisabilité", sectionIcon: "niveau_debutant", sectionColor: "#3D7B5F",
      label: "Quel est votre niveau en couture ?",
      subtitle: "Nous adapterons la complexité du patron et les instructions",
      type: "cards",
      options: [
        { value: "debutant", label: "Débutant·e", icon: "niveau_debutant", desc: "Premières pièces, coutures droites" },
        { value: "intermediaire", label: "Intermédiaire", icon: "niveau_inter", desc: "Fermetures, pinces, manches" },
        { value: "avance", label: "Avancé·e", icon: "niveau_avance", desc: "Doublures, cols, ajustements" },
        { value: "expert", label: "Expert·e", icon: "niveau_expert", desc: "Toutes techniques maîtrisées" },
      ],
      autrePlaceholder: "Ex: j'ai fait 3 projets simples (totebag, jupe élastiquée, top), je n'ai jamais posé de fermeture éclair...",
    },
    {
      key: "techniques_maitrisees", section: "Niveau & faisabilité", sectionIcon: "niveau_debutant", sectionColor: "#3D7B5F",
      label: "Quelles techniques maîtrisez-vous ?",
      subtitle: "Cochez celles que vous avez déjà pratiquées avec succès",
      type: "multi",
      options: [
        { value: "couture_droite", label: "Coutures droites", icon: "metre" },
        { value: "fermeture_eclair", label: "Fermeture éclair", icon: "fermeture" },
        { value: "boutonnieres", label: "Boutonnières", icon: "bouton" },
        { value: "montage_manches", label: "Montage de manches", icon: "bras" },
        { value: "pinces", label: "Pinces", icon: "patron_pdf" },
        { value: "col", label: "Pose de col", icon: "haut" },
        { value: "couture_anglaise", label: "Couture anglaise", icon: "metre" },
        { value: "surjet", label: "Surjet / Overlock", icon: "surjeteuse" },
        { value: "ourlet_invisible", label: "Ourlet invisible", icon: "metre" },
        { value: "doublure", label: "Pose de doublure", icon: "coton" },
        { value: "biais", label: "Pose de biais", icon: "metre" },
        { value: "elastique", label: "Pose d'élastique", icon: "jersey" },
        { value: "jersey", label: "Couture jersey", icon: "jersey" },
        { value: "rien", label: "Je débute !", icon: "niveau_debutant" },
      ],
      autrePlaceholder: "Ex: je me débrouille en couture droite et j'ai fait quelques ourlets, mais je galère avec les fermetures éclair...",
    },
    {
      key: "toile_essai", section: "Niveau & faisabilité", sectionIcon: "niveau_debutant", sectionColor: "#3D7B5F",
      label: "Comptez-vous faire une toile d'essai ?",
      subtitle: "Recommandé pour les projets complexes ou les tissus précieux",
      type: "cards",
      options: [
        { value: "oui", label: "Oui", icon: "check", desc: "Je teste avant le tissu final" },
        { value: "non", label: "Non", icon: "ciseaux", desc: "Je coupe directement" },
        { value: "pas_sur", label: "Pas sûr·e", icon: "question_mark", desc: "Conseillez-moi" },
      ],
      autrePlaceholder: "Ex: je ne sais pas si c'est nécessaire, mon tissu est cher et je ne veux pas le gâcher...",
    },

    // ▸ SECTION 4: TISSU & FOURNITURES
    {
      key: "tissu_type", section: "Tissu & fournitures", sectionIcon: "coton", sectionColor: "#8B5E3C",
      label: "Quel type de tissu allez-vous utiliser ?",
      subtitle: "Le tissu détermine les techniques de couture et le rendu final",
      type: "cards",
      columns: 3,
      options: [
        { value: "coton", label: "Coton", icon: "coton", desc: "Popeline, percale, batiste" },
        { value: "lin", label: "Lin", icon: "lin", desc: "Léger à moyen" },
        { value: "soie", label: "Soie / Satin", icon: "soie", desc: "Fluide et glissant" },
        { value: "laine", label: "Laine / Lainage", icon: "laine", desc: "Drap, tweed, flanelle" },
        { value: "jersey", label: "Jersey / Maille", icon: "jersey", desc: "Extensible, confort" },
        { value: "crepe", label: "Crêpe / Viscose", icon: "crepe", desc: "Fluide, beau tombé" },
        { value: "jean", label: "Denim / Jean", icon: "jean", desc: "Épais, structuré" },
        { value: "velours", label: "Velours", icon: "velours", desc: "Avec sens du poil" },
        { value: "pas_encore", label: "Pas encore choisi", icon: "question_mark", desc: "Conseillez-moi !" },
      ],
      autrePlaceholder: "Ex: j'ai un coupon de crêpe de viscose vert sauge de 2m50 en 140cm de laize...",
    },
    {
      key: "tissu_details", section: "Tissu & fournitures", sectionIcon: "coton", sectionColor: "#8B5E3C",
      label: "Précisions sur votre tissu",
      subtitle: "Ces détails influencent le placement des pièces et le métrage",
      type: "multi",
      options: [
        { value: "motif_directionnel", label: "Motifs avec sens", icon: "velours" },
        { value: "rayures", label: "Rayures / Carreaux", icon: "jean" },
        { value: "extensible", label: "Tissu extensible", icon: "jersey" },
        { value: "transparent", label: "Tissu transparent", icon: "soie" },
        { value: "epais", label: "Tissu épais", icon: "laine" },
        { value: "glissant", label: "Tissu glissant", icon: "soie" },
        { value: "uni", label: "Uni, sans contrainte", icon: "check" },
        { value: "pas_encore", label: "Pas encore acheté", icon: "question_mark" },
      ],
      autrePlaceholder: "Ex: c'est un wax africain avec de grands motifs, je voudrais qu'ils soient bien centrés sur le devant...",
    },
    {
      key: "materiel", section: "Tissu & fournitures", sectionIcon: "coton", sectionColor: "#8B5E3C",
      label: "De quel matériel disposez-vous ?",
      subtitle: "On adaptera les finitions en fonction de vos outils",
      type: "multi",
      options: [
        { value: "machine_basique", label: "Machine à coudre basique", icon: "machine" },
        { value: "machine_avancee", label: "Machine avec points fantaisie", icon: "machine" },
        { value: "surjeteuse", label: "Surjeteuse", icon: "surjeteuse" },
        { value: "recouvreuse", label: "Recouvreuse", icon: "surjeteuse" },
        { value: "cutter_rotatif", label: "Cutter rotatif + tapis", icon: "tapis" },
        { value: "mannequin", label: "Mannequin de couture", icon: "mannequin" },
        { value: "presse_repasser", label: "Fer / Presse à repasser", icon: "fer" },
        { value: "couture_main", label: "Couture main uniquement", icon: "main" },
      ],
      autrePlaceholder: "Ex: j'ai une Brother FS40 avec pied pour fermeture invisible, pas de surjeteuse mais je fais des finitions au zigzag...",
    },

    // ▸ SECTION 5: BUDGET & PLANNING
    {
      key: "budget", section: "Budget & planning", sectionIcon: "budget", sectionColor: "#2D6B8A",
      label: "Quel est votre budget total pour ce projet ?",
      subtitle: "Tissu + fournitures + patron — cela nous aide à vous conseiller",
      type: "cards",
      options: [
        { value: "moins_30", label: "Moins de 30€", icon: "budget", desc: "Petit budget" },
        { value: "30_60", label: "30 – 60€", icon: "budget", desc: "Budget moyen" },
        { value: "60_100", label: "60 – 100€", icon: "budget", desc: "Budget confortable" },
        { value: "plus_100", label: "Plus de 100€", icon: "couture", desc: "Sans contrainte" },
        { value: "pas_defini", label: "Pas encore défini", icon: "question_mark", desc: "À voir selon le projet" },
      ],
      autrePlaceholder: "Ex: j'ai déjà le tissu, je cherche juste le patron. Budget patron max 25€...",
    },
    {
      key: "delai", section: "Budget & planning", sectionIcon: "budget", sectionColor: "#2D6B8A",
      label: "Avez-vous un délai ?",
      subtitle: "Si c'est pour un événement, on priorisera la faisabilité",
      type: "cards",
      options: [
        { value: "urgent", label: "< 1 semaine", icon: "eclair", desc: "Urgent !" },
        { value: "2_semaines", label: "2 semaines", icon: "calendrier", desc: "Un peu de temps" },
        { value: "1_mois", label: "1 mois", icon: "calendrier", desc: "Confortable" },
        { value: "pas_presse", label: "Pas pressé·e", icon: "horloge", desc: "Je prends mon temps" },
      ],
      autrePlaceholder: "Ex: c'est pour un mariage le 28 juin, j'ai 6 semaines devant moi mais je ne couds que le weekend...",
    },
    {
      key: "temps_couture", section: "Budget & planning", sectionIcon: "budget", sectionColor: "#2D6B8A",
      label: "Combien de temps pouvez-vous consacrer à la couture ?",
      subtitle: "Pour estimer le nombre de sessions nécessaires",
      type: "cards",
      options: [
        { value: "1h_semaine", label: "~1h / semaine", icon: "horloge", desc: "Quelques moments" },
        { value: "3h_semaine", label: "~3h / semaine", icon: "horloge", desc: "Sessions régulières" },
        { value: "weekend", label: "Un weekend entier", icon: "calendrier", desc: "Sessions longues" },
        { value: "illimite", label: "Autant que nécessaire", icon: "infini", desc: "Flexible" },
      ],
      autrePlaceholder: "Ex: je couds le mercredi après-midi et le samedi matin, environ 5h par semaine...",
    },

    // ▸ SECTION 6: PRÉFÉRENCES PATRON
    {
      key: "format_patron", section: "Préférences patron", sectionIcon: "patron_pdf", sectionColor: "#555",
      label: "Quelles préférences pour votre patron ?",
      subtitle: "On personnalise aussi la documentation et les instructions",
      type: "multi",
      options: [
        { value: "marges_incluses", label: "Marges de couture incluses", icon: "metre" },
        { value: "multitaille", label: "Patron multitaille", icon: "hauteur" },
        { value: "instructions_detaillees", label: "Instructions très détaillées", icon: "patron_pdf" },
        { value: "schema_montage", label: "Schémas de montage", icon: "patron_pdf" },
        { value: "video", label: "Tutoriel vidéo", icon: "patron_pdf" },
        { value: "liste_fournitures", label: "Liste de fournitures complète", icon: "coton" },
        { value: "plan_decoupe", label: "Plan de découpe inclus", icon: "ciseaux" },
        { value: "reperes_crans", label: "Repères et crans bien visibles", icon: "pince" },
      ],
      autrePlaceholder: "Ex: j'aimerais que les marges soient à 1,5cm, avec un A0 et un format A4 à assembler...",
    },
  ];

  const q = questions[currentQ];
  const progress = ((currentQ + 1) / questions.length) * 100;
  const isAutre = autreOpen[q.key];

  const handleCardSelect = (value) => {
    updateData(q.key, value);
    setAutreOpen(p => ({ ...p, [q.key]: false }));
    if (q.type === "cards") {
      setTimeout(() => { if (currentQ < questions.length - 1) setCurrentQ(currentQ + 1); }, 350);
    }
  };

  const goNext = () => {
    if (currentQ < questions.length - 1) setCurrentQ(currentQ + 1);
    else onNext();
  };

  const hasAnswer = () => {
    if (q.type === "measurements") {
      const m = data.mensurations || {};
      return m.tour_poitrine || m.tour_taille || m.tour_hanches;
    }
    if (q.type === "multi") return (data[q.key] || []).length > 0 || isAutre;
    return !!data[q.key] || isAutre;
  };

  return (
    <div style={{ maxWidth: 720, margin: "0 auto", padding: "0 20px" }}>
      {/* Progress */}
      <div style={{ margin: "10px 0 20px" }}>
        <div style={{ height: 4, background: "#F0EBE5", borderRadius: 4, overflow: "hidden" }}>
          <div style={{ height: "100%", width: `${progress}%`, background: "linear-gradient(90deg, #1A1A1A, #333)", borderRadius: 4, transition: "width 0.6s cubic-bezier(0.4,0,0.2,1)" }} />
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6 }}>
          <span style={{ fontFamily: "'DM Sans'", fontSize: 11, color: q.sectionColor, fontWeight: 600, display: "flex", alignItems: "center", gap: 5 }}><Icon name={q.sectionIcon} size={14} />{q.section}</span>
          <span style={{ fontFamily: "'DM Sans'", fontSize: 11, color: "#BBB" }}>{currentQ + 1} / {questions.length}</span>
        </div>
      </div>

      {/* Question content */}
      <div key={currentQ} style={{ animation: "fadeSlideIn 0.45s ease" }}>
        <h2 style={{ fontFamily: "'Playfair Display', serif", fontSize: 24, fontWeight: 700, color: "#2D2926", marginBottom: 6, lineHeight: 1.3 }}>{q.label}</h2>
        <p style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#888", marginBottom: 22, fontWeight: 300, lineHeight: 1.5 }}>{q.subtitle}</p>

        {/* ── CARDS ── */}
        {q.type === "cards" && (
          <div style={{ display: "grid", gridTemplateColumns: `repeat(${q.columns || (q.options.length <= 4 ? 2 : 3)}, 1fr)`, gap: 10 }}>
            {q.options.map(opt => {
              const sel = data[q.key] === opt.value && !isAutre;
              return (
                <button key={opt.value} onClick={() => handleCardSelect(opt.value)} style={{
                  background: sel ? "linear-gradient(135deg, #2D2926, #4A3F3A)" : "#FDFBF9",
                  border: sel ? "2px solid #2D2926" : "2px solid #EDE8E2",
                  borderRadius: 14, padding: "16px 10px", cursor: "pointer",
                  display: "flex", flexDirection: "column", alignItems: "center", gap: 5,
                  transition: "all 0.25s cubic-bezier(0.4,0,0.2,1)",
                  transform: sel ? "scale(0.97)" : "scale(1)",
                  boxShadow: sel ? "0 4px 16px rgba(45,41,38,0.18)" : "0 1px 4px rgba(0,0,0,0.03)",
                }}>
                  <Icon name={opt.icon} size={30} style={sel ? { filter: "brightness(0) invert(1)" } : {}} />
                  <span style={{ fontFamily: "'DM Sans'", fontWeight: 600, fontSize: 13, color: sel ? "#fff" : "#2D2926" }}>{opt.label}</span>
                  <span style={{ fontFamily: "'DM Sans'", fontWeight: 300, fontSize: 10, color: sel ? "rgba(255,255,255,0.6)" : "#AAA", textAlign: "center", lineHeight: 1.3 }}>{opt.desc}</span>
                </button>
              );
            })}
          </div>
        )}

        {/* ── MULTI-SELECT ── */}
        {q.type === "multi" && (
          <MultiSelectChips options={q.options} selected={data[q.key] || []} onToggle={(v) => toggleMulti(q.key, v)} />
        )}

        {/* ── MEASUREMENTS ── */}
        {q.type === "measurements" && (
          <div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              {q.fields.map(f => (
                <MeasurementInput key={f.key} label={f.label} icon={f.icon} unit={f.unit}
                  placeholder={f.placeholder} tip={f.tip}
                  value={(data.mensurations || {})[f.key] || ""}
                  onChange={v => updateNested("mensurations", f.key, v)} />
              ))}
            </div>
            <div style={{
              marginTop: 14, padding: "10px 14px", background: "rgba(184,149,106,0.04)",
              borderRadius: 10, border: "1px solid rgba(184,149,106,0.08)",
              display: "flex", alignItems: "flex-start", gap: 8,
            }}>
              <Icon name="metre" size={16} />
              <p style={{ fontFamily: "'DM Sans'", fontSize: 11, color: "#888", lineHeight: 1.5, margin: 0 }}>
                Pas sûr·e de vos mesures ? Utilisez l'option <strong>Autre</strong> ci-dessous pour envoyer un message vocal, ou remplissez seulement les mesures que vous connaissez.
              </p>
            </div>
          </div>
        )}

        {/* ── AUTRE TOGGLE ── */}
        <button onClick={() => { setAutreOpen(p => ({ ...p, [q.key]: !isAutre })); if (!isAutre && q.type === "cards") updateData(q.key, "autre"); }}
          style={{
            width: "100%", marginTop: 12, padding: "12px 16px", borderRadius: 12,
            border: isAutre ? "2px solid #B8956A" : "2px dashed #DDD",
            background: isAutre ? "rgba(184,149,106,0.04)" : "transparent",
            fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 500, cursor: "pointer",
            color: isAutre ? "#B8956A" : "#999", display: "flex", alignItems: "center", justifyContent: "center", gap: 7,
            transition: "all 0.2s",
          }}>
          <Icon name="chat" size={16} />
          Autre — préciser par texte ou audio
        </button>
        {isAutre && (
          <AutreInput value={autreText[q.key]} onChange={v => setAutreText(p => ({ ...p, [q.key]: v }))}
            onAudioChange={v => setAutreAudio(p => ({ ...p, [q.key]: v }))}
            placeholder={q.autrePlaceholder || "Décrivez votre besoin..."} />
        )}
      </div>

      {/* Navigation */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 24, paddingBottom: 24 }}>
        <button onClick={() => currentQ > 0 && setCurrentQ(currentQ - 1)} style={{
          background: "none", border: "none", fontFamily: "'DM Sans'", fontSize: 13,
          color: currentQ > 0 ? "#2D2926" : "transparent", cursor: currentQ > 0 ? "pointer" : "default",
          fontWeight: 500, display: "flex", alignItems: "center", gap: 5,
        }}>← Précédent</button>

        {(q.type === "measurements" || q.type === "multi" || currentQ === questions.length - 1 || isAutre) && (
          <button onClick={goNext} style={{
            background: hasAnswer() ? "linear-gradient(135deg, #1A1A1A, #333)" : "#E8E0D8",
            border: "none", color: hasAnswer() ? "#fff" : "#999",
            fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 600, padding: "11px 28px",
            borderRadius: 50, cursor: "pointer",
            boxShadow: hasAnswer() ? "0 4px 16px rgba(26,26,26,0.12)" : "none",
            transition: "all 0.3s",
          }}>
            {currentQ === questions.length - 1 ? "Voir les inspirations →" : "Suivant →"}
          </button>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// ─── STEP 2: TINDER SWIPE ────────────────────────────
// ═══════════════════════════════════════════════════════
function StepInspirations({ liked, setLiked, onNext }) {
  const fileInputRef = useRef(null);
  const [dragOver, setDragOver] = useState(false);

  const handleFiles = (files) => {
    const validFiles = Array.from(files).filter(f => f.type.startsWith("image/")).slice(0, 5 - liked.length);
    validFiles.forEach(file => {
      const reader = new FileReader();
      reader.onload = (e) => {
        setLiked(prev => {
          if (prev.length >= 5) return prev;
          return [...prev, { id: Date.now() + Math.random(), src: e.target.result, name: file.name }];
        });
      };
      reader.readAsDataURL(file);
    });
  };

  const removeImage = (id) => setLiked(prev => prev.filter(img => img.id !== id));

  // Inline SVG icons since the Icon component doesn't have these
  const CameraIcon = () => (
    <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
      <circle cx="12" cy="13" r="4"/>
    </svg>
  );
  const PinIcon = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#B8956A" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
      <circle cx="12" cy="10" r="3"/>
    </svg>
  );
  const ImageIcon = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#B8956A" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
      <circle cx="8.5" cy="8.5" r="1.5"/>
      <polyline points="21 15 16 10 5 21"/>
    </svg>
  );
  const PencilIcon = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#B8956A" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 19l7-7 3 3-7 7-3-3z"/>
      <path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/>
      <path d="M2 2l7.586 7.586"/>
      <circle cx="11" cy="11" r="2"/>
    </svg>
  );

  return (
    <div style={{ maxWidth: 520, margin: "0 auto", padding: "0 20px" }}>
      {/* Header */}
      <div style={{ textAlign: "center", marginBottom: 32 }}>
        <div style={{ fontFamily: "'Caveat'", fontSize: 18, color: "#B8956A", marginBottom: 4 }}>Étape 2</div>
        <h2 style={{ fontFamily: "'Playfair Display'", fontSize: 26, color: "#2D2926", marginBottom: 10 }}>Vos inspirations</h2>
        <p style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#999", lineHeight: 1.6 }}>
          Importez 3 à 5 photos qui vous inspirent pour personnaliser votre patron
        </p>
      </div>

      {/* Upload zone */}
      <div
        onClick={() => liked.length < 5 && fileInputRef.current?.click()}
        onDragOver={e => { e.preventDefault(); setDragOver(true); }}
        onDragLeave={() => setDragOver(false)}
        onDrop={e => { e.preventDefault(); setDragOver(false); handleFiles(e.dataTransfer.files); }}
        style={{
          border: `2px dashed ${dragOver ? "#B8956A" : liked.length > 0 ? "#D4D0CC" : "#D4D0CC"}`,
          borderRadius: 24, padding: liked.length > 0 ? "20px" : "44px 20px", textAlign: "center",
          cursor: liked.length < 5 ? "pointer" : "default",
          background: dragOver ? "rgba(184,149,106,0.04)" : "#fff",
          transition: "all 0.25s ease",
          marginBottom: 20,
          boxShadow: dragOver ? "0 0 0 4px rgba(184,149,106,0.08)" : "none",
        }}>
        <input ref={fileInputRef} type="file" accept="image/*" multiple
          onChange={e => handleFiles(e.target.files)}
          style={{ display: "none" }} />

        {/* Grid des images uploadées — à l'intérieur de la zone */}
        {liked.length > 0 && (
          <div style={{ display: "grid", gridTemplateColumns: liked.length <= 2 ? "repeat(2, 1fr)" : "repeat(3, 1fr)", gap: 10, marginBottom: 16 }}>
            {liked.map((img, i) => (
              <div key={img.id} style={{
                position: "relative", borderRadius: 14, overflow: "hidden",
                aspectRatio: "3/4", background: "#F8F4F0",
                boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
              }}>
                <img src={img.src} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                <button onClick={(e) => { e.stopPropagation(); removeImage(img.id); }} style={{
                  position: "absolute", top: 6, right: 6, width: 24, height: 24, borderRadius: "50%",
                  background: "rgba(0,0,0,0.55)", border: "none", color: "#fff", fontSize: 13,
                  cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
                  backdropFilter: "blur(4px)", transition: "background 0.2s",
                }}
                onMouseEnter={e => e.currentTarget.style.background = "rgba(26,26,26,0.85)"}
                onMouseLeave={e => e.currentTarget.style.background = "rgba(0,0,0,0.55)"}
                >×</button>
                <div style={{
                  position: "absolute", bottom: 0, left: 0, right: 0, padding: "16px 8px 5px",
                  background: "linear-gradient(transparent, rgba(0,0,0,0.45))",
                  fontFamily: "'DM Sans'", fontSize: 9, color: "rgba(255,255,255,0.85)", fontWeight: 500, letterSpacing: "0.03em",
                }}>{i + 1} / {liked.length}</div>
              </div>
            ))}

            {/* Bouton ajouter inline */}
            {liked.length < 5 && (
              <div style={{
                borderRadius: 14, border: "2px dashed #E0DBD5", aspectRatio: "3/4",
                display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
                cursor: "pointer", background: "#FDFBF9", gap: 6, transition: "all 0.2s",
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = "#B8956A"; e.currentTarget.style.background = "rgba(184,149,106,0.03)"; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = "#E0DBD5"; e.currentTarget.style.background = "#FDFBF9"; }}
              >
                <div style={{ width: 32, height: 32, borderRadius: "50%", background: "#F0EBE5", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#999" strokeWidth="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                </div>
                <span style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", fontWeight: 500 }}>Ajouter</span>
              </div>
            )}
          </div>
        )}

        {/* Upload prompt */}
        {liked.length === 0 && (
          <>
            <div style={{
              width: 64, height: 64, borderRadius: "50%",
              background: "linear-gradient(135deg, #1A1A1A, #333)",
              margin: "0 auto 16px", display: "flex", alignItems: "center", justifyContent: "center",
              boxShadow: "0 4px 16px rgba(26,26,26,0.12)",
            }}>
              <CameraIcon />
            </div>
            <div style={{ fontFamily: "'DM Sans'", fontSize: 15, fontWeight: 600, color: "#2D2926", marginBottom: 4 }}>
              Ajouter des photos
            </div>
            <div style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#BBB" }}>
              Cliquez ou glissez-déposez • JPG, PNG, WEBP
            </div>
          </>
        )}

        {/* Counter */}
        <div style={{
          fontFamily: "'DM Sans'", fontSize: 11, fontWeight: 600, marginTop: liked.length > 0 ? 4 : 14,
          color: liked.length >= 3 ? "#4CAF50" : liked.length > 0 ? "#B8956A" : "#CCC",
          display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
        }}>
          <span>{liked.length} / 5 photo{liked.length !== 1 ? "s" : ""}</span>
          {liked.length >= 3 && <span>✓</span>}
        </div>
      </div>

      {/* Conseils — seulement quand vide */}
      {liked.length === 0 && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10, marginBottom: 28 }}>
          {[
            { icon: <PinIcon />, title: "Pinterest", desc: "Captures de vos pins préférés" },
            { icon: <ImageIcon />, title: "Photos", desc: "Vêtements que vous aimez" },
            { icon: <PencilIcon />, title: "Croquis", desc: "Vos dessins ou schémas" },
          ].map(tip => (
            <div key={tip.title} onClick={() => fileInputRef.current?.click()} style={{
              background: "#fff", borderRadius: 16, padding: "18px 12px", textAlign: "center",
              border: "1px solid #EDE8E2", cursor: "pointer", transition: "all 0.2s",
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = "#B8956A"; e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 4px 12px rgba(0,0,0,0.06)"; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = "#EDE8E2"; e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = ""; }}
            >
              <div style={{ marginBottom: 8, display: "flex", justifyContent: "center" }}>{tip.icon}</div>
              <div style={{ fontFamily: "'DM Sans'", fontSize: 12, fontWeight: 600, color: "#2D2926", marginBottom: 3 }}>{tip.title}</div>
              <div style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#BBB", lineHeight: 1.4 }}>{tip.desc}</div>
            </div>
          ))}
        </div>
      )}

      {/* CTA */}
      <button onClick={onNext} disabled={liked.length < 1} style={{
        width: "100%",
        background: liked.length >= 3 ? "linear-gradient(135deg, #1A1A1A, #333)" : liked.length >= 1 ? "#2D2926" : "#E8E4E0",
        border: "none", color: liked.length >= 1 ? "#fff" : "#BBB",
        fontFamily: "'DM Sans'", fontSize: 15, fontWeight: 600, padding: "15px",
        borderRadius: 50, cursor: liked.length >= 1 ? "pointer" : "default",
        boxShadow: liked.length >= 3 ? "0 4px 20px rgba(26,26,26,0.15)" : liked.length >= 1 ? "0 2px 12px rgba(45,41,38,0.15)" : "none",
        transition: "all 0.3s ease",
        letterSpacing: "0.01em",
      }}>
        {liked.length === 0 ? "Ajoutez au moins 1 photo" : liked.length < 3 ? `Continuer avec ${liked.length} photo${liked.length > 1 ? "s" : ""} (3 recommandées)` : `Créer mon patron avec ${liked.length} inspirations →`}
      </button>

      {liked.length > 0 && liked.length < 3 && (
        <p style={{ fontFamily: "'DM Sans'", fontSize: 11, color: "#CCC", textAlign: "center", marginTop: 10 }}>
          Plus vous ajoutez de photos, plus votre patron sera personnalisé
        </p>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// ─── STEP 3: PATRON + CHAT ──────────────────────────
// ═══════════════════════════════════════════════════════
function StepPatronChat({ data, liked, patronResult, setPatronResult, onNext }) {
  const [messages, setMessages] = useState([
    { role: "assistant", text: "Je prépare votre patron personnalisé à partir de vos réponses... Un instant !" }
  ]);
  const [input, setInput] = useState("");
  const [isTyping, setIsTyping] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [previewMode, setPreviewMode] = useState("rendu"); // "rendu", "patron", "realiste"
  const [aiImage, setAiImage] = useState(null); // { url, prompt }
  const [aiImageLoading, setAiImageLoading] = useState(false);
  const [aiImageError, setAiImageError] = useState(null);
  const chatRef = useRef(null);

  // Charger l'image réaliste quand on clique sur l'onglet
  const loadRealisticView = async () => {
    setPreviewMode("realiste");
    if (aiImage) return; // déjà chargée
    setAiImageLoading(true);
    setAiImageError(null);
    try {
      const res = await fetch(`${API_URL}/api/patron/visualize`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ formData: data, patron: patronResult?.patron }),
      });
      const result = await res.json();
      if (result.success && result.image_url) {
        setAiImage({ url: result.image_url, prompt: result.prompt });
      } else {
        setAiImageError(result.error || "Impossible de générer l'image");
      }
    } catch (err) {
      setAiImageError("Erreur de connexion au service de visualisation");
    }
    setAiImageLoading(false);
  };

  // Labels lisibles pour les tags récap
  const labelMap = {
    // Types
    robe: "Robe", jupe: "Jupe", haut: "Haut", pantalon: "Pantalon",
    // Styles
    couture: "Couture", boheme: "Bohème", minimaliste: "Minimaliste", streetwear: "Streetwear", vintage: "Vintage", romantique: "Romantique",
    // Morphologies
    sablier: "Sablier", triangle: "Triangle", triangle_inverse: "Triangle inversé", rectangle: "Rectangle", ronde: "Ronde",
    // Niveaux
    debutant: "Débutante", intermediaire: "Intermédiaire", avance: "Avancée", expert: "Experte",
    // Tissus
    coton: "Coton", lin: "Lin", soie: "Soie", jersey: "Jersey", viscose: "Viscose", laine: "Laine", denim: "Denim",
    // Occasions
    quotidien: "Quotidien", bureau: "Bureau", soiree: "Soirée", ceremonie: "Cérémonie", weekend: "Weekend",
    // Budgets
    economique: "Économique", moyen: "Moyen", premium: "Premium", pas_defini: "Flexible",
  };
  const label = (v) => labelMap[v] || (v ? v.charAt(0).toUpperCase() + v.slice(1).replace(/_/g, " ") : "");

  const features = [
    { label: "Type", value: label(data.type), icon: "robe" },
    { label: "Style", value: label(data.style), icon: "boheme" },
    { label: "Taille", value: data.taille_standard, icon: "metre" },
    { label: "Morpho", value: label(data.morphologie), icon: "sablier" },
    { label: "Niveau", value: label(data.niveau), icon: "niveau_debutant" },
    { label: "Tissu", value: label(data.tissu_type), icon: "coton" },
    { label: "Occasion", value: label(data.occasion), icon: "calendrier" },
    { label: "Budget", value: label(data.budget), icon: "budget" },
  ].filter(f => f.value && f.value !== "Autre" && f.value !== "Flexible");

  // ── Appel API au montage — génère le patron ──
  useEffect(() => {
    if (patronResult) {
      setIsLoading(false);
      setMessages([{
        role: "assistant",
        text: patronResult.ia
          ? `Votre patron est prêt ! ${patronResult.patron.nom} — ${patronResult.patron.pieces.length} pièces, métrage estimé : ${patronResult.patron.metrage_estime.metres}m. ${patronResult.ia.temps_estime ? `Temps estimé : ${patronResult.ia.temps_estime}.` : ""} Que souhaitez-vous ajuster ?`
          : `Votre ${patronResult.patron.nom} est prêt ! ${patronResult.patron.pieces.length} pièces, métrage estimé : ${patronResult.patron.metrage_estime.metres}m. Que souhaitez-vous ajuster ?`
      }]);
      return;
    }

    const fetchPatron = async () => {
      try {
        setIsTyping(true);

        // ── Étape 1 : Patron géométrique RAPIDE (< 1s) ──
        const res = await fetch(`${API_URL}/api/patron`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(data),
        });
        if (!res.ok) throw new Error(`Erreur serveur (${res.status})`);
        const result = await res.json();
        setPatronResult(result);
        setIsLoading(false);

        const piecesNames = result.patron.pieces.map(p => p.nom).join(", ");
        const baseMsg = `Votre ${result.patron.nom} est prêt !\n\n📐 ${result.patron.pieces.length} pièces : ${piecesNames}\n🧵 Métrage estimé : ${result.patron.metrage_estime.metres}m (laize ${result.patron.metrage_estime.laize_recommandee}cm)\n\nJ'analyse votre projet avec l'IA pour des conseils personnalisés...`;
        setMessages([{ role: "assistant", text: baseMsg }]);

        // ── Étape 2 : Enrichissement IA en arrière-plan (10-25s) ──
        try {
          const iaRes = await fetch(`${API_URL}/api/patron/ia`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(data),
          });
          const iaResult = await iaRes.json();

          if (iaResult.success && iaResult.ia) {
            setPatronResult(iaResult);
            setIsTyping(false);
            const iaPiecesNames = iaResult.patron.pieces.map(p => p.nom).join(", ");
            const iaMsg = `✨ Analyse IA terminée !\n\n📐 ${iaResult.patron.nom} — ${iaResult.patron.pieces.length} pièces : ${iaPiecesNames}\n🧵 Métrage : ${iaResult.patron.metrage_estime.metres}m\n⏱ Difficulté : ${iaResult.ia.difficulte || "moyen"}${iaResult.ia.temps_estime ? ` • Temps estimé : ${iaResult.ia.temps_estime}` : ""}\n\nQue souhaitez-vous ajuster ?`;
            setMessages([{ role: "assistant", text: iaMsg }]);
          } else {
            setIsTyping(false);
            setMessages(prev => [...prev, { role: "assistant", text: "Le patron de base est prêt. Que souhaitez-vous ajuster ?" }]);
          }
        } catch (iaErr) {
          setIsTyping(false);
          setMessages(prev => [...prev, { role: "assistant", text: "Le patron de base est prêt. Que souhaitez-vous ajuster ?" }]);
        }

      } catch (err) {
        setIsTyping(false);
        setIsLoading(false);
        setError(err.message);
        setMessages([{
          role: "assistant",
          text: `Hmm, je n'arrive pas à contacter le serveur (${err.message}). Vérifiez que le backend tourne sur ${API_URL}. En attendant, vous pouvez continuer avec un patron simulé.`
        }]);
        setPatronResult({
          patron: { type: data.type || "jupe", nom: data.type || "Patron", pieces: [], metrage_estime: { metres: 1.5, laize_recommandee: 140 }, options: { marges_incluses: true, marge_couture: "1.5 cm" }, mensurations_utilisees: {} },
          ia: null, mensurations: {},
        });
      }
    };
    fetchPatron();
  }, []);

  // ── Chat interactif ──
  const sendMessage = async () => {
    if (!input.trim()) return;
    const userMsg = input.trim();
    setMessages(p => [...p, { role: "user", text: userMsg }]);
    setInput("");
    setIsTyping(true);

    // Si l'IA est dispo, on pourrait rappeler Claude pour ajuster
    // Pour l'instant, réponses contextuelles basées sur le patron généré
    setTimeout(() => {
      const pr = patronResult;
      const responses = [
        pr?.ia?.conseils_tissu ? `Bon à savoir pour votre tissu : ${pr.ia.conseils_tissu}` : null,
        pr?.patron?.metrage_estime ? `Pour rappel, il vous faudra environ ${pr.patron.metrage_estime.metres}m de tissu en laize ${pr.patron.metrage_estime.laize_recommandee}cm. ${pr.patron.metrage_estime.note}` : null,
        `J'ai bien noté votre demande. Le patron sera ajusté en conséquence lors de la génération finale du PDF.`,
        pr?.ia?.fournitures?.mercerie ? `N'oubliez pas votre mercerie : ${pr.ia.fournitures.mercerie.slice(0, 3).join(", ")}.` : null,
        `Bonne remarque ! Les marges de couture sont ${pr?.patron?.options?.marges_incluses ? "déjà incluses" : "à ajouter"} sur ce patron. Voulez-vous autre chose ?`,
        `Modification notée ! Les pinces et ajustements de votre patron tiennent compte de votre morphologie ${data.morphologie || ""}.`,
      ].filter(Boolean);

      const r = responses[Math.floor(Math.random() * responses.length)];
      setMessages(p => [...p, { role: "assistant", text: r }]);
      setIsTyping(false);
    }, 1200);
  };

  useEffect(() => { if (chatRef.current) chatRef.current.scrollTop = chatRef.current.scrollHeight; }, [messages, isTyping]);

  return (
    <div style={{ maxWidth: 920, margin: "0 auto", padding: "0 20px", display: "flex", gap: 20, alignItems: "flex-start", flexWrap: "wrap" }}>
      {/* Patron */}
      <div style={{ flex: "1 1 340px", minWidth: 290 }}>
        <div style={{ background: "#FDFBF9", borderRadius: 24, border: "2px solid #EDE8E2", overflow: "hidden" }}>
          <div style={{ height: previewMode === "realiste" ? 420 : 380, background: previewMode === "realiste" ? "linear-gradient(135deg, #1a1a2e, #16213e)" : "linear-gradient(135deg, #FFF8F0, #F8ECE4)", display: "flex", alignItems: "center", justifyContent: "center", position: "relative", padding: 10, transition: "all 0.4s ease" }}>
            {/* Toggle buttons */}
            <div style={{ position: "absolute", top: 10, right: 10, display: "flex", background: "#fff", borderRadius: 12, overflow: "hidden", border: "1px solid #EDE8E2", zIndex: 2, boxShadow: "0 2px 8px rgba(0,0,0,0.06)" }}>
              {[{id: "rendu", label: "Croquis"}, {id: "patron", label: "Patron"}, {id: "realiste", label: "✨ IA"}].map(v => (
                <button key={v.id} onClick={() => v.id === "realiste" ? loadRealisticView() : setPreviewMode(v.id)} style={{
                  padding: "6px 13px", border: "none", fontFamily: "'DM Sans'", fontSize: 10, fontWeight: 600, cursor: "pointer",
                  background: previewMode === v.id
                    ? v.id === "realiste" ? "linear-gradient(135deg, #1A1A1A, #B8956A)" : "#B8956A"
                    : "transparent",
                  color: previewMode === v.id ? "#fff" : "#999",
                  transition: "all 0.2s",
                  letterSpacing: v.id === "realiste" ? "0.02em" : 0,
                }}>{v.label}</button>
              ))}
            </div>
            <div style={{ position: "absolute", top: 14, left: 14, fontFamily: "'Caveat'", fontSize: 13, color: previewMode === "realiste" ? "#B8956A" : "#B8956A", fontWeight: 600 }}>
              {previewMode === "rendu" ? "Aperçu du vêtement" : previewMode === "patron" ? "Patron personnalisé" : "Rendu réaliste IA"}
            </div>

            {/* ── VUE RENDU : croquis du vêtement fini ── */}
            {previewMode === "rendu" && (() => {
              const type = patronResult?.patron?.type || data.type || "haut";
              const ia = patronResult?.ia;
              const longueur = ia?.patron?.options?.longueur || "standard";
              return React.createElement("svg", { viewBox: "0 0 200 340", width: "160", height: "280", style: { marginTop: 20 } }, [
                // Mannequin
                React.createElement("ellipse", { key: "head", cx: 100, cy: 28, rx: 12, ry: 14, fill: "none", stroke: "#C4B8A8", strokeWidth: 1.5 }),
                React.createElement("line", { key: "neck", x1: 100, y1: 42, x2: 100, y2: 52, stroke: "#C4B8A8", strokeWidth: 1.5 }),

                // Corps
                ...(type === "jupe" || type === "bas" ? [
                  // Buste nu
                  React.createElement("line", { key: "shoulder-l", x1: 72, y1: 56, x2: 100, y2: 52, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "shoulder-r", x1: 128, y1: 56, x2: 100, y2: 52, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("path", { key: "body", d: "M72 56 L74 110 L126 110 L128 56", fill: "none", stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "arm-l", x1: 72, y1: 56, x2: 58, y2: 130, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "arm-r", x1: 128, y1: 56, x2: 142, y2: 130, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  // Jupe
                  React.createElement("path", { key: "skirt", d: longueur === "mini" ? "M74 110 Q72 115 66 170 Q100 175 134 170 Q128 115 126 110 Z" : longueur === "maxi" ? "M74 110 Q68 140 58 290 Q100 300 142 290 Q132 140 126 110 Z" : "M74 110 Q70 130 62 230 Q100 238 138 230 Q130 130 126 110 Z", fill: "rgba(184,149,106,0.08)", stroke: "#B8956A", strokeWidth: 2, strokeLinejoin: "round" }),
                  React.createElement("path", { key: "waistband", d: "M74 110 Q100 107 126 110 Q100 113 74 110", fill: "none", stroke: "#B8956A", strokeWidth: 1.5 }),
                  // Jambes
                  React.createElement("line", { key: "leg-l", x1: 88, y1: longueur === "maxi" ? 290 : longueur === "mini" ? 170 : 230, x2: 85, y2: 310, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "leg-r", x1: 112, y1: longueur === "maxi" ? 290 : longueur === "mini" ? 170 : 230, x2: 115, y2: 310, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                ] : type === "pantalon" ? [
                  // Buste nu
                  React.createElement("line", { key: "shoulder-l", x1: 72, y1: 56, x2: 100, y2: 52, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "shoulder-r", x1: 128, y1: 56, x2: 100, y2: 52, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("path", { key: "body", d: "M72 56 L74 110 L126 110 L128 56", fill: "none", stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "arm-l", x1: 72, y1: 56, x2: 58, y2: 130, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "arm-r", x1: 128, y1: 56, x2: 142, y2: 130, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  // Pantalon
                  React.createElement("path", { key: "pant-l", d: "M74 110 L72 115 L68 280 L92 280 L100 115", fill: "rgba(184,149,106,0.08)", stroke: "#B8956A", strokeWidth: 2, strokeLinejoin: "round" }),
                  React.createElement("path", { key: "pant-r", d: "M100 115 L108 280 L132 280 L128 115 L126 110", fill: "rgba(184,149,106,0.08)", stroke: "#B8956A", strokeWidth: 2, strokeLinejoin: "round" }),
                  React.createElement("path", { key: "waistband-p", d: "M74 110 Q100 107 126 110", fill: "none", stroke: "#B8956A", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "pant-center", x1: 100, y1: 115, x2: 100, y2: 180, stroke: "#B8956A", strokeWidth: 1, strokeDasharray: "4,3" }),
                ] : type === "robe" ? [
                  // Robe avec manches
                  React.createElement("line", { key: "shoulder-l", x1: 72, y1: 56, x2: 100, y2: 52, stroke: "#B8956A", strokeWidth: 1.8 }),
                  React.createElement("line", { key: "shoulder-r", x1: 128, y1: 56, x2: 100, y2: 52, stroke: "#B8956A", strokeWidth: 1.8 }),
                  // Manches
                  React.createElement("path", { key: "sleeve-l", d: "M72 56 L52 60 L48 120 L66 118 L70 85", fill: "rgba(184,149,106,0.06)", stroke: "#B8956A", strokeWidth: 1.8, strokeLinejoin: "round" }),
                  React.createElement("path", { key: "sleeve-r", d: "M128 56 L148 60 L152 120 L134 118 L130 85", fill: "rgba(184,149,106,0.06)", stroke: "#B8956A", strokeWidth: 1.8, strokeLinejoin: "round" }),
                  // Corsage
                  React.createElement("path", { key: "bodice", d: "M72 56 L70 85 Q100 80 130 85 L128 56", fill: "rgba(184,149,106,0.06)", stroke: "#B8956A", strokeWidth: 2 }),
                  // Pinces taille
                  React.createElement("path", { key: "dart-l", d: "M85 78 L88 95 L91 78", fill: "none", stroke: "#B8956A", strokeWidth: 1, strokeDasharray: "3,3" }),
                  React.createElement("path", { key: "dart-r", d: "M109 78 L112 95 L115 78", fill: "none", stroke: "#B8956A", strokeWidth: 1, strokeDasharray: "3,3" }),
                  // Jupe
                  React.createElement("path", { key: "skirt-r", d: longueur === "mini" ? "M70 85 Q66 110 60 170 Q100 178 140 170 Q134 110 130 85" : longueur === "maxi" ? "M70 85 Q62 130 52 290 Q100 300 148 290 Q138 130 130 85" : "M70 85 Q64 120 56 230 Q100 240 144 230 Q136 120 130 85", fill: "rgba(184,149,106,0.08)", stroke: "#B8956A", strokeWidth: 2, strokeLinejoin: "round" }),
                  React.createElement("path", { key: "waist-r", d: "M70 85 Q100 80 130 85", fill: "none", stroke: "#B8956A", strokeWidth: 1.5, strokeDasharray: "4,3" }),
                  // Bras (visible sous les manches)
                  React.createElement("line", { key: "forearm-l", x1: 48, y1: 120, x2: 44, y2: 170, stroke: "#C4B8A8", strokeWidth: 1.2 }),
                  React.createElement("line", { key: "forearm-r", x1: 152, y1: 120, x2: 156, y2: 170, stroke: "#C4B8A8", strokeWidth: 1.2 }),
                  // Jambes
                  React.createElement("line", { key: "leg-l-r", x1: 88, y1: longueur === "maxi" ? 290 : longueur === "mini" ? 170 : 230, x2: 85, y2: 310, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "leg-r-r", x1: 112, y1: longueur === "maxi" ? 290 : longueur === "mini" ? 170 : 230, x2: 115, y2: 310, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  // Encolure
                  React.createElement("path", { key: "neckline", d: "M80 54 Q100 62 120 54", fill: "none", stroke: "#B8956A", strokeWidth: 1.5 }),
                ] : [
                  // Haut / corsage (défaut)
                  React.createElement("path", { key: "top-l", d: "M72 56 L70 130 Q100 135 130 130 L128 56", fill: "rgba(184,149,106,0.08)", stroke: "#B8956A", strokeWidth: 2, strokeLinejoin: "round" }),
                  React.createElement("line", { key: "shoulder-l-t", x1: 72, y1: 56, x2: 100, y2: 52, stroke: "#B8956A", strokeWidth: 1.8 }),
                  React.createElement("line", { key: "shoulder-r-t", x1: 128, y1: 56, x2: 100, y2: 52, stroke: "#B8956A", strokeWidth: 1.8 }),
                  React.createElement("path", { key: "neckline-t", d: "M80 54 Q100 62 120 54", fill: "none", stroke: "#B8956A", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "sleeve-l", x1: 72, y1: 56, x2: 52, y2: 110, stroke: "#B8956A", strokeWidth: 2 }),
                  React.createElement("line", { key: "sleeve-r", x1: 128, y1: 56, x2: 148, y2: 110, stroke: "#B8956A", strokeWidth: 2 }),
                  React.createElement("line", { key: "sleeve-l2", x1: 52, y1: 110, x2: 70, y2: 108, stroke: "#B8956A", strokeWidth: 2 }),
                  React.createElement("line", { key: "sleeve-r2", x1: 148, y1: 110, x2: 130, y2: 108, stroke: "#B8956A", strokeWidth: 2 }),
                  // Pinces taille
                  React.createElement("path", { key: "dart-l-t", d: "M85 85 L88 115 L91 85", fill: "none", stroke: "#B8956A", strokeWidth: 1, strokeDasharray: "3,3" }),
                  React.createElement("path", { key: "dart-r-t", d: "M109 85 L112 115 L115 85", fill: "none", stroke: "#B8956A", strokeWidth: 1, strokeDasharray: "3,3" }),
                  // Jambes
                  React.createElement("line", { key: "leg-l-t", x1: 88, y1: 200, x2: 85, y2: 310, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("line", { key: "leg-r-t", x1: 112, y1: 200, x2: 115, y2: 310, stroke: "#C4B8A8", strokeWidth: 1.5 }),
                  React.createElement("path", { key: "bottom-t", d: "M74 135 L72 200 Q100 208 128 200 L126 135", fill: "none", stroke: "#C4B8A8", strokeWidth: 1.5 }),
                ]),
                // Label type
                React.createElement("text", { key: "type-label", x: 100, y: 330, textAnchor: "middle", fontSize: 10, fill: "#AAA", fontFamily: "DM Sans", fontWeight: 500 },
                  (patronResult?.patron?.nom || data.type || "Vêtement"))
              ]);
            })()}

            {/* ── VUE PATRON : pièces techniques ── */}
            {previewMode === "patron" && (
              patronResult?.patron?.pieces?.length > 0 ? (() => {
                const pieces = patronResult.patron.pieces.filter(p => !p.isParementure);
                const allPts = pieces.flatMap(p => p.contour);
                const allGradePts = pieces.flatMap(p => (p.gradation || []).flatMap(g => g.contour));
                const allMargePts = pieces.flatMap(p => (p.marges_couture || []));
                const combinedPts = [...allPts, ...allGradePts, ...allMargePts];
                const minX = Math.min(...combinedPts.map(p => p.x));
                const maxX = Math.max(...combinedPts.map(p => p.x));
                const minY = Math.min(...combinedPts.map(p => p.y));
                const maxY = Math.max(...combinedPts.map(p => p.y));
                const pw = maxX - minX || 1;
                const ph = maxY - minY || 1;
                const pad = 25;
                const colors = ["#B8956A", "#2D6B4F", "#2D6B8A"];
                const gradeColors = ["#6BA3D9", "#2D2926", "#D96A6A", "#4AAD6A", "#D9B86A"];

                // Helper: build SVG path with Bézier support
                const buildPath = (pts) => {
                  return pts.map((p, i) => {
                    if (i === 0) return `M${p.x},${p.y}`;
                    if (p.cp1x !== undefined) return `C${p.cp1x},${p.cp1y} ${p.cp2x},${p.cp2y} ${p.x},${p.y}`;
                    return `L${p.x},${p.y}`;
                  }).join(" ") + " Z";
                };

                return React.createElement("svg", {
                  viewBox: `${minX - pad} ${minY - pad} ${pw + pad * 2} ${ph + pad * 2}`,
                  width: "100%", height: "100%",
                  style: { maxHeight: 340 }
                }, pieces.map((piece, pi) => {
                  const pts = piece.contour;
                  const d = buildPath(pts);
                  const col = colors[pi % colors.length];
                  const cx = pts.reduce((s, p) => s + p.x, 0) / pts.length;
                  const cy = pts.reduce((s, p) => s + p.y, 0) / pts.length;
                  const sw = Math.max(1, pw / 200);
                  const elements = [
                    React.createElement("path", { key: "fill", d, style: { fill: `${col}11` } }),
                    React.createElement("path", { key: "stroke", d, fill: "none", stroke: col, strokeWidth: sw, strokeLinejoin: "round" }),
                  ];

                  // Gradation lines
                  if (piece.gradation) {
                    piece.gradation.forEach((g, gi) => {
                      if (g.isBase) return;
                      const gd = buildPath(g.contour);
                      const gc = gradeColors[gi % gradeColors.length];
                      elements.push(React.createElement("path", {
                        key: `grade-${gi}`, d: gd, fill: "none", stroke: gc,
                        strokeWidth: Math.max(0.4, pw / 400),
                        strokeDasharray: `${pw / 60},${pw / 100}`, opacity: 0.5,
                      }));
                    });
                  }

                  // Seam allowance dashed
                  if (piece.marges_couture && piece.marges_couture.length > 1) {
                    const md = piece.marges_couture.map((p, i) => `${i === 0 ? "M" : "L"}${p.x},${p.y}`).join(" ") + " Z";
                    elements.push(React.createElement("path", {
                      key: "seam", d: md, fill: "none", stroke: "#C4B8A8",
                      strokeWidth: Math.max(0.4, pw / 350),
                      strokeDasharray: `${pw / 80},${pw / 120}`, opacity: 0.6,
                    }));
                  }

                  // Pinces
                  piece.pinces.forEach((pince, di) => {
                    const px = pince.position.x;
                    const py = pince.position.y;
                    const hv = pince.valeur / 2;
                    const len = pince.longueur;
                    const pd = pince.direction === "bas"
                      ? `M${px - hv},${py} L${px},${py + len} L${px + hv},${py}`
                      : `M${px - hv},${py} L${px},${py - len} L${px + hv},${py}`;
                    elements.push(React.createElement("path", { key: `dart-${di}`, d: pd, fill: "none", stroke: "#B8956A", strokeWidth: Math.max(0.8, pw / 300), strokeDasharray: `${pw / 80},${pw / 120}` }));
                  });

                  // Crans
                  piece.crans.forEach((cran, ci) => {
                    const sz = pw / 40;
                    elements.push(React.createElement("g", { key: `notch-${ci}` }, [
                      React.createElement("line", { key: "h", x1: cran.x - sz, y1: cran.y, x2: cran.x + sz, y2: cran.y, stroke: "#B8956A", strokeWidth: Math.max(0.6, pw / 400) }),
                      React.createElement("line", { key: "v", x1: cran.x, y1: cran.y - sz, x2: cran.x, y2: cran.y + sz, stroke: "#B8956A", strokeWidth: Math.max(0.6, pw / 400) })
                    ]));
                  });

                  // Droit-fil
                  piece.reperes.filter(r => r.type === "droit_fil").forEach((r, ri) => {
                    elements.push(React.createElement("line", {
                      key: `df-${ri}`, x1: r.x, y1: r.y,
                      x2: r.direction === "vertical" ? r.x : r.x + r.longueur,
                      y2: r.direction === "vertical" ? r.y + r.longueur : r.y,
                      stroke: "#999", strokeWidth: Math.max(0.5, pw / 400), strokeDasharray: `${pw / 50},${pw / 80}`
                    }));
                  });

                  // Label
                  elements.push(React.createElement("text", { key: "label", x: cx, y: cy, textAnchor: "middle", dominantBaseline: "middle", fontSize: Math.max(8, pw / 22), fill: col, fontFamily: "DM Sans", fontWeight: 600, opacity: 0.5 }, piece.nom));

                  return React.createElement("g", { key: pi }, elements);
                }));
              })() : (
                <svg viewBox="0 0 200 300" width="150" height="230" style={{ opacity: 0.9 }}>
                  <path d="M60 40 L80 30 L100 25 L120 30 L140 40 L145 80 L155 150 L165 250 L140 280 L100 285 L60 280 L35 250 L45 150 L55 80 Z" fill="none" stroke="#B8956A" strokeWidth="1.5" strokeDasharray="6,3" />
                  <path d="M70 40 L85 35 L100 32 L115 35 L130 40 L133 75 L140 140 L148 240 L130 260 L100 265 L70 260 L52 240 L60 140 L67 75 Z" fill="rgba(184,149,106,0.06)" stroke="#2D2926" strokeWidth="2" />
                  <line x1="100" y1="60" x2="100" y2="240" stroke="#999" strokeWidth="0.8" strokeDasharray="8,4" />
                  <text x="100" y="250" textAnchor="middle" fontSize="8" fill="#999" fontFamily="DM Sans">Chargement...</text>
                </svg>
              )
            )}

            {/* ── VUE RÉALISTE : image IA photoréaliste ── */}
            {previewMode === "realiste" && (
              <div style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", position: "relative" }}>
                {aiImageLoading && (
                  <div style={{ textAlign: "center", animation: "fadeSlideIn 0.4s ease" }}>
                    {/* Shimmer loading */}
                    <div style={{
                      width: 200, height: 260, borderRadius: 16, overflow: "hidden", margin: "0 auto 16px",
                      background: "linear-gradient(110deg, #F0EBE5 8%, #F8F4F0 18%, #F0EBE5 33%)",
                      backgroundSize: "200% 100%",
                      animation: "shimmer 1.5s infinite linear",
                    }} />
                    <style>{`@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }`}</style>
                    <div style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#999", display: "flex", alignItems: "center", gap: 8, justifyContent: "center" }}>
                      <div style={{ display: "flex", gap: 4 }}>
                        {[0, 0.2, 0.4].map(d => <span key={d} style={{ width: 6, height: 6, borderRadius: "50%", background: "linear-gradient(135deg, #1A1A1A, #B8956A)", display: "inline-block", animation: `pulse 1.2s ease-in-out ${d}s infinite` }} />)}
                      </div>
                      Génération IA en cours...
                    </div>
                    <div style={{ fontFamily: "'Caveat'", fontSize: 11, color: "#CCC", marginTop: 8 }}>
                      Votre vêtement prend vie
                    </div>
                  </div>
                )}
                {aiImage && !aiImageLoading && (
                  <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", animation: "fadeSlideIn 0.6s ease" }}>
                    <img src={aiImage.url} alt="Rendu réaliste IA" style={{
                      maxWidth: "92%", maxHeight: 360, borderRadius: 14,
                      objectFit: "contain",
                      boxShadow: "0 8px 32px rgba(0,0,0,0.12)",
                    }} />
                    {/* Badge IA */}
                    <div style={{
                      position: "absolute", bottom: 12, left: 14,
                      background: "linear-gradient(135deg, #1A1A1A, #B8956A)",
                      backdropFilter: "blur(8px)",
                      color: "#fff", fontFamily: "'DM Sans'", fontSize: 9, fontWeight: 600,
                      padding: "4px 10px", borderRadius: 20, letterSpacing: "0.04em",
                    }}>✨ Généré par IA</div>
                    {/* Regenerate */}
                    <button onClick={() => { setAiImage(null); loadRealisticView(); }} style={{
                      position: "absolute", bottom: 12, right: 14,
                      background: "rgba(255,255,255,0.9)", backdropFilter: "blur(8px)",
                      border: "1px solid #EDE8E2", borderRadius: 20,
                      padding: "4px 10px", fontFamily: "'DM Sans'", fontSize: 9, fontWeight: 600,
                      color: "#666", cursor: "pointer",
                    }}>↻ Regénérer</button>
                  </div>
                )}
                {aiImageError && !aiImageLoading && (
                  <div style={{ textAlign: "center", padding: 20, animation: "fadeSlideIn 0.4s ease" }}>
                    <div style={{ width: 56, height: 56, borderRadius: "50%", background: "#F8F4F0", margin: "0 auto 12px", display: "flex", alignItems: "center", justifyContent: "center" }}>
                      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#AAA" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
                    </div>
                    <div style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#999", marginBottom: 8 }}>{aiImageError}</div>
                    <button onClick={() => { setAiImageError(null); loadRealisticView(); }} style={{
                      background: "linear-gradient(135deg, #1A1A1A, #B8956A)", border: "none", color: "#fff",
                      padding: "8px 20px", borderRadius: 20, fontFamily: "'DM Sans'", fontSize: 11, fontWeight: 600,
                      cursor: "pointer",
                    }}>Réessayer</button>
                  </div>
                )}
              </div>
            )}

            {patronResult?.patron && previewMode !== "realiste" && (
              <div style={{ position: "absolute", bottom: 10, right: 14, fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA" }}>
                {patronResult.patron.pieces.length} pièces • {patronResult.patron.metrage_estime.metres}m
              </div>
            )}
          </div>
          <div style={{ padding: 16 }}>
            <h3 style={{ fontFamily: "'Playfair Display'", fontSize: 17, color: "#2D2926", marginBottom: 12 }}>Récapitulatif</h3>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {features.map(f => (
                <div key={f.label} style={{ background: "#F8F4F0", borderRadius: 8, padding: "6px 10px", display: "flex", alignItems: "center", gap: 6 }}>
                  <Icon name={f.icon} size={16} />
                  <span style={{ fontFamily: "'DM Sans'", fontSize: 11, color: "#2D2926", fontWeight: 500, textTransform: "capitalize" }}>{f.value}</span>
                </div>
              ))}
            </div>
            {data.mensurations && Object.values(data.mensurations).some(Boolean) && (
              <div style={{ marginTop: 10, padding: "8px 10px", background: "#F8F4F0", borderRadius: 8 }}>
                <div style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", marginBottom: 4 }}>Mensurations</div>
                <div style={{ fontFamily: "'DM Sans'", fontSize: 11, color: "#2D2926", display: "flex", flexWrap: "wrap", gap: "2px 12px" }}>
                  {Object.entries(data.mensurations).filter(([,v]) => v).map(([k,v]) => (
                    <span key={k}>{k.replace(/_/g, ' ')}: <strong>{v}cm</strong></span>
                  ))}
                </div>
              </div>
            )}
            {(data.personnalisation || []).length > 0 && (
              <div style={{ marginTop: 10, display: "flex", flexWrap: "wrap", gap: 4 }}>
                {data.personnalisation.map(p => (
                  <span key={p} style={{ background: "rgba(184,149,106,0.08)", color: "#B8956A", padding: "3px 10px", borderRadius: 20, fontFamily: "'DM Sans'", fontSize: 10, fontWeight: 500 }}>{p}</span>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Chat */}
      <div style={{ flex: "1 1 340px", minWidth: 290 }}>
        <div style={{ background: "#fff", borderRadius: 24, border: "2px solid #EDE8E2", display: "flex", flexDirection: "column", height: 480, overflow: "hidden" }}>
          <div style={{ padding: "12px 16px", borderBottom: "1px solid #F0EBE5", display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ width: 34, height: 34, borderRadius: "50%", background: "#1A1A1A", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <span style={{ fontFamily: "'Playfair Display'", fontSize: 15, fontWeight: 700, color: "#fff", fontStyle: "italic" }}>P</span>
            </div>
            <div>
              <div style={{ fontFamily: "'Playfair Display'", fontWeight: 600, fontSize: 13, color: "#1A1A1A", letterSpacing: "0.04em" }}>PATRONIA</div>
              <div style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#4CAF50" }}>● En ligne</div>
            </div>
          </div>
          <div ref={chatRef} style={{ flex: 1, overflow: "auto", padding: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            {messages.map((msg, i) => (
              <div key={i} style={{ alignSelf: msg.role === "user" ? "flex-end" : "flex-start", maxWidth: "85%" }}>
                <div style={{
                  background: msg.role === "user" ? "linear-gradient(135deg, #2D2926, #4A3F3A)" : "#F8F4F0",
                  color: msg.role === "user" ? "#fff" : "#2D2926",
                  padding: "10px 14px", borderRadius: 16,
                  borderBottomRightRadius: msg.role === "user" ? 4 : 16,
                  borderBottomLeftRadius: msg.role === "user" ? 16 : 4,
                  fontFamily: "'DM Sans'", fontSize: 13, lineHeight: 1.5,
                }}>{msg.text}</div>
              </div>
            ))}
            {isTyping && (
              <div style={{ alignSelf: "flex-start" }}>
                <div style={{ background: "#F8F4F0", padding: "10px 18px", borderRadius: 16, borderBottomLeftRadius: 4, display: "flex", gap: 5 }}>
                  {[0, 0.15, 0.3].map(d => <span key={d} style={{ animation: "bounce 1s infinite", animationDelay: `${d}s`, width: 7, height: 7, borderRadius: "50%", background: "#CCC", display: "inline-block" }} />)}
                </div>
              </div>
            )}
          </div>
          <div style={{ padding: "10px 12px", borderTop: "1px solid #F0EBE5", display: "flex", gap: 8 }}>
            <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === "Enter" && sendMessage()}
              placeholder="Décrivez vos modifications..."
              style={{ flex: 1, border: "2px solid #EDE8E2", borderRadius: 12, padding: "10px 12px", fontFamily: "'DM Sans'", fontSize: 13, outline: "none", background: "#FDFBF9" }}
              onFocus={e => e.target.style.borderColor = "#B8956A"} onBlur={e => e.target.style.borderColor = "#EDE8E2"} />
            <button onClick={sendMessage} style={{ width: 40, height: 40, borderRadius: 12, border: "none", background: "linear-gradient(135deg, #1A1A1A, #333)", color: "#fff", fontSize: 16, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>→</button>
          </div>
        </div>
        <button onClick={onNext} style={{
          width: "100%", marginTop: 12, background: "linear-gradient(135deg, #1A1A1A, #333)",
          border: "none", color: "#fff", fontFamily: "'DM Sans'", fontSize: 14, fontWeight: 600,
          padding: "12px", borderRadius: 14, cursor: "pointer", boxShadow: "0 4px 16px rgba(26,26,26,0.12)",
        }}>Valider mon patron ✓</button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// ─── STEP 4: CHOOSE PATH + PAYMENT ──────────────────
// ═══════════════════════════════════════════════════════
function StepFinalize({ data, patronResult }) {
  const [path, setPath] = useState(null); // null = choosing, "diy" or "produce"
  const [selectedPlan, setSelectedPlan] = useState("standard");
  const [selectedFabric, setSelectedFabric] = useState(null);
  const [selectedSize, setSelectedSize] = useState(data.taille_standard || "M");
  const [showSuccess, setShowSuccess] = useState(false);
  const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
  const [pdfUrl, setPdfUrl] = useState(null);
  const [deliveryInfo, setDeliveryInfo] = useState({ name: "", address: "", city: "", zip: "", country: "France", phone: "" });

  // ── Générer et télécharger le PDF ──
  const handleDownloadPDF = async () => {
    if (pdfUrl) { window.open(`${API_URL}${pdfUrl}`, "_blank"); return; }
    if (!patronResult?.patron) { alert("Patron non disponible"); return; }
    setIsGeneratingPDF(true);
    try {
      const res = await fetch(`${API_URL}/api/pdf`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ patron: patronResult.patron, ia: patronResult.ia, format: "A4" }),
      });
      if (!res.ok) throw new Error("Erreur PDF");
      const result = await res.json();
      setPdfUrl(result.url);
      window.open(`${API_URL}${result.url}`, "_blank");
    } catch (err) { alert("Erreur PDF : " + err.message); }
    setIsGeneratingPDF(false);
  };

  // ── Lancer le paiement Stripe ──
  const handleCheckout = async () => {
    const tierMap = { basic: "essentiel", standard: "complet", premium: "premium", essential: "essentiel", luxe: "luxe" };
    try {
      // Sauvegarder le patron pour le récupérer après paiement
      try {
        localStorage.setItem("patronia_checkout", JSON.stringify({
          patron: patronResult?.patron,
          ia: patronResult?.ia,
          mensurations: patronResult?.mensurations,
          formData: data,
        }));
      } catch(e) {}

      const res = await fetch(`${API_URL}/api/checkout`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ path: path === "diy" ? "diy" : "production", tier: tierMap[selectedPlan] || "complet" }),
      });
      const result = await res.json();
      if (result.checkout_url) { window.location.href = result.checkout_url; }
      else { setShowSuccess(true); }
    } catch { setShowSuccess(true); }
  };

  const diyPlans = [
    { id: "basic", label: "Essentiel", price: "1", features: ["Patron PDF multi-tailles", "Instructions de montage", "Liste des fournitures", "Plan de découpe"] },
    { id: "standard", label: "Complet", price: "1", popular: true, features: ["Tout de l'Essentiel", "Tutoriel vidéo pas à pas", "Conseils tissus personnalisés", "Support chat 7 jours", "Formats A4 + A0"] },
    { id: "premium", label: "Premium", price: "1", features: ["Tout du Complet", "Ajustements illimités 30j", "Consultation visio 30min", "Patron imprimé envoyé", "Toile d'essai guidée"] },
  ];

  const productionOptions = [
    { id: "essential", label: "Essentiel", price: "1", delivery: "4-5 semaines", features: ["Confection sur-mesure", "Tissu standard au choix", "Contrôle qualité", "Livraison France incluse"] },
    { id: "premium", label: "Premium", price: "1", popular: true, delivery: "3-4 semaines", features: ["Confection sur-mesure", "Tissu premium au choix", "Finitions haute qualité", "Étiquette personnalisée", "Livraison express incluse", "Retouche gratuite"] },
    { id: "luxe", label: "Luxe", price: "1", delivery: "3-4 semaines", features: ["Confection artisanale", "Tissu luxe (soie, lin premium)", "Finitions main & surpiqûres", "Étiquette tissée à votre nom", "Livraison express + suivi", "2 retouches gratuites", "Boîte cadeau premium"] },
  ];

  const fabricChoices = [
    { id: "coton_bio", name: "Coton bio", color: "#F5E6D3", desc: "Doux, respirant, certifié GOTS", available: ["essential", "premium", "luxe"] },
    { id: "lin_lave", name: "Lin lavé", color: "#D4C5A9", desc: "Texture naturelle, beau tombé", available: ["essential", "premium", "luxe"] },
    { id: "viscose_ecovero", name: "Viscose EcoVero", color: "#E8D5C4", desc: "Fluide, éco-responsable", available: ["premium", "luxe"] },
    { id: "tencel", name: "Tencel / Lyocell", color: "#C5D5D8", desc: "Soyeux, durable", available: ["premium", "luxe"] },
    { id: "soie", name: "Soie naturelle", color: "#F0E0D0", desc: "Luxueux, léger", available: ["luxe"] },
    { id: "laine_merinos", name: "Laine mérinos", color: "#D8CFC5", desc: "Chaud, noble", available: ["luxe"] },
  ];

  const timeline = [
    { step: "Validation", desc: "Vérification de votre patron", icon: "check", days: "J+0" },
    { step: "Coupe", desc: "Découpe de votre tissu", icon: "ciseaux", days: "J+3" },
    { step: "Confection", desc: "Assemblage et finitions", icon: "machine", days: "J+10" },
    { step: "Contrôle", desc: "Qualité et mesures", icon: "metre", days: "J+18" },
    { step: "Expédition", desc: "Emballage et envoi", icon: "patron_pdf", days: "J+21" },
    { step: "Livraison", desc: "Chez vous !", icon: "livraison", days: "J+25" },
  ];

  // ── SUCCESS SCREEN ──
  if (showSuccess) {
    const isDIY = path === "diy";
    return (
      <div style={{ maxWidth: 540, margin: "0 auto", textAlign: "center", padding: "50px 20px", animation: "fadeSlideIn 0.6s ease" }}>
        <div style={{
          width: 100, height: 100, borderRadius: "50%", margin: "0 auto 24px",
          background: isDIY ? "linear-gradient(135deg, #4CAF50, #66BB6A)" : "linear-gradient(135deg, #1A1A1A, #333)",
          display: "flex", alignItems: "center", justifyContent: "center",
          boxShadow: isDIY ? "0 8px 30px rgba(76,175,80,0.3)" : "0 8px 30px rgba(26,26,26,0.15)",
        }}><Icon name={isDIY ? "check" : "coeur"} size={44} style={{ filter: "brightness(0) invert(1)" }} /></div>
        <h2 style={{ fontFamily: "'Playfair Display'", fontSize: 28, color: "#2D2926", marginBottom: 10 }}>
          {isDIY ? "Merci pour votre commande !" : "Votre vêtement est en production !"}
        </h2>
        <p style={{ fontFamily: "'DM Sans'", fontSize: 14, color: "#888", lineHeight: 1.6 }}>
          {isDIY
            ? "Votre patron personnalisé est en cours de finalisation. Vous recevrez un email avec votre PDF dans les 24h."
            : "Nos artisans commencent la confection de votre pièce unique. Vous recevrez un email de suivi à chaque étape."
          }
        </p>

        {/* Recap */}
        <div style={{ marginTop: 28, background: "#F8F4F0", borderRadius: 16, padding: 22, fontFamily: "'DM Sans'", fontSize: 14, color: "#666", textAlign: "left" }}>
          <div style={{ fontWeight: 600, color: "#2D2926", marginBottom: 12 }}>📦 Récapitulatif</div>
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
            <span style={{ textTransform: "capitalize" }}>{data.type || "Vêtement"} {data.style || ""} sur-mesure</span>
            <span style={{ fontWeight: 700, color: "#2D2926" }}>
              €{isDIY ? diyPlans.find(p => p.id === selectedPlan)?.price : productionOptions.find(p => p.id === selectedPlan)?.price}
            </span>
          </div>
          {!isDIY && (
            <>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4, fontSize: 13, color: "#999" }}>
                <span>Tissu : {fabricChoices.find(f => f.id === selectedFabric)?.name || "Standard"}</span>
                <span>Taille : {selectedSize}</span>
              </div>
              <div style={{ marginTop: 12, padding: "10px 14px", background: "#fff", borderRadius: 10, border: "1px solid #EDE8E2" }}>
                <div style={{ fontSize: 11, color: "#AAA", marginBottom: 6, fontWeight: 600 }}>📍 Livraison estimée</div>
                <div style={{ fontSize: 14, fontWeight: 600, color: "#2D6B4F" }}>
                  {productionOptions.find(p => p.id === selectedPlan)?.delivery}
                </div>
              </div>
            </>
          )}
        </div>

        {/* Production timeline */}
        {!isDIY && (
          <div style={{ marginTop: 24, textAlign: "left" }}>
            <div style={{ fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 600, color: "#2D2926", marginBottom: 14 }}>🏭 Suivi de production</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
              {timeline.map((t, i) => (
                <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                    <div style={{
                      width: 32, height: 32, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center",
                      background: i === 0 ? "#B8956A" : "#F0EBE5",
                    }}><Icon name={t.icon} size={16} style={i === 0 ? { filter: "brightness(0) invert(1)" } : {}} /></div>
                    {i < timeline.length - 1 && <div style={{ width: 2, height: 24, background: "#EDE8E2" }} />}
                  </div>
                  <div style={{ paddingBottom: i < timeline.length - 1 ? 8 : 0 }}>
                    <div style={{ fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 600, color: "#2D2926" }}>{t.step}</div>
                    <div style={{ fontFamily: "'DM Sans'", fontSize: 11, color: "#AAA" }}>{t.desc} • {t.days}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  }

  // ── PATH CHOOSER ──
  if (path === null) {
    return (
      <div style={{ maxWidth: 800, margin: "0 auto", padding: "0 20px" }}>
        <div style={{ textAlign: "center", marginBottom: 32 }}>
          <h2 style={{ fontFamily: "'Playfair Display'", fontSize: 26, color: "#2D2926", marginBottom: 8 }}>
            Votre patron est prêt !
          </h2>
          <p style={{ fontFamily: "'DM Sans'", fontSize: 14, color: "#888", lineHeight: 1.5 }}>
            Choisissez comment vous souhaitez donner vie à votre création
          </p>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, maxWidth: 700, margin: "0 auto" }}>
          {/* DIY Option */}
          <div onClick={() => setPath("diy")} style={{
            background: "#FDFBF9", border: "2px solid #EDE8E2", borderRadius: 24, padding: 0,
            cursor: "pointer", overflow: "hidden", transition: "all 0.3s",
            boxShadow: "0 2px 12px rgba(0,0,0,0.04)",
          }}
          onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-4px)"; e.currentTarget.style.boxShadow = "0 12px 32px rgba(0,0,0,0.1)"; }}
          onMouseLeave={e => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = "0 2px 12px rgba(0,0,0,0.04)"; }}
          >
            {/* Visual header */}
            <div style={{
              height: 180, background: "linear-gradient(135deg, #FFF8F0, #F8ECE4)",
              display: "flex", alignItems: "center", justifyContent: "center", position: "relative",
            }}>
              <Icon name="ciseaux" size={70} style={{ opacity: 0.9 }} />
              <div style={{
                position: "absolute", top: 14, right: 14,
                background: "#2D2926", color: "#fff", fontFamily: "'DM Sans'", fontSize: 11,
                fontWeight: 600, padding: "4px 12px", borderRadius: 20,
              }}>DIY</div>
              {/* Decorative pattern lines */}
              <svg style={{ position: "absolute", bottom: 0, left: 0, right: 0, opacity: 0.1 }} viewBox="0 0 400 40" height="40">
                <line x1="0" y1="10" x2="400" y2="10" stroke="#2D2926" strokeWidth="1" strokeDasharray="8,4" />
                <line x1="0" y1="25" x2="400" y2="25" stroke="#2D2926" strokeWidth="1" strokeDasharray="4,8" />
              </svg>
            </div>

            <div style={{ padding: "20px 22px 24px" }}>
              <h3 style={{ fontFamily: "'Playfair Display'", fontSize: 20, fontWeight: 700, color: "#2D2926", marginBottom: 6 }}>
                Je couds moi-même
              </h3>
              <p style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#888", lineHeight: 1.5, marginBottom: 16 }}>
                Recevez votre patron PDF personnalisé avec toutes les instructions pour réaliser votre projet de couture.
              </p>

              <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginBottom: 16 }}>
                <span style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#AAA" }}>à partir de</span>
                <span style={{ fontFamily: "'Playfair Display'", fontSize: 28, fontWeight: 700, color: "#2D2926" }}>€1</span>
              </div>

              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {["Patron PDF sur-mesure", "Instructions détaillées", "Plan de découpe", "Support par chat"].map(f => (
                  <div key={f} style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#666", display: "flex", alignItems: "center", gap: 7 }}>
                    <span style={{ color: "#B8956A", fontSize: 12 }}>✓</span>{f}
                  </div>
                ))}
              </div>

              <div style={{
                marginTop: 18, padding: "12px", background: "#F8F4F0", borderRadius: 12, textAlign: "center",
                fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 600, color: "#2D2926",
              }}>
                Choisir cette option →
              </div>
            </div>
          </div>

          {/* PRODUCTION Option */}
          <div onClick={() => { setPath("produce"); setSelectedPlan("premium"); }} style={{
            background: "linear-gradient(135deg, #2D2926, #4A3F3A)", border: "2px solid #2D2926", borderRadius: 24, padding: 0,
            cursor: "pointer", overflow: "hidden", transition: "all 0.3s", position: "relative",
            boxShadow: "0 4px 20px rgba(45,41,38,0.2)",
          }}
          onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-4px)"; e.currentTarget.style.boxShadow = "0 16px 40px rgba(45,41,38,0.3)"; }}
          onMouseLeave={e => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = "0 4px 20px rgba(45,41,38,0.2)"; }}
          >
            {/* Popular badge */}
            <div style={{
              position: "absolute", top: 14, left: 14, zIndex: 2,
              background: "linear-gradient(135deg, #1A1A1A, #333)", color: "#fff",
              fontFamily: "'DM Sans'", fontSize: 10, fontWeight: 700, padding: "4px 12px",
              borderRadius: 20, letterSpacing: "0.04em",
            }}>✨ NOUVEAU</div>

            {/* Visual header */}
            <div style={{
              height: 180, background: "linear-gradient(135deg, #3D3530, #5A4D45)",
              display: "flex", alignItems: "center", justifyContent: "center", position: "relative",
            }}>
              <Icon name="robe" size={70} style={{ opacity: 0.9, filter: "brightness(0) invert(1)" }} />
              <div style={{
                position: "absolute", top: 14, right: 14,
                background: "linear-gradient(135deg, #1A1A1A, #333)", color: "#fff",
                fontFamily: "'DM Sans'", fontSize: 11, fontWeight: 600, padding: "4px 12px", borderRadius: 20,
              }}>CONFECTION</div>
              {/* Sewing stitch decoration */}
              <svg style={{ position: "absolute", bottom: 0, left: 0, right: 0, opacity: 0.15 }} viewBox="0 0 400 40" height="40">
                <path d="M0,20 Q50,5 100,20 Q150,35 200,20 Q250,5 300,20 Q350,35 400,20" fill="none" stroke="#fff" strokeWidth="2" />
              </svg>
            </div>

            <div style={{ padding: "20px 22px 24px" }}>
              <h3 style={{ fontFamily: "'Playfair Display'", fontSize: 20, fontWeight: 700, color: "#fff", marginBottom: 6 }}>
                Faites-le produire
              </h3>
              <p style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "rgba(255,255,255,0.65)", lineHeight: 1.5, marginBottom: 16 }}>
                Nos artisans confectionnent votre vêtement unique et vous le livrent chez vous. Zéro couture, 100% sur-mesure.
              </p>

              <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginBottom: 16 }}>
                <span style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "rgba(255,255,255,0.45)" }}>à partir de</span>
                <span style={{ fontFamily: "'Playfair Display'", fontSize: 28, fontWeight: 700, color: "#fff" }}>€1</span>
              </div>

              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {["Confection artisanale sur-mesure", "Choix du tissu premium", "Livraison France incluse", "Retouche gratuite"].map(f => (
                  <div key={f} style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "rgba(255,255,255,0.7)", display: "flex", alignItems: "center", gap: 7 }}>
                    <span style={{ color: "#C4A87C", fontSize: 12 }}>✓</span>{f}
                  </div>
                ))}
              </div>

              <div style={{
                marginTop: 18, padding: "12px",
                background: "linear-gradient(135deg, #1A1A1A, #333)", borderRadius: 12, textAlign: "center",
                fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 600, color: "#fff",
                boxShadow: "0 4px 16px rgba(26,26,26,0.15)",
              }}>
                Choisir cette option →
              </div>
            </div>
          </div>
        </div>

        {/* Trust badges */}
        <div style={{
          display: "flex", justifyContent: "center", gap: 28, marginTop: 32, flexWrap: "wrap",
        }}>
          {[
            { icon: "check", label: "Paiement sécurisé" },
            { icon: "machine", label: "Confection Europe" },
            { icon: "lin", label: "Tissus éco-responsables" },
            { icon: "coeur", label: "Satisfait ou remboursé" },
          ].map(b => (
            <div key={b.label} style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <Icon name={b.icon} size={18} />
              <span style={{ fontFamily: "'DM Sans'", fontSize: 11, color: "#AAA", fontWeight: 500 }}>{b.label}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── DIY PATH ──
  if (path === "diy") {
    return (
      <div style={{ maxWidth: 800, margin: "0 auto", padding: "0 20px" }}>
        {/* Back button */}
        <button onClick={() => setPath(null)} style={{
          background: "none", border: "none", fontFamily: "'DM Sans'", fontSize: 13,
          color: "#999", cursor: "pointer", fontWeight: 500, marginBottom: 16,
          display: "flex", alignItems: "center", gap: 5,
        }}>← Changer d'option</button>

        <div style={{ textAlign: "center", marginBottom: 28 }}>
          <div style={{ fontSize: 36, marginBottom: 8 }}><Icon name="ciseaux" size={40} /></div>
          <h2 style={{ fontFamily: "'Playfair Display'", fontSize: 24, color: "#2D2926", marginBottom: 6 }}>Je couds moi-même</h2>
          <p style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#888" }}>Choisissez votre formule de patron</p>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 14, marginBottom: 28 }}>
          {diyPlans.map(plan => {
            const sel = selectedPlan === plan.id;
            return (
              <div key={plan.id} onClick={() => setSelectedPlan(plan.id)} style={{
                background: sel ? "linear-gradient(135deg, #2D2926, #4A3F3A)" : "#FDFBF9",
                border: sel ? "2px solid #2D2926" : "2px solid #EDE8E2",
                borderRadius: 18, padding: 20, cursor: "pointer", position: "relative",
                transition: "all 0.3s", transform: sel ? "scale(1.02)" : "scale(1)",
                boxShadow: sel ? "0 8px 24px rgba(45,41,38,0.15)" : "none",
              }}>
                {plan.popular && <div style={{ position: "absolute", top: -10, right: 12, background: "linear-gradient(135deg, #1A1A1A, #333)", color: "#fff", fontFamily: "'DM Sans'", fontSize: 10, fontWeight: 600, padding: "3px 12px", borderRadius: 20 }}>Populaire</div>}
                <div style={{ fontFamily: "'DM Sans'", fontSize: 10, fontWeight: 600, letterSpacing: "0.08em", color: sel ? "rgba(255,255,255,0.5)" : "#AAA", textTransform: "uppercase", marginBottom: 6 }}>{plan.label}</div>
                <span style={{ fontFamily: "'Playfair Display'", fontSize: 30, fontWeight: 700, color: sel ? "#fff" : "#2D2926" }}>€{plan.price}</span>
                <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 12 }}>
                  {plan.features.map((f, i) => (
                    <div key={i} style={{ fontFamily: "'DM Sans'", fontSize: 11, color: sel ? "rgba(255,255,255,0.7)" : "#666", display: "flex", alignItems: "center", gap: 6 }}>
                      <span style={{ color: sel ? "#C4A87C" : "#B8956A", fontSize: 12 }}>✓</span>{f}
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>

        {/* Payment */}
        <div style={{ background: "#FDFBF9", borderRadius: 18, border: "2px solid #EDE8E2", padding: 22, maxWidth: 400, margin: "0 auto" }}>
          <h3 style={{ fontFamily: "'DM Sans'", fontSize: 14, fontWeight: 600, color: "#2D2926", marginBottom: 16 }}>Paiement sécurisé 🔒</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <div>
              <label style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", display: "block", marginBottom: 4 }}>Numéro de carte</label>
              <input placeholder="4242 4242 4242 4242" style={{ width: "100%", border: "2px solid #EDE8E2", borderRadius: 10, padding: "10px 12px", fontFamily: "'DM Sans'", fontSize: 13, outline: "none", background: "#fff", boxSizing: "border-box" }} />
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              <div style={{ flex: 1 }}><label style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", display: "block", marginBottom: 4 }}>Expiration</label><input placeholder="MM/AA" style={{ width: "100%", border: "2px solid #EDE8E2", borderRadius: 10, padding: "10px 12px", fontFamily: "'DM Sans'", fontSize: 13, outline: "none", background: "#fff", boxSizing: "border-box" }} /></div>
              <div style={{ flex: 1 }}><label style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", display: "block", marginBottom: 4 }}>CVC</label><input placeholder="123" style={{ width: "100%", border: "2px solid #EDE8E2", borderRadius: 10, padding: "10px 12px", fontFamily: "'DM Sans'", fontSize: 13, outline: "none", background: "#fff", boxSizing: "border-box" }} /></div>
            </div>
            <div><label style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", display: "block", marginBottom: 4 }}>Email</label><input placeholder="votre@email.com" style={{ width: "100%", border: "2px solid #EDE8E2", borderRadius: 10, padding: "10px 12px", fontFamily: "'DM Sans'", fontSize: 13, outline: "none", background: "#fff", boxSizing: "border-box" }} /></div>
          </div>
          <button onClick={handleCheckout} style={{
            width: "100%", marginTop: 16, background: "linear-gradient(135deg, #1A1A1A, #333)",
            border: "none", color: "#fff", fontFamily: "'DM Sans'", fontSize: 14, fontWeight: 600,
            padding: "13px", borderRadius: 12, cursor: "pointer", boxShadow: "0 4px 16px rgba(26,26,26,0.12)",
          }}>Payer €{diyPlans.find(p => p.id === selectedPlan)?.price} →</button>
          {patronResult?.patron && (
            <button onClick={handleDownloadPDF} disabled={isGeneratingPDF} style={{
              width: "100%", marginTop: 8, background: "none", border: "2px solid #2D2926",
              color: "#2D2926", fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 600,
              padding: "11px", borderRadius: 12, cursor: "pointer",
              opacity: isGeneratingPDF ? 0.5 : 1,
            }}>{isGeneratingPDF ? "Génération en cours..." : pdfUrl ? "Ouvrir le PDF patron" : "Aperçu PDF gratuit"}</button>
          )}
          <p style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#BBB", textAlign: "center", marginTop: 8 }}>Paiement sécurisé via Stripe • Satisfait ou remboursé 14j</p>
        </div>
      </div>
    );
  }

  // ── PRODUCTION PATH ──
  return (
    <div style={{ maxWidth: 860, margin: "0 auto", padding: "0 20px" }}>
      <button onClick={() => setPath(null)} style={{
        background: "none", border: "none", fontFamily: "'DM Sans'", fontSize: 13,
        color: "#999", cursor: "pointer", fontWeight: 500, marginBottom: 16,
        display: "flex", alignItems: "center", gap: 5,
      }}>← Changer d'option</button>

      <div style={{ textAlign: "center", marginBottom: 28 }}>
        <div style={{ marginBottom: 8 }}><Icon name="robe" size={40} /></div>
        <h2 style={{ fontFamily: "'Playfair Display'", fontSize: 24, color: "#2D2926", marginBottom: 6 }}>Faites produire votre création</h2>
        <p style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#888" }}>Nos artisans confectionnent votre pièce unique sur-mesure</p>
      </div>

      {/* Step 1: Choose tier */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontFamily: "'DM Sans'", fontSize: 12, fontWeight: 600, color: "#B8956A", marginBottom: 12, letterSpacing: "0.04em" }}>
          ① CHOISISSEZ VOTRE GAMME
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 12 }}>
          {productionOptions.map(opt => {
            const sel = selectedPlan === opt.id;
            return (
              <div key={opt.id} onClick={() => setSelectedPlan(opt.id)} style={{
                background: sel ? "linear-gradient(135deg, #2D2926, #4A3F3A)" : "#FDFBF9",
                border: sel ? "2px solid #2D2926" : "2px solid #EDE8E2",
                borderRadius: 16, padding: 18, cursor: "pointer", position: "relative",
                transition: "all 0.3s", transform: sel ? "scale(1.01)" : "scale(1)",
                boxShadow: sel ? "0 6px 20px rgba(45,41,38,0.15)" : "none",
              }}>
                {opt.popular && <div style={{ position: "absolute", top: -9, right: 12, background: "linear-gradient(135deg, #1A1A1A, #333)", color: "#fff", fontFamily: "'DM Sans'", fontSize: 9, fontWeight: 600, padding: "3px 10px", borderRadius: 20 }}>Populaire</div>}
                <div style={{ fontFamily: "'DM Sans'", fontSize: 10, fontWeight: 600, letterSpacing: "0.06em", color: sel ? "rgba(255,255,255,0.5)" : "#AAA", textTransform: "uppercase", marginBottom: 4 }}>{opt.label}</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 4, marginBottom: 4 }}>
                  <span style={{ fontFamily: "'Playfair Display'", fontSize: 28, fontWeight: 700, color: sel ? "#fff" : "#2D2926" }}>€{opt.price}</span>
                </div>
                <div style={{ fontFamily: "'DM Sans'", fontSize: 11, color: sel ? "rgba(255,255,255,0.5)" : "#BBB", marginBottom: 10 }}>
                  📦 {opt.delivery}
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                  {opt.features.map((f, i) => (
                    <div key={i} style={{ fontFamily: "'DM Sans'", fontSize: 11, color: sel ? "rgba(255,255,255,0.7)" : "#666", display: "flex", alignItems: "center", gap: 5 }}>
                      <span style={{ color: sel ? "#C4A87C" : "#B8956A", fontSize: 11 }}>✓</span>{f}
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Step 2: Choose fabric */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontFamily: "'DM Sans'", fontSize: 12, fontWeight: 600, color: "#B8956A", marginBottom: 12, letterSpacing: "0.04em" }}>
          ② CHOISISSEZ VOTRE TISSU
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
          {fabricChoices.map(fab => {
            const available = fab.available.includes(selectedPlan);
            const sel = selectedFabric === fab.id;
            return (
              <button key={fab.id} onClick={() => available && setSelectedFabric(fab.id)}
                style={{
                  padding: "10px 14px", borderRadius: 12, cursor: available ? "pointer" : "not-allowed",
                  border: sel ? "2px solid #2D2926" : "2px solid #EDE8E2",
                  background: sel ? "#2D2926" : available ? "#FDFBF9" : "#F5F3F0",
                  opacity: available ? 1 : 0.45,
                  display: "flex", alignItems: "center", gap: 10, transition: "all 0.2s",
                }}>
                <div style={{ width: 28, height: 28, borderRadius: "50%", background: fab.color, border: "2px solid rgba(0,0,0,0.08)" }} />
                <div style={{ textAlign: "left" }}>
                  <div style={{ fontFamily: "'DM Sans'", fontSize: 12, fontWeight: 600, color: sel ? "#fff" : "#2D2926" }}>{fab.name}</div>
                  <div style={{ fontFamily: "'DM Sans'", fontSize: 10, color: sel ? "rgba(255,255,255,0.6)" : "#AAA" }}>
                    {available ? fab.desc : `Disponible en ${fab.available[0]}`}
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Step 3: Confirm size */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontFamily: "'DM Sans'", fontSize: 12, fontWeight: 600, color: "#B8956A", marginBottom: 12, letterSpacing: "0.04em" }}>
          ③ CONFIRMEZ VOTRE TAILLE
        </div>
        <div style={{
          background: "#F8F4F0", borderRadius: 14, padding: 16,
          display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12,
        }}>
          <div>
            <div style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#2D2926", fontWeight: 500 }}>
              Basé sur vos mensurations et votre profil
            </div>
            <div style={{ fontFamily: "'DM Sans'", fontSize: 11, color: "#AAA", marginTop: 2 }}>
              {data.mensurations?.tour_poitrine && `Poitrine: ${data.mensurations.tour_poitrine}cm`}
              {data.mensurations?.tour_taille && ` • Taille: ${data.mensurations.tour_taille}cm`}
              {data.mensurations?.tour_hanches && ` • Hanches: ${data.mensurations.tour_hanches}cm`}
            </div>
          </div>
          <div style={{ display: "flex", gap: 6 }}>
            {["XS", "S", "M", "L", "XL", "XXL"].map(s => (
              <button key={s} onClick={() => setSelectedSize(s)} style={{
                width: 36, height: 36, borderRadius: 10, border: selectedSize === s ? "2px solid #2D2926" : "2px solid #DDD",
                background: selectedSize === s ? "#2D2926" : "#fff",
                color: selectedSize === s ? "#fff" : "#666",
                fontFamily: "'DM Sans'", fontSize: 11, fontWeight: 600, cursor: "pointer",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>{s}</button>
            ))}
          </div>
        </div>
        <p style={{ fontFamily: "'DM Sans'", fontSize: 11, color: "#AAA", marginTop: 6, fontStyle: "italic" }}>
          💡 Votre vêtement sera confectionné selon vos mensurations exactes, pas seulement la taille standard.
        </p>
      </div>

      {/* Step 4: Delivery info + Payment */}
      <div style={{ display: "flex", gap: 16, flexWrap: "wrap" }}>
        {/* Delivery */}
        <div style={{ flex: "1 1 260px", background: "#FDFBF9", borderRadius: 16, border: "2px solid #EDE8E2", padding: 20 }}>
          <h3 style={{ fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 600, color: "#2D2926", marginBottom: 14 }}>📍 Adresse de livraison</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {[
              { key: "name", label: "Nom complet", placeholder: "Marie Dupont" },
              { key: "address", label: "Adresse", placeholder: "12 rue de la Couture" },
              { key: "city", label: "Ville", placeholder: "Paris" },
              { key: "zip", label: "Code postal", placeholder: "75011" },
              { key: "phone", label: "Téléphone", placeholder: "06 12 34 56 78" },
            ].map(f => (
              <div key={f.key}>
                <label style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", display: "block", marginBottom: 3 }}>{f.label}</label>
                <input value={deliveryInfo[f.key]} onChange={e => setDeliveryInfo(p => ({ ...p, [f.key]: e.target.value }))}
                  placeholder={f.placeholder}
                  style={{ width: "100%", border: "2px solid #EDE8E2", borderRadius: 10, padding: "9px 12px", fontFamily: "'DM Sans'", fontSize: 12, outline: "none", background: "#fff", boxSizing: "border-box" }} />
              </div>
            ))}
          </div>
        </div>

        {/* Payment */}
        <div style={{ flex: "1 1 260px", background: "#FDFBF9", borderRadius: 16, border: "2px solid #EDE8E2", padding: 20 }}>
          <h3 style={{ fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 600, color: "#2D2926", marginBottom: 14 }}>💳 Paiement sécurisé</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            <div><label style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", display: "block", marginBottom: 3 }}>Carte bancaire</label><input placeholder="4242 4242 4242 4242" style={{ width: "100%", border: "2px solid #EDE8E2", borderRadius: 10, padding: "9px 12px", fontFamily: "'DM Sans'", fontSize: 12, outline: "none", background: "#fff", boxSizing: "border-box" }} /></div>
            <div style={{ display: "flex", gap: 8 }}>
              <div style={{ flex: 1 }}><label style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", display: "block", marginBottom: 3 }}>Exp.</label><input placeholder="MM/AA" style={{ width: "100%", border: "2px solid #EDE8E2", borderRadius: 10, padding: "9px 12px", fontFamily: "'DM Sans'", fontSize: 12, outline: "none", background: "#fff", boxSizing: "border-box" }} /></div>
              <div style={{ flex: 1 }}><label style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", display: "block", marginBottom: 3 }}>CVC</label><input placeholder="123" style={{ width: "100%", border: "2px solid #EDE8E2", borderRadius: 10, padding: "9px 12px", fontFamily: "'DM Sans'", fontSize: 12, outline: "none", background: "#fff", boxSizing: "border-box" }} /></div>
            </div>
            <div><label style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#AAA", display: "block", marginBottom: 3 }}>Email</label><input placeholder="votre@email.com" style={{ width: "100%", border: "2px solid #EDE8E2", borderRadius: 10, padding: "9px 12px", fontFamily: "'DM Sans'", fontSize: 12, outline: "none", background: "#fff", boxSizing: "border-box" }} /></div>
          </div>

          {/* Order summary */}
          <div style={{ marginTop: 14, padding: "12px 14px", background: "#F8F4F0", borderRadius: 10 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "'DM Sans'", fontSize: 12, color: "#666", marginBottom: 4 }}>
              <span>Confection {productionOptions.find(p => p.id === selectedPlan)?.label}</span>
              <span>€{productionOptions.find(p => p.id === selectedPlan)?.price}</span>
            </div>
            {selectedFabric && (
              <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "'DM Sans'", fontSize: 11, color: "#AAA", marginBottom: 4 }}>
                <span>Tissu : {fabricChoices.find(f => f.id === selectedFabric)?.name}</span>
                <span>inclus</span>
              </div>
            )}
            <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "'DM Sans'", fontSize: 11, color: "#AAA", marginBottom: 4 }}>
              <span>Livraison France</span>
              <span>incluse</span>
            </div>
            <div style={{ borderTop: "1px solid #E8E0D8", marginTop: 8, paddingTop: 8, display: "flex", justifyContent: "space-between", fontFamily: "'DM Sans'" }}>
              <span style={{ fontSize: 14, fontWeight: 700, color: "#2D2926" }}>Total</span>
              <span style={{ fontSize: 14, fontWeight: 700, color: "#B8956A" }}>€{productionOptions.find(p => p.id === selectedPlan)?.price}</span>
            </div>
          </div>

          <button onClick={handleCheckout} style={{
            width: "100%", marginTop: 14, background: "linear-gradient(135deg, #1A1A1A, #333)",
            border: "none", color: "#fff", fontFamily: "'DM Sans'", fontSize: 14, fontWeight: 600,
            padding: "13px", borderRadius: 12, cursor: "pointer", boxShadow: "0 4px 16px rgba(26,26,26,0.12)",
          }}>
            Commander • €{productionOptions.find(p => p.id === selectedPlan)?.price} →
          </button>
          <p style={{ fontFamily: "'DM Sans'", fontSize: 9, color: "#BBB", textAlign: "center", marginTop: 8, lineHeight: 1.4 }}>
            Paiement sécurisé via Stripe • Livraison {productionOptions.find(p => p.id === selectedPlan)?.delivery} • Retouche offerte
          </p>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// ─── LANDING PAGE ───────────────────────────────────
// ═══════════════════════════════════════════════════════
function Landing({ onStart }) {
  const [hovered, setHovered] = useState(null);
  const [scrollY, setScrollY] = useState(0);

  useEffect(() => {
    const h = () => setScrollY(window.scrollY);
    window.addEventListener("scroll", h, { passive: true });
    return () => window.removeEventListener("scroll", h);
  }, []);

  const parallax = (speed) => ({ transform: `translateY(${scrollY * speed}px)` });

  return (
    <div style={{ minHeight: "100vh", background: "#FFFDF9", fontFamily: "'DM Sans', sans-serif", overflow: "hidden" }}>

      {/* ── NAV ── */}
      <nav style={{
        position: "fixed", top: 0, left: 0, right: 0, zIndex: 100,
        padding: "16px 32px", display: "flex", alignItems: "center", justifyContent: "space-between",
        background: scrollY > 60 ? "rgba(255,253,249,0.92)" : "transparent",
        backdropFilter: scrollY > 60 ? "blur(20px)" : "none",
        borderBottom: scrollY > 60 ? "1px solid rgba(0,0,0,0.05)" : "1px solid transparent",
        transition: "all 0.4s ease",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Logo size="small" />
        </div>
        <button onClick={onStart} style={{
          background: "#2D2926", color: "#fff", border: "none", padding: "10px 24px",
          borderRadius: 50, fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 600,
          cursor: "pointer", transition: "all 0.3s ease",
          boxShadow: "0 2px 10px rgba(45,41,38,0.15)",
        }}>Créer mon patron</button>
      </nav>

      {/* ── HERO ── */}
      <section style={{
        position: "relative", minHeight: "100vh", display: "flex", alignItems: "center",
        padding: "120px 32px 80px", maxWidth: 1200, margin: "0 auto",
      }}>
        {/* Floating icons background */}
        <div style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, overflow: "hidden", pointerEvents: "none" }}>
          {[
            { name: "robe", x: "8%", y: "15%", size: 60, rot: -12, speed: -0.08 },
            { name: "metre", x: "85%", y: "12%", size: 50, rot: 15, speed: -0.06 },
            { name: "ciseaux", x: "92%", y: "55%", size: 45, rot: -8, speed: -0.1 },
            { name: "machine", x: "5%", y: "65%", size: 55, rot: 10, speed: -0.07 },
            { name: "coton", x: "78%", y: "78%", size: 40, rot: -20, speed: -0.05 },
            { name: "mannequin", x: "15%", y: "85%", size: 38, rot: 5, speed: -0.09 },
          ].map((ico, i) => (
            <div key={i} style={{
              position: "absolute", left: ico.x, top: ico.y, opacity: 0.07,
              transform: `rotate(${ico.rot}deg) translateY(${scrollY * ico.speed}px)`,
              transition: "transform 0.1s linear",
            }}>
              <Icon name={ico.name} size={ico.size} />
            </div>
          ))}
        </div>

        <div style={{ position: "relative", zIndex: 2, maxWidth: 680 }}>
          {/* Eyebrow */}
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "6px 16px 6px 8px", borderRadius: 50,
            background: "rgba(184,149,106,0.06)", border: "1px solid rgba(184,149,106,0.12)",
            marginBottom: 28, animation: "fadeSlideIn 0.6s ease",
          }}>
            <div style={{ width: 22, height: 22, borderRadius: "50%", background: "#B8956A", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="coeur" size={12} style={{ filter: "brightness(0) invert(1)" }} />
            </div>
            <span style={{ fontFamily: "'DM Sans'", fontSize: 12, fontWeight: 600, color: "#B8956A", letterSpacing: "0.02em" }}>Intelligence artificielle + savoir-faire couture</span>
          </div>

          {/* Title */}
          <h1 style={{
            fontFamily: "'Playfair Display'", fontSize: "clamp(38px, 6vw, 64px)",
            fontWeight: 800, color: "#2D2926", lineHeight: 1.08, marginBottom: 24,
            animation: "fadeSlideIn 0.7s ease",
          }}>
            Votre patron de couture
            <br />
            <span style={{ color: "#B8956A", fontStyle: "italic" }}>sur-mesure</span>
            <span style={{ fontFamily: "'Caveat'", fontSize: "clamp(22px, 3vw, 32px)", color: "#C4B8A8", marginLeft: 12, fontWeight: 500 }}>en quelques clics</span>
          </h1>

          {/* Subtitle */}
          <p style={{
            fontFamily: "'DM Sans'", fontSize: "clamp(15px, 2vw, 18px)", color: "#888",
            lineHeight: 1.7, maxWidth: 520, marginBottom: 40,
            animation: "fadeSlideIn 0.8s ease",
          }}>
            PatronIA crée un patron personnalisé à vos mensurations, votre style et votre niveau.
            Cousez-le vous-même ou faites-le confectionner par nos artisans.
          </p>

          {/* CTA */}
          <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap", animation: "fadeSlideIn 0.9s ease" }}>
            <button onClick={onStart}
              onMouseEnter={() => setHovered("cta")} onMouseLeave={() => setHovered(null)}
              style={{
                background: "#1A1A1A",
                color: "#fff", border: "none", padding: "16px 36px", borderRadius: 60,
                fontFamily: "'DM Sans'", fontSize: 16, fontWeight: 700, cursor: "pointer",
                display: "flex", alignItems: "center", gap: 10,
                boxShadow: hovered === "cta" ? "0 8px 32px rgba(26,26,26,0.25)" : "0 4px 20px rgba(26,26,26,0.12)",
                transform: hovered === "cta" ? "translateY(-2px)" : "translateY(0)",
                transition: "all 0.3s cubic-bezier(0.4,0,0.2,1)",
              }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
              Créer mon patron
            </button>
            <span style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#BBB" }}>Gratuit • 5 min</span>
          </div>

          {/* Social proof mini */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 32, animation: "fadeSlideIn 1s ease" }}>
            <div style={{ display: "flex" }}>
              {[0,1,2,3].map(i => (
                <div key={i} style={{
                  width: 28, height: 28, borderRadius: "50%", border: "2px solid #FFFDF9",
                  background: ["#B8956A", "#C4A87C", "#2D2926", "#C4B8A8"][i],
                  marginLeft: i > 0 ? -8 : 0, display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  <Icon name={["femme","homme","enfant","nongenre"][i]} size={14} style={{ filter: "brightness(0) invert(1)" }} />
                </div>
              ))}
            </div>
            <span style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#AAA" }}>
              <strong style={{ color: "#2D2926" }}>2 847</strong> patrons créés ce mois
            </span>
          </div>
        </div>

        {/* Hero visual - Pattern preview card */}
        <div style={{
          position: "absolute", right: "5%", top: "50%", transform: `translateY(-50%) rotate(3deg) translateY(${scrollY * -0.04}px)`,
          width: 320, display: "none",
        }}>
          {/* Show on desktop via media query workaround */}
        </div>
      </section>

      {/* ── MARQUEE ── */}
      <div style={{
        padding: "20px 0", background: "#2D2926", overflow: "hidden", position: "relative",
      }}>
        <div style={{
          display: "flex", gap: 48, animation: "marquee 20s linear infinite",
          whiteSpace: "nowrap",
        }}>
          {[...Array(2)].map((_, rep) => (
            <div key={rep} style={{ display: "flex", gap: 48, alignItems: "center", flexShrink: 0 }}>
              {["Sur-mesure", "Patron PDF", "Made in France", "IA générative", "Toutes tailles", "Éco-responsable", "Couture guidée", "Artisans qualifiés"].map((t, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <Icon name={["metre","patron_pdf","machine","coeur","sablier","lin","ciseaux","mannequin"][i]} size={16} style={{ filter: "brightness(0) invert(1)", opacity: 0.4 }} />
                  <span style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "rgba(255,255,255,0.5)", fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase" }}>{t}</span>
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>

      {/* ── COMMENT ÇA MARCHE ── */}
      <section style={{ padding: "100px 32px", maxWidth: 1100, margin: "0 auto" }}>
        <div style={{ textAlign: "center", marginBottom: 64 }}>
          <span style={{ fontFamily: "'Caveat'", fontSize: 18, color: "#B8956A", fontWeight: 600 }}>Simple comme 1, 2, 3</span>
          <h2 style={{ fontFamily: "'Playfair Display'", fontSize: "clamp(28px, 4vw, 42px)", fontWeight: 700, color: "#2D2926", marginTop: 8 }}>
            Comment ça marche ?
          </h2>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 24 }}>
          {[
            { icon: "chat", num: "01", title: "Décrivez votre projet", desc: "Répondez à quelques questions sur votre morphologie, le vêtement souhaité, votre tissu et votre niveau.", color: "#B8956A" },
            { icon: "coeur", num: "02", title: "Swipez vos inspirations", desc: "Parcourez des modèles et indiquez ce qui vous plaît. Notre IA comprend votre style.", color: "#C4A87C" },
            { icon: "patron_pdf", num: "03", title: "Recevez votre patron", desc: "Un patron PDF sur-mesure, avec instructions détaillées adaptées à votre niveau de couture.", color: "#2D6B4F" },
            { icon: "robe", num: "04", title: "Cousez ou faites produire", desc: "Lancez-vous en DIY avec notre guide pas-à-pas, ou confiez la confection à nos artisans.", color: "#2D6B8A" },
          ].map((s, i) => (
            <div key={i}
              onMouseEnter={() => setHovered(`step-${i}`)} onMouseLeave={() => setHovered(null)}
              style={{
                position: "relative", padding: "36px 28px 32px", borderRadius: 20,
                background: "#FDFBF9", border: "1.5px solid #EDE8E2",
                transition: "all 0.35s cubic-bezier(0.4,0,0.2,1)",
                transform: hovered === `step-${i}` ? "translateY(-6px)" : "translateY(0)",
                boxShadow: hovered === `step-${i}` ? "0 16px 40px rgba(0,0,0,0.08)" : "0 2px 8px rgba(0,0,0,0.02)",
              }}>
              <div style={{
                position: "absolute", top: -16, left: 24,
                width: 44, height: 44, borderRadius: 14,
                background: s.color, display: "flex", alignItems: "center", justifyContent: "center",
                boxShadow: `0 4px 16px ${s.color}33`,
              }}>
                <Icon name={s.icon} size={22} style={{ filter: "brightness(0) invert(1)" }} />
              </div>
              <div style={{ fontFamily: "'Caveat'", fontSize: 40, fontWeight: 700, color: "#EDE8E2", position: "absolute", top: 12, right: 20 }}>{s.num}</div>
              <h3 style={{ fontFamily: "'Playfair Display'", fontSize: 18, fontWeight: 700, color: "#2D2926", marginTop: 20, marginBottom: 10 }}>{s.title}</h3>
              <p style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#999", lineHeight: 1.7 }}>{s.desc}</p>
            </div>
          ))}
        </div>
      </section>

      {/* ── FEATURES BENTO ── */}
      <section style={{ padding: "40px 32px 100px", maxWidth: 1100, margin: "0 auto" }}>
        <div style={{
          display: "grid", gap: 16,
          gridTemplateColumns: "repeat(12, 1fr)", gridAutoRows: "minmax(180px, auto)",
        }}>
          {/* Card 1 — wide */}
          <div style={{
            gridColumn: "span 7", borderRadius: 24, padding: "36px 32px",
            background: "linear-gradient(145deg, #2D2926, #3D3936)",
            position: "relative", overflow: "hidden",
          }}>
            <div style={{ position: "relative", zIndex: 2 }}>
              <span style={{ fontFamily: "'Caveat'", fontSize: 15, color: "#B8956A", fontWeight: 600 }}>Intelligence artificielle</span>
              <h3 style={{ fontFamily: "'Playfair Display'", fontSize: 24, fontWeight: 700, color: "#fff", marginTop: 6, marginBottom: 12, lineHeight: 1.3 }}>
                Un patron qui <em style={{ color: "#C4A87C" }}>vous</em> ressemble
              </h3>
              <p style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "rgba(255,255,255,0.5)", lineHeight: 1.7, maxWidth: 360 }}>
                Notre IA analyse vos mensurations, votre morphologie et vos préférences pour générer un patron parfaitement ajusté. Pas de grading approximatif.
              </p>
            </div>
            <div style={{ position: "absolute", right: 20, bottom: 20, opacity: 0.08 }}>
              <Icon name="sablier" size={140} style={{ filter: "brightness(0) invert(1)" }} />
            </div>
          </div>

          {/* Card 2 — square */}
          <div style={{
            gridColumn: "span 5", borderRadius: 24, padding: "32px 28px",
            background: "linear-gradient(145deg, #B8956A, #C01050)",
            position: "relative", overflow: "hidden",
          }}>
            <span style={{ fontFamily: "'Caveat'", fontSize: 15, color: "rgba(255,255,255,0.7)", fontWeight: 600 }}>Tous niveaux</span>
            <h3 style={{ fontFamily: "'Playfair Display'", fontSize: 22, fontWeight: 700, color: "#fff", marginTop: 6, marginBottom: 12 }}>
              De débutant·e à expert·e
            </h3>
            <div style={{ display: "flex", gap: 8, marginTop: 16 }}>
              {["niveau_debutant","niveau_inter","niveau_avance","niveau_expert"].map((n,i) => (
                <div key={i} style={{ width: 44, height: 44, borderRadius: 12, background: "rgba(255,255,255,0.15)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name={n} size={24} style={{ filter: "brightness(0) invert(1)" }} />
                </div>
              ))}
            </div>
          </div>

          {/* Card 3 — Tissus */}
          <div style={{
            gridColumn: "span 4", borderRadius: 24, padding: "32px 24px",
            background: "#FDFBF9", border: "1.5px solid #EDE8E2",
            position: "relative", overflow: "hidden",
          }}>
            <span style={{ fontFamily: "'Caveat'", fontSize: 15, color: "#B8956A", fontWeight: 600 }}>8 familles de tissus</span>
            <h3 style={{ fontFamily: "'Playfair Display'", fontSize: 18, fontWeight: 700, color: "#2D2926", marginTop: 6, marginBottom: 16 }}>
              Adapté à votre matière
            </h3>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {[{n:"coton",l:"Coton"},{n:"lin",l:"Lin"},{n:"soie",l:"Soie"},{n:"laine",l:"Laine"},{n:"jersey",l:"Jersey"},{n:"jean",l:"Denim"}].map(t => (
                <div key={t.n} style={{ display: "flex", alignItems: "center", gap: 5, padding: "4px 10px", borderRadius: 20, background: "#F4F0EB" }}>
                  <Icon name={t.n} size={14} />
                  <span style={{ fontFamily: "'DM Sans'", fontSize: 11, color: "#666", fontWeight: 500 }}>{t.l}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Card 4 — Production */}
          <div style={{
            gridColumn: "span 8", borderRadius: 24, padding: "36px 32px",
            background: "linear-gradient(145deg, #FFF8F0, #F8ECE4)",
            border: "1.5px solid #EDE8E2", position: "relative", overflow: "hidden",
          }}>
            <div style={{ display: "flex", gap: 28, alignItems: "center", flexWrap: "wrap" }}>
              <div style={{ flex: "1 1 280px" }}>
                <span style={{ fontFamily: "'Caveat'", fontSize: 15, color: "#B8956A", fontWeight: 600 }}>Double parcours</span>
                <h3 style={{ fontFamily: "'Playfair Display'", fontSize: 22, fontWeight: 700, color: "#2D2926", marginTop: 6, marginBottom: 12, lineHeight: 1.3 }}>
                  DIY ou confection artisanale
                </h3>
                <p style={{ fontFamily: "'DM Sans'", fontSize: 13, color: "#999", lineHeight: 1.7 }}>
                  Recevez votre patron PDF pour coudre chez vous, ou confiez la réalisation complète à nos artisans européens.
                </p>
              </div>
              <div style={{ display: "flex", gap: 12 }}>
                {[
                  { icon: "ciseaux", label: "DIY", sub: "Patron PDF", bg: "#2D2926" },
                  { icon: "machine", label: "Production", sub: "Fait pour vous", bg: "#B8956A" },
                ].map((p, i) => (
                  <div key={i} style={{
                    width: 120, padding: "20px 16px", borderRadius: 16,
                    background: p.bg, textAlign: "center",
                  }}>
                    <Icon name={p.icon} size={32} style={{ filter: "brightness(0) invert(1)", marginBottom: 8, display: "block", margin: "0 auto 8px" }} />
                    <div style={{ fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 700, color: "#fff" }}>{p.label}</div>
                    <div style={{ fontFamily: "'Caveat'", fontSize: 12, color: "rgba(255,255,255,0.6)" }}>{p.sub}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ── TYPES DE VÊTEMENTS ── */}
      <section style={{ padding: "60px 32px 100px", background: "#F8F4F0" }}>
        <div style={{ maxWidth: 1100, margin: "0 auto" }}>
          <div style={{ textAlign: "center", marginBottom: 48 }}>
            <span style={{ fontFamily: "'Caveat'", fontSize: 18, color: "#B8956A", fontWeight: 600 }}>Toutes les pièces</span>
            <h2 style={{ fontFamily: "'Playfair Display'", fontSize: "clamp(26px, 4vw, 38px)", fontWeight: 700, color: "#2D2926", marginTop: 8 }}>
              Quel sera votre prochain projet ?
            </h2>
          </div>
          <div style={{ display: "flex", justifyContent: "center", flexWrap: "wrap", gap: 16 }}>
            {[
              { icon: "robe", label: "Robes" },
              { icon: "haut", label: "Hauts" },
              { icon: "pantalon", label: "Pantalons" },
              { icon: "jupe", label: "Jupes" },
              { icon: "veste", label: "Vestes" },
              { icon: "combinaison", label: "Combis" },
              { icon: "lingerie", label: "Lingerie" },
              { icon: "accessoire", label: "Accessoires" },
            ].map((v, i) => (
              <div key={i}
                onMouseEnter={() => setHovered(`v-${i}`)} onMouseLeave={() => setHovered(null)}
                style={{
                  width: 110, padding: "24px 12px 18px", borderRadius: 18,
                  background: hovered === `v-${i}` ? "#2D2926" : "#FDFBF9",
                  border: "1.5px solid #EDE8E2", textAlign: "center",
                  cursor: "pointer", transition: "all 0.3s ease",
                  transform: hovered === `v-${i}` ? "translateY(-4px)" : "translateY(0)",
                  boxShadow: hovered === `v-${i}` ? "0 12px 32px rgba(0,0,0,0.1)" : "none",
                }}>
                <Icon name={v.icon} size={36} style={hovered === `v-${i}` ? { filter: "brightness(0) invert(1)" } : {}} />
                <div style={{
                  fontFamily: "'DM Sans'", fontSize: 12, fontWeight: 600, marginTop: 10,
                  color: hovered === `v-${i}` ? "#fff" : "#2D2926",
                  transition: "color 0.3s ease",
                }}>{v.label}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ── TESTIMONIALS ── */}
      <section style={{ padding: "100px 32px", maxWidth: 1100, margin: "0 auto" }}>
        <div style={{ textAlign: "center", marginBottom: 48 }}>
          <span style={{ fontFamily: "'Caveat'", fontSize: 18, color: "#B8956A", fontWeight: 600 }}>Elles l'ont adopté</span>
          <h2 style={{ fontFamily: "'Playfair Display'", fontSize: "clamp(26px, 4vw, 38px)", fontWeight: 700, color: "#2D2926", marginTop: 8 }}>
            Ce qu'en disent nos couturières
          </h2>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 20 }}>
          {[
            { name: "Marie L.", level: "Intermédiaire", text: "Le patron tombait parfaitement dès la première toile. Mes ajustements FBA étaient déjà intégrés, incroyable !", stars: 5 },
            { name: "Sophie D.", level: "Débutante", text: "Les instructions étape par étape m'ont permis de coudre ma première robe. Je n'aurais jamais osé sans PatronIA.", stars: 5 },
            { name: "Camille R.", level: "Avancée", text: "J'ai fait produire un manteau sur-mesure. La qualité de confection et le tombé sont exactement ce que j'imaginais.", stars: 5 },
          ].map((t, i) => (
            <div key={i} style={{
              padding: "28px 24px", borderRadius: 20,
              background: "#FDFBF9", border: "1.5px solid #EDE8E2",
            }}>
              <div style={{ display: "flex", gap: 4, marginBottom: 14 }}>
                {[...Array(t.stars)].map((_, j) => (
                  <Icon key={j} name="coeur" size={14} />
                ))}
              </div>
              <p style={{ fontFamily: "'DM Sans'", fontSize: 14, color: "#555", lineHeight: 1.7, marginBottom: 18, fontStyle: "italic" }}>
                "{t.text}"
              </p>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ width: 32, height: 32, borderRadius: "50%", background: "#F0EBE5", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name="femme" size={16} />
                </div>
                <div>
                  <div style={{ fontFamily: "'DM Sans'", fontSize: 13, fontWeight: 600, color: "#2D2926" }}>{t.name}</div>
                  <div style={{ fontFamily: "'Caveat'", fontSize: 12, color: "#B8956A" }}>{t.level}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* ── FINAL CTA ── */}
      <section style={{
        padding: "80px 32px", margin: "0 32px 60px", borderRadius: 32,
        background: "linear-gradient(145deg, #2D2926, #3D3936)",
        textAlign: "center", position: "relative", overflow: "hidden",
        maxWidth: 1040, marginLeft: "auto", marginRight: "auto",
      }}>
        <div style={{ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", opacity: 0.04, pointerEvents: "none" }}>
          <Icon name="robe" size={300} style={{ filter: "brightness(0) invert(1)" }} />
        </div>
        <div style={{ position: "relative", zIndex: 2 }}>
          <h2 style={{ fontFamily: "'Playfair Display'", fontSize: "clamp(28px, 5vw, 44px)", fontWeight: 800, color: "#fff", marginBottom: 16, lineHeight: 1.15 }}>
            Prêt·e à créer votre
            <br />
            <span style={{ color: "#C4A87C", fontStyle: "italic" }}>chef-d'œuvre</span> ?
          </h2>
          <p style={{ fontFamily: "'DM Sans'", fontSize: 15, color: "rgba(255,255,255,0.45)", maxWidth: 440, margin: "0 auto 32px", lineHeight: 1.7 }}>
            Décrivez votre projet et laissez PatronIA créer le patron parfait pour vous.
          </p>
          <button onClick={onStart}
            onMouseEnter={() => setHovered("cta2")} onMouseLeave={() => setHovered(null)}
            style={{
              background: "linear-gradient(135deg, #1A1A1A, #333)",
              color: "#fff", border: "none", padding: "18px 44px", borderRadius: 60,
              fontFamily: "'DM Sans'", fontSize: 17, fontWeight: 700, cursor: "pointer",
              display: "inline-flex", alignItems: "center", gap: 12,
              boxShadow: hovered === "cta2" ? "0 8px 40px rgba(26,26,26,0.3)" : "0 4px 24px rgba(26,26,26,0.15)",
              transform: hovered === "cta2" ? "scale(1.04)" : "scale(1)",
              transition: "all 0.3s cubic-bezier(0.4,0,0.2,1)",
            }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
            Créer mon patron gratuitement
          </button>
          <div style={{ display: "flex", justifyContent: "center", gap: 28, marginTop: 28 }}>
            {[
              { icon: "check", label: "Gratuit" },
              { icon: "horloge", label: "5 minutes" },
              { icon: "patron_pdf", label: "Patron PDF" },
            ].map((b, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <Icon name={b.icon} size={14} style={{ filter: "brightness(0) invert(1)", opacity: 0.5 }} />
                <span style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "rgba(255,255,255,0.4)", fontWeight: 500 }}>{b.label}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ── BLOG SEO ── */}
      <section style={{ padding: "60px 32px", maxWidth: 1100, margin: "0 auto" }}>
        <div style={{ textAlign: "center", marginBottom: 36 }}>
          <span style={{ fontFamily: "'Caveat'", fontSize: 18, color: "#B8956A" }}>Nos guides couture</span>
          <h2 style={{ fontFamily: "'Playfair Display'", fontSize: 30, color: "#2D2926", marginTop: 6 }}>Le blog PatronIA</h2>
          <p style={{ fontFamily: "'DM Sans'", fontSize: 14, color: "#888", marginTop: 8, maxWidth: 500, margin: "8px auto 0" }}>
            Tutoriels, guides pratiques et conseils pour coudre des vêtements qui vous vont vraiment.
          </p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 20 }}>
          {[
            { emoji: "✂️", tag: "Guide", title: "Patron sur-mesure : le guide complet", desc: "Comment créer un patron adapté à vos mensurations", slug: "patron-couture-sur-mesure-guide-complet", time: "8 min" },
            { emoji: "📏", tag: "Tutoriel", title: "Comment prendre ses mensurations", desc: "Les 8 mesures essentielles pas à pas", slug: "comment-prendre-ses-mensurations-couture", time: "6 min" },
            { emoji: "🧵", tag: "Guide", title: "Quel tissu choisir pour votre patron ?", desc: "Coton, lin, soie... le guide par projet", slug: "quel-tissu-choisir-patron-couture", time: "7 min" },
            { emoji: "🖨️", tag: "Tutoriel", title: "Imprimer un patron PDF en A4", desc: "La méthode infaillible pour assembler vos pages", slug: "imprimer-patron-couture-pdf-a4", time: "5 min" },
            { emoji: "👗", tag: "Guide", title: "Quelle morphologie, quel patron ?", desc: "Choisir la coupe qui met en valeur votre corps", slug: "morphologie-femme-quel-patron-choisir", time: "7 min" },
          ].map((art, i) => (
            <a key={i} href={`/blog/${art.slug}`} style={{
              background: "#fff", borderRadius: 18, border: "1px solid #EDE8E2", overflow: "hidden",
              textDecoration: "none", display: "block", transition: "transform 0.2s, box-shadow 0.2s",
            }}
            onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-4px)"; e.currentTarget.style.boxShadow = "0 8px 30px rgba(0,0,0,0.08)"; }}
            onMouseLeave={e => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = ""; }}
            >
              <div style={{ height: 100, background: "linear-gradient(135deg, #FFF0ED, #F8E8E4)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 36 }}>{art.emoji}</div>
              <div style={{ padding: 16 }}>
                <span style={{ background: "rgba(184,149,106,0.08)", color: "#B8956A", padding: "2px 10px", borderRadius: 12, fontFamily: "'DM Sans'", fontSize: 10, fontWeight: 600 }}>{art.tag}</span>
                <h3 style={{ fontFamily: "'Playfair Display'", fontSize: 16, color: "#2D2926", marginTop: 8, lineHeight: 1.3 }}>{art.title}</h3>
                <p style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#888", marginTop: 6 }}>{art.desc}</p>
                <span style={{ fontFamily: "'DM Sans'", fontSize: 10, color: "#CCC", marginTop: 8, display: "block" }}>{art.time} de lecture</span>
              </div>
            </a>
          ))}
        </div>
        <div style={{ textAlign: "center", marginTop: 28 }}>
          <a href="/blog" style={{ fontFamily: "'DM Sans'", fontSize: 14, color: "#B8956A", fontWeight: 600, textDecoration: "none" }}>
            Voir tous les articles →
          </a>
        </div>
      </section>

      {/* ── FOOTER ── */}
      <footer style={{ padding: "40px 32px 48px", borderTop: "1px solid #EDE8E2", maxWidth: 1100, margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <Logo size="small" />
          </div>
          <div style={{ display: "flex", gap: 20, alignItems: "center" }}>
            <a href="/blog" style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#AAA", textDecoration: "none" }}>Blog</a>
            <span style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#CCC" }}>© 2026 PatronIA — Le patron sur-mesure par IA</span>
          </div>
        </div>
      </footer>
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// ─── MAIN APP ────────────────────────────────────────
// ═══════════════════════════════════════════════════════
function PatronApp() {
  const [page, setPage] = useState("landing");
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState({});
  const [liked, setLiked] = useState([]);
  const [patronResult, setPatronResult] = useState(null);
  const [paymentStatus, setPaymentStatus] = useState(null); // "success" | "cancelled" | null
  const [fulfillStatus, setFulfillStatus] = useState(null); // "pending" | "done" | "error"

  // Détecter retour Stripe et déclencher le fulfillment
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const sessionId = params.get("session_id");

    if (params.get("payment") === "success" && sessionId) {
      setPaymentStatus("success");
      setPage("payment-result");
      setFulfillStatus("pending");

      // Récupérer les données patron sauvegardées avant le redirect
      let checkoutData = {};
      try { checkoutData = JSON.parse(localStorage.getItem("patronia_checkout") || "{}"); } catch(e) {}

      // Appeler le fulfillment (PDF + email)
      fetch(`${API_URL}/api/fulfill`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          session_id: sessionId,
          patron: checkoutData.patron,
          ia: checkoutData.ia,
          mensurations: checkoutData.mensurations,
          formData: checkoutData.formData,
        }),
      })
        .then(r => r.json())
        .then(result => {
          setFulfillStatus(result.success ? "done" : "error");
          try { localStorage.removeItem("patronia_checkout"); } catch(e) {}
        })
        .catch(() => setFulfillStatus("error"));

      window.history.replaceState({}, "", "/");

    } else if (params.get("payment") === "cancelled") {
      setPaymentStatus("cancelled");
      setPage("payment-result");
      window.history.replaceState({}, "", "/");
    }
  }, []);

  // Page de retour paiement
  if (page === "payment-result") {
    const isSuccess = paymentStatus === "success";
    return (
      <div style={{ minHeight: "100vh", background: "linear-gradient(180deg, #FFFDF9 0%, #FFF8F0 30%, #F8F0E8 100%)", fontFamily: "'DM Sans', sans-serif" }}>
        <style>{FONTS_CSS}</style>
        <div style={{ maxWidth: 540, margin: "0 auto", textAlign: "center", padding: "80px 20px" }}>
          <div style={{
            width: 100, height: 100, borderRadius: "50%", margin: "0 auto 24px",
            background: isSuccess ? "linear-gradient(135deg, #4CAF50, #66BB6A)" : "linear-gradient(135deg, #FF9800, #FFB74D)",
            display: "flex", alignItems: "center", justifyContent: "center",
            boxShadow: isSuccess ? "0 8px 30px rgba(76,175,80,0.3)" : "0 8px 30px rgba(255,152,0,0.3)",
          }}>
            <span style={{ fontSize: 44, filter: "brightness(0) invert(1)" }}>{isSuccess ? "✓" : "↩"}</span>
          </div>
          <h2 style={{ fontFamily: "'Playfair Display'", fontSize: 28, color: "#2D2926", marginBottom: 10 }}>
            {isSuccess ? "Merci pour votre commande !" : "Paiement annulé"}
          </h2>
          <p style={{ fontFamily: "'DM Sans'", fontSize: 15, color: "#888", lineHeight: 1.6, marginBottom: 12 }}>
            {isSuccess
              ? fulfillStatus === "pending"
                ? "Génération de votre patron et envoi par email en cours..."
                : fulfillStatus === "done"
                  ? "✅ Votre patron a été envoyé par email ! Vérifiez votre boîte de réception."
                  : "Votre paiement est confirmé. Votre patron sera envoyé par email sous peu."
              : "Votre paiement a été annulé. Votre patron est toujours sauvegardé — vous pouvez reprendre à tout moment."
            }
          </p>
          {isSuccess && fulfillStatus === "pending" && (
            <div style={{ display: "flex", justifyContent: "center", gap: 6, marginBottom: 16 }}>
              {[0, 0.15, 0.3].map(d => <span key={d} style={{ animation: "bounce 1s infinite", animationDelay: `${d}s`, width: 8, height: 8, borderRadius: "50%", background: "#4CAF50", display: "inline-block" }} />)}
            </div>
          )}
          <style>{`@keyframes bounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-5px); } }`}</style>
          <button onClick={() => { setPage("landing"); setPaymentStatus(null); }} style={{
            background: "linear-gradient(135deg, #1A1A1A, #333)", border: "none", color: "#fff",
            padding: "14px 36px", borderRadius: 50, fontFamily: "'DM Sans'", fontSize: 15, fontWeight: 600,
            cursor: "pointer", boxShadow: "0 4px 20px rgba(26,26,26,0.15)", marginTop: 16,
          }}>{isSuccess ? "Retour à l'accueil" : "Reprendre mon patron"}</button>
        </div>
      </div>
    );
  }

  if (page === "landing") {
    return (
      <div>
        <style>{FONTS_CSS}{`
          @keyframes fadeSlideIn { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: translateY(0); } }
          @keyframes marquee { 0% { transform: translateX(0); } 100% { transform: translateX(-50%); } }
          * { margin: 0; padding: 0; box-sizing: border-box; }
          ::-webkit-scrollbar { width: 4px; }
          ::-webkit-scrollbar-thumb { background: #DDD; border-radius: 4px; }
        `}</style>
        <Landing onStart={() => { setPage("app"); window.scrollTo(0, 0); }} />
      </div>
    );
  }

  return (
    <div style={{ minHeight: "100vh", background: "linear-gradient(180deg, #FFFDF9 0%, #FFF8F0 30%, #F8F0E8 100%)", fontFamily: "'DM Sans', sans-serif" }}>
      <style>{FONTS_CSS}{`
        @keyframes fadeSlideIn { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes bounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-5px); } }
        @keyframes pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.4; transform: scale(1.3); } }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        input::placeholder, textarea::placeholder { color: #CCC; }
        ::-webkit-scrollbar { width: 4px; }
        ::-webkit-scrollbar-thumb { background: #DDD; border-radius: 4px; }
        input[type="range"] { height: 6px; }
      `}</style>

      <header style={{ padding: "18px 28px", display: "flex", alignItems: "center", justifyContent: "space-between", borderBottom: "1px solid rgba(0,0,0,0.05)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }} onClick={() => setPage("landing")}>
          <Logo />
        </div>
        <div style={{ fontFamily: "'DM Sans'", fontSize: 12, color: "#AAA" }}>Créez votre patron sur-mesure</div>
      </header>

      <StepIndicator step={step} onStepClick={setStep} />

      <div style={{ padding: "16px 0 60px", animation: "fadeSlideIn 0.45s ease" }} key={step}>
        {step === 1 && <StepQuestionnaire data={formData} setData={setFormData} onNext={() => setStep(2)} />}
        {step === 2 && <StepInspirations liked={liked} setLiked={setLiked} onNext={() => setStep(3)} />}
        {step === 3 && <StepPatronChat data={formData} liked={liked} patronResult={patronResult} setPatronResult={setPatronResult} onNext={() => setStep(4)} />}
        {step === 4 && <StepFinalize data={formData} patronResult={patronResult} />}
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(React.createElement(PatronApp));
