import { useState, useRef, useEffect } from 'react';

// Pencil Design Colors
const colors = {
  primary: '#213A7E',
  primaryDark: '#152850',
  primaryLight: '#4A6BA8',
  textDark: '#1A1A1A',
  textBody: '#444444',
  textGray: '#666666',
  textLight: '#888888',
  bgLight: '#FAFAFA',
  border: '#E5E5E5',
  white: '#FFFFFF',
  success: '#22C55E',
};

const TOTAL_QUOTA = 8;

// ---------- Config-driven product definitions ----------
type ProductKey = 'maleta' | 'mochila' | 'bolso';

interface Option { id: string; title: string; desc?: string; }
interface Question { key: string; label: string; layout: 'cards' | 'grid'; options: Option[]; }

interface ProductConfig {
  label: string;
  article: string;          // "tu maleta"
  questions: Question[];
  caracteristicas: string[];
  referenceHint: string;
  referenceRecommended: boolean;
}

const COLOR_OPTS = [
  { name: 'Negro',       hex: '#1A1A1A' },
  { name: 'Azul marino', hex: '#213A7E' },
  { name: 'Gris',        hex: '#8A8F98' },
  { name: 'Vino',        hex: '#7B2233' },
  { name: 'Verde',       hex: '#2F5D50' },
  { name: 'Rosa',        hex: '#D98BA6' },
  { name: 'Dorado',      hex: '#C8A24B' },
  { name: 'Plata',       hex: '#C4C7CC' },
];

const PRODUCTS: Record<ProductKey, ProductConfig> = {
  maleta: {
    label: 'Maleta',
    article: 'tu maleta',
    questions: [
      {
        key: 'construccion', label: 'CONSTRUCCIÓN', layout: 'cards',
        options: [
          { id: 'rigida', title: 'Rígida', desc: 'Cáscara dura (PC / ABS). Protección máxima.' },
          { id: 'blanda', title: 'Blanda', desc: 'Tela flexible (nylon / poliéster). Más ligera y expandible.' },
        ],
      },
      {
        key: 'tamano', label: 'TAMAÑO', layout: 'grid',
        options: [
          { id: 'cabina',  title: 'Cabina',  desc: '20" · carry-on' },
          { id: 'mediana', title: 'Mediana', desc: '24" · documentada' },
          { id: 'grande',  title: 'Grande',  desc: '28" · viaje largo' },
          { id: 'set',     title: 'Set',     desc: '3 piezas' },
        ],
      },
    ],
    caracteristicas: ['Candado TSA', 'Expandible', 'Ruedas 360°', 'Puerto USB'],
    referenceHint: '¿Tienes una maleta o estilo que te gusta? Súbela y creamos tu versión.',
    referenceRecommended: false,
  },
  mochila: {
    label: 'Mochila',
    article: 'tu mochila',
    questions: [
      {
        key: 'tipo', label: 'TIPO', layout: 'grid',
        options: [
          { id: 'laptop',  title: 'Laptop',  desc: 'Trabajo / oficina' },
          { id: 'viaje',   title: 'Viaje',   desc: 'Cabina / expandible' },
          { id: 'casual',  title: 'Casual',  desc: 'Diario / urbano' },
          { id: 'outdoor', title: 'Outdoor', desc: 'Senderismo / técnica' },
        ],
      },
      {
        key: 'tamano', label: 'CAPACIDAD', layout: 'grid',
        options: [
          { id: 'peque',  title: 'Pequeña', desc: '15–20 L' },
          { id: 'media',  title: 'Mediana', desc: '25–30 L' },
          { id: 'grande', title: 'Grande',  desc: '35 L+' },
        ],
      },
    ],
    caracteristicas: ['Compartimento laptop', 'Puerto USB', 'Antirrobo', 'Impermeable', 'Correa de trolley'],
    referenceHint: '¿Un modelo que te inspira? Súbelo y adaptamos el estilo a tu marca.',
    referenceRecommended: false,
  },
  bolso: {
    label: 'Bolso',
    article: 'tu bolso',
    questions: [
      {
        key: 'tipo', label: 'ESTILO', layout: 'grid',
        options: [
          { id: 'tote',      title: 'Tote',      desc: 'Amplio / diario' },
          { id: 'crossbody', title: 'Crossbody', desc: 'Bandolera' },
          { id: 'clutch',    title: 'Clutch',    desc: 'De mano / noche' },
          { id: 'weekender', title: 'Weekender', desc: 'Fin de semana' },
        ],
      },
      {
        key: 'material', label: 'MATERIAL', layout: 'grid',
        options: [
          { id: 'nylon',   title: 'Nylon',        desc: 'Ligero / resistente' },
          { id: 'lona',    title: 'Lona',         desc: 'Casual / natural' },
          { id: 'piel',    title: 'Piel sint.',   desc: 'Elegante / premium' },
          { id: 'poli',    title: 'Poliéster',    desc: 'Económico / versátil' },
        ],
      },
    ],
    caracteristicas: ['Cierre magnético', 'Correa ajustable', 'Herrajes dorados'],
    referenceHint: 'Recomendado: sube una referencia del bolso que te gusta — el estilo de bolso es muy variado.',
    referenceRecommended: true,
  },
};

// ---------- Product silhouettes ----------
function Silhouette({ product, hex }: { product: ProductKey; hex: string }) {
  const common = { fill: hex };
  if (product === 'mochila') {
    return (
      <svg viewBox="0 0 200 240" width="100%" height="100%" style={{ maxHeight: 300 }}>
        <path d="M60 40 Q100 8 140 40 L140 60 L60 60 Z" fill={hex} opacity="0.9" />
        <rect x="46" y="56" width="108" height="160" rx="34" {...common} />
        <rect x="46" y="56" width="108" height="160" rx="34" fill="url(#sh)" />
        <rect x="70" y="96" width="60" height="70" rx="14" fill="none" stroke="#fff" strokeWidth="2" opacity="0.25" />
        <path d="M64 60 Q56 130 74 200" fill="none" stroke="#00000030" strokeWidth="4" />
        <path d="M136 60 Q144 130 126 200" fill="none" stroke="#00000030" strokeWidth="4" />
        <defs><linearGradient id="sh" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stopColor="#fff" stopOpacity="0.22" /><stop offset="45%" stopColor="#fff" stopOpacity="0" /></linearGradient></defs>
      </svg>
    );
  }
  if (product === 'bolso') {
    return (
      <svg viewBox="0 0 200 240" width="100%" height="100%" style={{ maxHeight: 300 }}>
        <path d="M64 70 Q100 20 136 70" fill="none" stroke={hex} strokeWidth="8" opacity="0.85" />
        <path d="M46 78 L154 78 L142 200 Q140 212 126 212 L74 212 Q60 212 58 200 Z" {...common} />
        <path d="M46 78 L154 78 L142 200 Q140 212 126 212 L74 212 Q60 212 58 200 Z" fill="url(#sh2)" />
        <line x1="100" y1="86" x2="100" y2="204" stroke="#fff" strokeWidth="2" opacity="0.16" />
        <defs><linearGradient id="sh2" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stopColor="#fff" stopOpacity="0.22" /><stop offset="45%" stopColor="#fff" stopOpacity="0" /></linearGradient></defs>
      </svg>
    );
  }
  // maleta (default)
  return (
    <svg viewBox="0 0 200 240" width="100%" height="100%" style={{ maxHeight: 300 }}>
      <rect x="80" y="14" width="40" height="34" rx="8" fill="none" stroke={hex} strokeWidth="7" opacity="0.85" />
      <rect x="34" y="46" width="132" height="168" rx="20" {...common} />
      <rect x="34" y="46" width="132" height="168" rx="20" fill="url(#sh3)" />
      <line x1="70" y1="52" x2="70" y2="208" stroke="#fff" strokeWidth="2" opacity="0.18" />
      <line x1="100" y1="52" x2="100" y2="208" stroke="#fff" strokeWidth="2" opacity="0.18" />
      <line x1="130" y1="52" x2="130" y2="208" stroke="#fff" strokeWidth="2" opacity="0.18" />
      <circle cx="56" cy="222" r="9" {...common} stroke="#00000030" strokeWidth="2" />
      <circle cx="144" cy="222" r="9" {...common} stroke="#00000030" strokeWidth="2" />
      <defs><linearGradient id="sh3" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stopColor="#fff" stopOpacity="0.22" /><stop offset="45%" stopColor="#fff" stopOpacity="0" /></linearGradient></defs>
    </svg>
  );
}

interface Prefill { nombre?: string; empresa?: string; email?: string; whatsapp?: string; }
interface Props { product?: ProductKey; prefill?: Prefill; }

interface ColorState { name: string; hex: string; }

export default function ProductCreator({ product: initialProduct, prefill }: Props) {
  const [product, setProduct] = useState<ProductKey | null>(initialProduct ?? null);
  const [step, setStep] = useState(1);
  const [selections, setSelections] = useState<Record<string, string>>({});
  const [color, setColor] = useState<ColorState>(COLOR_OPTS[1]);
  const [caracteristicas, setCaracteristicas] = useState<string[]>([]);
  const [superficie, setSuperficie] = useState<string | null>(null);
  const [disenoTexto, setDisenoTexto] = useState('');
  const [refImg, setRefImg] = useState<string | null>(null);
  const [logoImg, setLogoImg] = useState<string | null>(null);

  const [generating, setGenerating] = useState(false);
  const [generated, setGenerated] = useState(false);
  const [used, setUsed] = useState(0);

  // Color picker modes
  const [eyedropOpen, setEyedropOpen] = useState(false);
  const [eyedropImg, setEyedropImg] = useState<string | null>(null);

  // Quote modal
  const [showQuote, setShowQuote] = useState(false);
  const [quoteSent, setQuoteSent] = useState(false);
  const [form, setForm] = useState({
    nombre: prefill?.nombre ?? '',
    empresa: prefill?.empresa ?? '',
    email: prefill?.email ?? '',
    whatsapp: prefill?.whatsapp ?? '',
    mensaje: '',
  });

  const refInput = useRef<HTMLInputElement>(null);
  const logoInput = useRef<HTMLInputElement>(null);
  const eyedropInput = useRef<HTMLInputElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  // Restore config from URL (design link) after mount — lets sales reopen a design
  useEffect(() => {
    if (typeof window === 'undefined') return;
    const p = new URLSearchParams(window.location.search);
    const prod = p.get('producto') as ProductKey | null;
    if (prod && PRODUCTS[prod]) {
      setProduct(prod);
      const restored: Record<string, string> = {};
      PRODUCTS[prod].questions.forEach((q) => {
        const v = p.get(q.key);
        if (v) restored[q.key] = v;
      });
      if (Object.keys(restored).length) setSelections(restored);
      const hex = p.get('color');
      if (hex) setColor({ name: 'Personalizado', hex });
      const extras = p.get('extras');
      if (extras) setCaracteristicas(extras.split(',').filter(Boolean));
      const sup = p.get('superficie');
      if (sup) setSuperficie(sup);
      const dis = p.get('diseno');
      if (dis) setDisenoTexto(dis);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const cfg = product ? PRODUCTS[product] : null;
  const stepLabels = ['Detalles', 'Color', 'Personalización', 'Resultado'];
  const remaining = TOTAL_QUOTA - used;

  // Surface-design chips — "Relieve" only makes sense on hard-shell luggage (in-mold)
  const surfaceChips = ['Liso', 'Rayas', 'Degradado', 'Estampado'];
  if (product === 'maleta' && selections.construccion === 'rigida') {
    surfaceChips.splice(3, 0, 'Relieve');
  }

  const pickProduct = (p: ProductKey) => {
    setProduct(p);
    setSelections({});
    setStep(1);
    setGenerated(false);
  };

  const select = (qKey: string, optId: string) =>
    setSelections((prev) => ({ ...prev, [qKey]: optId }));

  const toggleCaracteristica = (c: string) =>
    setCaracteristicas((prev) => (prev.includes(c) ? prev.filter((x) => x !== c) : [...prev, c]));

  const readFile = (file: File, setter: (v: string) => void) => {
    const reader = new FileReader();
    reader.onload = () => setter(reader.result as string);
    reader.readAsDataURL(file);
  };

  const canContinue = () => {
    if (!cfg) return false;
    if (step === 1) return cfg.questions.every((q) => selections[q.key]);
    return true;
  };

  const goGenerate = () => {
    setGenerating(true);
    setGenerated(false);
    // MOCK — real model call goes here later
    setTimeout(() => {
      setGenerating(false);
      setGenerated(true);
      setUsed((u) => Math.min(TOTAL_QUOTA, u + 1));
    }, 2600);
  };

  const optTitle = (qKey: string) => {
    if (!cfg) return '—';
    const q = cfg.questions.find((x) => x.key === qKey);
    const o = q?.options.find((x) => x.id === selections[qKey]);
    return o?.title ?? '—';
  };

  // ---- Eyedropper: pick color from an uploaded image ----
  const loadEyedropImage = (file: File) => {
    const reader = new FileReader();
    reader.onload = () => {
      const src = reader.result as string;
      setEyedropImg(src);
      const img = new Image();
      img.onload = () => {
        const canvas = canvasRef.current;
        if (!canvas) return;
        const maxW = 460;
        const scale = Math.min(1, maxW / img.width);
        canvas.width = Math.round(img.width * scale);
        canvas.height = Math.round(img.height * scale);
        const ctx = canvas.getContext('2d');
        ctx?.drawImage(img, 0, 0, canvas.width, canvas.height);
      };
      img.src = src;
    };
    reader.readAsDataURL(file);
  };

  const pickColorFromCanvas = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const rect = canvas.getBoundingClientRect();
    const x = Math.round((e.clientX - rect.left) * (canvas.width / rect.width));
    const y = Math.round((e.clientY - rect.top) * (canvas.height / rect.height));
    const ctx = canvas.getContext('2d');
    const d = ctx?.getImageData(x, y, 1, 1).data;
    if (!d) return;
    const hex = '#' + [d[0], d[1], d[2]].map((v) => v.toString(16).padStart(2, '0')).join('');
    setColor({ name: 'De imagen', hex });
  };

  // ---- Design link: encode config so it can be reopened ----
  const buildDesignLink = () => {
    if (typeof window === 'undefined' || !product) return '';
    const p = new URLSearchParams();
    p.set('producto', product);
    Object.entries(selections).forEach(([k, v]) => p.set(k, v));
    p.set('color', color.hex);
    if (caracteristicas.length) p.set('extras', caracteristicas.join(','));
    if (superficie) p.set('superficie', superficie);
    if (disenoTexto.trim()) p.set('diseno', disenoTexto.trim());
    return `${window.location.origin}/es/crea-tu-producto?${p.toString()}`;
  };

  const submitQuote = () => {
    // MOCK — later POSTs to lead endpoint with design context + token identity
    setQuoteSent(true);
  };

  // ---------- PRODUCT PICKER ----------
  if (!product || !cfg) {
    return (
      <div className="lc-root">
        <style>{css}</style>
        <div className="lc-picker">
          <div className="lc-picker-grid">
            {(Object.keys(PRODUCTS) as ProductKey[]).map((p) => (
              <button key={p} className="lc-picker-card" onClick={() => pickProduct(p)}>
                <div className="lc-picker-art"><Silhouette product={p} hex={colors.primary} /></div>
                <span className="lc-card-title">{PRODUCTS[p].label}</span>
                <span className="lc-picker-cta">Crear →</span>
              </button>
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="lc-root">
      <style>{css}</style>

      {/* Progress */}
      <div className="lc-progress">
        {stepLabels.map((label, i) => {
          const n = i + 1;
          const active = n === step;
          const done = n < step;
          return (
            <div key={label} className="lc-progress-item">
              <div className={`lc-dot ${active ? 'active' : ''} ${done ? 'done' : ''}`}>{done ? '✓' : n}</div>
              <span className={`lc-progress-label ${active ? 'active' : ''}`}>{label}</span>
              {n < 4 && <div className={`lc-progress-line ${done ? 'done' : ''}`} />}
            </div>
          );
        })}
      </div>

      <div className="lc-body">
        <div className="lc-panel">
          {/* STEP 1 — dynamic category questions */}
          {step === 1 && (
            <div className="lc-step">
              <h2 className="lc-h2">Diseña {cfg.article}</h2>
              <p className="lc-sub">Elige las características principales. Podrás afinar color y marca después.</p>

              {cfg.questions.map((q, qi) => (
                <div key={q.key} style={{ marginTop: qi === 0 ? 0 : 28 }}>
                  <span className="lc-label">{q.label}</span>
                  <div className={q.layout === 'cards' ? 'lc-cards-2' : 'lc-cards-grid'}>
                    {q.options.map((o) => (
                      <button
                        key={o.id}
                        className={`lc-card ${q.layout === 'grid' ? 'sm' : ''} ${selections[q.key] === o.id ? 'selected' : ''}`}
                        onClick={() => select(q.key, o.id)}
                      >
                        <span className="lc-card-title">{o.title}</span>
                        {o.desc && <span className="lc-card-desc">{o.desc}</span>}
                      </button>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* STEP 2 — color + features */}
          {step === 2 && (
            <div className="lc-step">
              <h2 className="lc-h2">Elige el color base</h2>
              <p className="lc-sub">Es el punto de partida — el color exacto y acabado se afina en producción.</p>
              <span className="lc-label">COLOR</span>
              <div className="lc-swatches">
                {COLOR_OPTS.map((c) => (
                  <button key={c.name} className={`lc-swatch ${color.name === c.name && color.hex === c.hex ? 'selected' : ''}`} onClick={() => setColor(c)} title={c.name}>
                    <span className="lc-swatch-dot" style={{ background: c.hex }} />
                    <span className="lc-swatch-name">{c.name}</span>
                  </button>
                ))}
              </div>

              {/* Custom color + eyedropper */}
              <div className="lc-color-tools">
                <label className="lc-color-custom">
                  <input
                    type="color"
                    value={color.hex}
                    onChange={(e) => setColor({ name: 'Personalizado', hex: e.target.value })}
                  />
                  <span className="lc-color-swatch" style={{ background: color.hex }} />
                  <span className="lc-color-info">
                    <strong>Color a medida</strong>
                    <span>{color.hex.toUpperCase()}{color.name === 'Personalizado' || color.name === 'De imagen' ? ` · ${color.name}` : ''}</span>
                  </span>
                </label>
                <button
                  className={`lc-color-eyedrop ${eyedropOpen ? 'active' : ''}`}
                  onClick={() => { setEyedropOpen((v) => !v); if (!eyedropImg) eyedropInput.current?.click(); }}
                >
                  <EyedropIcon /> Tomar color de una imagen
                </button>
                <input ref={eyedropInput} type="file" accept="image/*" hidden onChange={(e) => { if (e.target.files?.[0]) { setEyedropOpen(true); loadEyedropImage(e.target.files[0]); } }} />
              </div>

              {eyedropOpen && eyedropImg && (
                <div className="lc-eyedrop-panel">
                  <p className="lc-upload-hint">Toca cualquier punto de la imagen para tomar ese color.</p>
                  <canvas ref={canvasRef} className="lc-eyedrop-canvas" onClick={pickColorFromCanvas} />
                  <div className="lc-eyedrop-actions">
                    <span className="lc-eyedrop-preview"><span style={{ background: color.hex }} /> {color.hex.toUpperCase()}</span>
                    <button className="lc-remove" onClick={() => eyedropInput.current?.click()}>Cambiar imagen</button>
                  </div>
                </div>
              )}

              <span className="lc-label" style={{ marginTop: 28 }}>CARACTERÍSTICAS <span className="lc-optional">(opcional)</span></span>
              <div className="lc-chips">
                {cfg.caracteristicas.map((c) => (
                  <button key={c} className={`lc-chip ${caracteristicas.includes(c) ? 'selected' : ''}`} onClick={() => toggleCaracteristica(c)}>
                    {caracteristicas.includes(c) ? '✓ ' : '+ '}{c}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* STEP 3 — personalization */}
          {step === 3 && (
            <div className="lc-step">
              <h2 className="lc-h2">Personalización <span className="lc-optional">(opcional)</span></h2>
              <p className="lc-sub">Describe el diseño que imaginas, sube una referencia y/o tu logo. Todo ayuda a acercar el resultado a lo que buscas.</p>

              {/* Surface design — technique (chip) + content (text) work together */}
              <span className="lc-label">ACABADO <span className="lc-optional">cómo se aplica</span></span>
              <div className="lc-chips" style={{ marginBottom: 22 }}>
                {surfaceChips.map((s) => (
                  <button
                    key={s}
                    className={`lc-chip ${superficie === s ? 'selected' : ''}`}
                    onClick={() => setSuperficie(superficie === s ? null : s)}
                  >
                    {superficie === s ? '✓ ' : ''}{s}
                  </button>
                ))}
              </div>

              <span className="lc-label">DESCRIBE TU DISEÑO <span className="lc-optional">qué quieres ver</span></span>
              <textarea
                className="lc-input lc-textarea"
                placeholder="ej. estrellas de 5 puntas, un panda al frente, hojas tropicales, las iniciales de mi marca…"
                value={disenoTexto}
                onChange={(e) => setDisenoTexto(e.target.value)}
              />
              <span className="lc-hint-line">
                Combínalos: p. ej. <strong>Relieve</strong> + “estrellas de 5 puntas”, o <strong>Estampado</strong> + “un panda al frente”.
              </span>
              <div style={{ marginBottom: 32 }} />

              <div className="lc-uploads">
                <div className="lc-upload">
                  <span className="lc-label">IMAGEN DE REFERENCIA {cfg.referenceRecommended && <span className="lc-reco">recomendado</span>}</span>
                  <p className="lc-upload-hint">{cfg.referenceHint}</p>
                  <div className={`lc-dropzone ${refImg ? 'has-img' : ''}`} onClick={() => refInput.current?.click()}>
                    {refImg ? <img src={refImg} alt="Referencia" className="lc-drop-img" /> : (<><UploadIcon /><span>Subir referencia</span></>)}
                  </div>
                  {refImg && <button className="lc-remove" onClick={() => setRefImg(null)}>Quitar</button>}
                  <input ref={refInput} type="file" accept="image/*" hidden onChange={(e) => e.target.files?.[0] && readFile(e.target.files[0], setRefImg)} />
                </div>

                <div className="lc-upload">
                  <span className="lc-label">TU LOGO</span>
                  <p className="lc-upload-hint">Lo colocamos en el producto para que veas tu marca aplicada.</p>
                  <div className={`lc-dropzone ${logoImg ? 'has-img' : ''}`} onClick={() => logoInput.current?.click()}>
                    {logoImg ? <img src={logoImg} alt="Logo" className="lc-drop-img contain" /> : (<><UploadIcon /><span>Subir logo</span></>)}
                  </div>
                  {logoImg && <button className="lc-remove" onClick={() => setLogoImg(null)}>Quitar</button>}
                  <input ref={logoInput} type="file" accept="image/*" hidden onChange={(e) => e.target.files?.[0] && readFile(e.target.files[0], setLogoImg)} />
                </div>
              </div>
            </div>
          )}

          {/* STEP 4 — result */}
          {step === 4 && (
            <div className="lc-step lc-result-step">
              {!generated && !generating && (
                <>
                  <h2 className="lc-h2">Todo listo para crear {cfg.article}</h2>
                  <p className="lc-sub">Revisa el resumen a la derecha. Cuando quieras, generamos tu diseño.</p>
                  <button className="lc-generate-btn" onClick={goGenerate}>✨ Generar {cfg.article}</button>
                  <span className="lc-quota">Te quedan <strong>{remaining}</strong> de {TOTAL_QUOTA} diseños</span>
                </>
              )}
              {generating && (
                <div className="lc-loading">
                  <div className="lc-spinner" />
                  <h2 className="lc-h2">Diseñando {cfg.article}…</h2>
                  <p className="lc-sub">Nuestro diseñador de IA está creando tu concepto. Esto toma unos segundos.</p>
                </div>
              )}
              {generated && (
                <div className="lc-generated">
                  <div className="lc-result-frame">
                    <Silhouette product={product} hex={color.hex} />
                    {logoImg && <img src={logoImg} alt="logo" className="lc-result-logo" />}
                    <span className="lc-mock-badge">PREVIEW (mock)</span>
                  </div>
                  <div className="lc-result-actions">
                    <button className="lc-btn-secondary" onClick={goGenerate} disabled={remaining <= 0}>
                      ↻ Regenerar {remaining > 0 && `(${remaining} restantes)`}
                    </button>
                    <button className="lc-btn-primary" onClick={() => { setQuoteSent(false); setShowQuote(true); }}>
                      Solicitar cotización de este diseño
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Summary */}
        <aside className="lc-summary">
          <span className="lc-label">TU {cfg.label.toUpperCase()}</span>
          <div className="lc-summary-preview"><Silhouette product={product} hex={color.hex} /></div>
          <ul className="lc-summary-list">
            {cfg.questions.map((q) => (
              <li key={q.key}><span>{q.label.charAt(0) + q.label.slice(1).toLowerCase()}</span><strong>{optTitle(q.key)}</strong></li>
            ))}
            <li><span>Color</span><strong>{color.name}</strong></li>
            <li><span>Diseño</span><strong>{superficie || (disenoTexto.trim() ? 'A medida' : '—')}</strong></li>
            <li><span>Extras</span><strong>{caracteristicas.length || '—'}</strong></li>
            <li><span>Referencia</span><strong>{refImg ? 'Sí' : '—'}</strong></li>
            <li><span>Logo</span><strong>{logoImg ? 'Sí' : '—'}</strong></li>
          </ul>
          {!initialProduct && (
            <button className="lc-change" onClick={() => setProduct(null)}>Cambiar producto</button>
          )}
        </aside>
      </div>

      {/* Nav */}
      {step < 4 && (
        <div className="lc-nav">
          {step > 1 ? <button className="lc-btn-back" onClick={() => setStep((s) => s - 1)}>← Atrás</button> : <span />}
          <button className="lc-btn-next" disabled={!canContinue()} onClick={() => setStep((s) => s + 1)}>Continuar →</button>
        </div>
      )}
      {step === 4 && !generating && (
        <div className="lc-nav">
          <button className="lc-btn-back" onClick={() => { setStep((s) => s - 1); setGenerated(false); }}>← Atrás</button>
          <span />
        </div>
      )}

      {/* ---- Quote modal ---- */}
      {showQuote && (
        <div className="lc-modal-overlay" onClick={() => setShowQuote(false)}>
          <div className="lc-modal" onClick={(e) => e.stopPropagation()}>
            <button className="lc-modal-close" onClick={() => setShowQuote(false)} aria-label="Cerrar">✕</button>

            {!quoteSent ? (
              <>
                <h3 className="lc-modal-title">Solicita tu cotización</h3>
                <p className="lc-modal-sub">Un ejecutivo revisará tu diseño y te contactará con precios reales.</p>

                {/* Design summary */}
                <div className="lc-modal-design">
                  <div className="lc-modal-thumb"><Silhouette product={product} hex={color.hex} /></div>
                  <div className="lc-modal-specs">
                    <span className="lc-modal-prod">{cfg.label}</span>
                    <span className="lc-modal-detail">
                      {cfg.questions.map((q) => optTitle(q.key)).join(' · ')} · {color.name}
                      {superficie ? ` · ${superficie}` : ''}
                      {caracteristicas.length ? ` · ${caracteristicas.length} extras` : ''}
                      {disenoTexto.trim() ? ` · "${disenoTexto.trim().slice(0, 40)}${disenoTexto.trim().length > 40 ? '…' : ''}"` : ''}
                    </span>
                  </div>
                </div>

                <div className="lc-form">
                  <div className="lc-form-row">
                    <input className="lc-input" placeholder="Nombre *" value={form.nombre} onChange={(e) => setForm({ ...form, nombre: e.target.value })} />
                    <input className="lc-input" placeholder="Empresa *" value={form.empresa} onChange={(e) => setForm({ ...form, empresa: e.target.value })} />
                  </div>
                  <div className="lc-form-row">
                    <input className="lc-input" type="email" placeholder="Email *" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
                    <input className="lc-input" placeholder="WhatsApp" value={form.whatsapp} onChange={(e) => setForm({ ...form, whatsapp: e.target.value })} />
                  </div>
                  <textarea className="lc-input lc-textarea" placeholder="¿Algo más que debamos saber? (cantidad, fechas, etc.)" value={form.mensaje} onChange={(e) => setForm({ ...form, mensaje: e.target.value })} />
                </div>

                <button className="lc-btn-primary lc-modal-submit" disabled={!form.nombre || !form.email || !form.empresa} onClick={submitQuote}>
                  Enviar solicitud
                </button>
                <span className="lc-modal-note">Tu diseño se adjunta automáticamente para que podamos retomarlo.</span>
              </>
            ) : (
              <div className="lc-modal-success">
                <div className="lc-success-check">✓</div>
                <h3 className="lc-modal-title">¡Solicitud enviada!</h3>
                <p className="lc-modal-sub">Gracias{form.nombre ? `, ${form.nombre}` : ''}. Un ejecutivo te contactará en menos de 24 horas con tu cotización.</p>
                <a href={buildDesignLink()} target="_blank" rel="noopener noreferrer" className="lc-design-link">↗ Ver tu diseño guardado</a>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function EyedropIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="m2 22 1-1h3l9-9" /><path d="M3 21v-3l9-9" />
      <path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z" />
    </svg>
  );
}

function UploadIcon() {
  return (
    <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
      <polyline points="17 8 12 3 7 8" />
      <line x1="12" y1="3" x2="12" y2="15" />
    </svg>
  );
}

const css = `
.lc-root { font-family: 'Inter', sans-serif; max-width: 1080px; margin: 0 auto; padding: 8px 0 40px; }

/* Picker */
.lc-picker { padding: 20px 0 10px; }
.lc-picker-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-top: 12px; }
.lc-picker-card {
  display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 28px 20px;
  background: ${colors.white}; border: 1.5px solid ${colors.border}; border-radius: 16px; cursor: pointer; transition: all .18s;
}
.lc-picker-card:hover { border-color: ${colors.primary}; transform: translateY(-4px); box-shadow: 0 12px 28px rgba(0,0,0,.08); }
.lc-picker-art { height: 150px; display: flex; align-items: center; }
.lc-picker-cta { font-size: 13px; color: ${colors.primary}; font-weight: 600; }

/* Progress */
.lc-progress { display: flex; align-items: center; justify-content: center; margin-bottom: 40px; flex-wrap: wrap; }
.lc-progress-item { display: flex; align-items: center; }
.lc-dot { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 13px; font-weight: 600; background: #EEF0F4; color: #999; flex-shrink: 0; transition: all .2s; }
.lc-dot.active { background: ${colors.primary}; color: #fff; }
.lc-dot.done { background: ${colors.success}; color: #fff; }
.lc-progress-label { font-size: 13px; color: #999; margin: 0 10px 0 8px; white-space: nowrap; }
.lc-progress-label.active { color: ${colors.primary}; font-weight: 600; }
.lc-progress-line { width: 36px; height: 2px; background: #E5E5E5; margin-right: 10px; }
.lc-progress-line.done { background: ${colors.success}; }

/* Body */
.lc-body { display: flex; gap: 32px; align-items: flex-start; }
.lc-panel { flex: 1; min-width: 0; }
.lc-step { animation: lcFade .25s ease; }
@keyframes lcFade { from { opacity: 0; transform: translateY(6px);} to {opacity:1; transform:none;} }

.lc-h2 { font-family: 'Newsreader', serif; font-size: 30px; font-weight: 500; color: ${colors.textDark}; margin: 0 0 8px; }
.lc-sub { font-size: 15px; color: ${colors.textGray}; margin: 0 0 28px; line-height: 1.6; }
.lc-label { display: block; font-family: 'JetBrains Mono', monospace; font-size: 11px; font-weight: 600; letter-spacing: 1px; color: ${colors.textLight}; margin-bottom: 14px; }
.lc-optional { color: ${colors.textLight}; font-weight: 400; font-size: 12px; letter-spacing: 0; text-transform: none; }
.lc-reco { display: inline-block; background: ${colors.primary}12; color: ${colors.primary}; font-size: 10px; padding: 2px 7px; border-radius: 4px; margin-left: 6px; letter-spacing: 0; }

/* Cards */
.lc-cards-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
.lc-cards-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
.lc-card { display: flex; flex-direction: column; gap: 8px; text-align: left; padding: 20px; background: ${colors.white}; border: 1.5px solid ${colors.border}; border-radius: 12px; cursor: pointer; transition: all .18s; }
.lc-card.sm { padding: 16px; gap: 4px; }
.lc-card:hover { border-color: ${colors.primaryLight}; transform: translateY(-2px); }
.lc-card.selected { border-color: ${colors.primary}; background: ${colors.primary}08; box-shadow: 0 0 0 3px ${colors.primary}15; }
.lc-card-title { font-family: 'Newsreader', serif; font-size: 18px; font-weight: 500; color: ${colors.textDark}; }
.lc-card.sm .lc-card-title { font-size: 16px; }
.lc-card-desc { font-size: 13px; color: ${colors.textGray}; line-height: 1.5; }

/* Swatches */
.lc-swatches { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
.lc-swatch { display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 14px 8px; background: ${colors.white}; border: 1.5px solid ${colors.border}; border-radius: 12px; cursor: pointer; transition: all .18s; }
.lc-swatch:hover { border-color: ${colors.primaryLight}; }
.lc-swatch.selected { border-color: ${colors.primary}; box-shadow: 0 0 0 3px ${colors.primary}15; }
.lc-swatch-dot { width: 40px; height: 40px; border-radius: 50%; border: 1px solid #00000015; }
.lc-swatch-name { font-size: 12px; color: ${colors.textBody}; }

/* Chips */
.lc-chips { display: flex; flex-wrap: wrap; gap: 10px; }
.lc-chip { font-size: 13px; padding: 9px 16px; border-radius: 100px; cursor: pointer; transition: all .15s; background: ${colors.white}; border: 1.5px solid ${colors.border}; color: ${colors.textBody}; }
.lc-chip:hover { border-color: ${colors.primaryLight}; }
.lc-chip.selected { background: ${colors.primary}; border-color: ${colors.primary}; color: #fff; }

/* Uploads */
.lc-uploads { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
.lc-upload { display: flex; flex-direction: column; }
.lc-upload-hint { font-size: 13px; color: ${colors.textGray}; margin: -6px 0 14px; line-height: 1.5; }
.lc-dropzone { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; height: 200px; border: 2px dashed ${colors.border}; border-radius: 12px; cursor: pointer; color: ${colors.textLight}; font-size: 14px; transition: all .18s; background: ${colors.bgLight}; overflow: hidden; }
.lc-dropzone:hover { border-color: ${colors.primary}; color: ${colors.primary}; background: ${colors.primary}05; }
.lc-dropzone.has-img { border-style: solid; padding: 0; }
.lc-drop-img { width: 100%; height: 100%; object-fit: cover; }
.lc-drop-img.contain { object-fit: contain; padding: 16px; background: #fff; }
.lc-remove { align-self: center; margin-top: 10px; background: none; border: none; color: ${colors.textGray}; font-size: 12px; cursor: pointer; text-decoration: underline; }

/* Summary */
.lc-summary { width: 280px; flex-shrink: 0; background: ${colors.bgLight}; border: 1px solid ${colors.border}; border-radius: 16px; padding: 24px; position: sticky; top: 96px; }
.lc-summary-preview { background: ${colors.white}; border-radius: 12px; padding: 20px; margin-bottom: 20px; display: flex; justify-content: center; }
.lc-summary-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 12px; }
.lc-summary-list li { display: flex; justify-content: space-between; align-items: center; font-size: 14px; }
.lc-summary-list li span { color: ${colors.textGray}; }
.lc-summary-list li strong { color: ${colors.textDark}; font-weight: 600; }
.lc-change { margin-top: 20px; width: 100%; background: none; border: 1px solid ${colors.border}; color: ${colors.textGray}; padding: 10px; border-radius: 8px; font-size: 13px; cursor: pointer; }
.lc-change:hover { border-color: ${colors.primary}; color: ${colors.primary}; }

/* Nav */
.lc-nav { display: flex; justify-content: space-between; align-items: center; margin-top: 32px; }
.lc-btn-back { background: none; border: none; color: ${colors.textGray}; font-size: 15px; font-weight: 500; cursor: pointer; padding: 12px 8px; }
.lc-btn-back:hover { color: ${colors.textDark}; }
.lc-btn-next { background: ${colors.primary}; color: #fff; border: none; padding: 14px 32px; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer; transition: opacity .2s; }
.lc-btn-next:hover { opacity: .9; }
.lc-btn-next:disabled { background: ${colors.border}; color: ${colors.textLight}; cursor: not-allowed; }

/* Result */
.lc-result-step { text-align: center; display: flex; flex-direction: column; align-items: center; }
.lc-generate-btn { background: ${colors.primary}; color: #fff; border: none; padding: 18px 40px; border-radius: 10px; font-size: 17px; font-weight: 600; cursor: pointer; margin: 12px 0 16px; transition: transform .15s, opacity .2s; }
.lc-generate-btn:hover { opacity: .92; transform: translateY(-2px); }
.lc-quota { font-size: 13px; color: ${colors.textGray}; }
.lc-quota strong { color: ${colors.primary}; }
.lc-loading { display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 30px 0; }
.lc-spinner { width: 52px; height: 52px; border: 4px solid ${colors.primary}20; border-top-color: ${colors.primary}; border-radius: 50%; animation: lcSpin .8s linear infinite; margin-bottom: 20px; }
@keyframes lcSpin { to { transform: rotate(360deg); } }
.lc-generated { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 24px; }
.lc-result-frame { position: relative; width: 100%; max-width: 420px; background: ${colors.bgLight}; border: 1px solid ${colors.border}; border-radius: 16px; padding: 32px; display: flex; justify-content: center; }
.lc-result-logo { position: absolute; bottom: 30%; left: 50%; transform: translateX(-50%); max-width: 60px; max-height: 40px; object-fit: contain; }
.lc-mock-badge { position: absolute; top: 12px; right: 12px; font-family: 'JetBrains Mono', monospace; font-size: 10px; letter-spacing: 1px; background: ${colors.textDark}; color: #fff; padding: 4px 8px; border-radius: 4px; opacity: .8; }
.lc-result-actions { display: flex; gap: 14px; flex-wrap: wrap; justify-content: center; }
.lc-btn-secondary { background: ${colors.white}; color: ${colors.primary}; border: 1.5px solid ${colors.primary}; padding: 13px 24px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; transition: all .2s; }
.lc-btn-secondary:hover { background: ${colors.primary}08; }
.lc-btn-secondary:disabled { color: ${colors.textLight}; border-color: ${colors.border}; cursor: not-allowed; }
.lc-btn-primary { background: ${colors.primary}; color: #fff; padding: 13px 24px; border-radius: 8px; font-size: 14px; font-weight: 600; text-decoration: none; display: inline-flex; align-items: center; transition: opacity .2s; }
.lc-btn-primary:hover { opacity: .9; }

/* Color tools */
.lc-color-tools { display: flex; gap: 12px; margin-top: 16px; flex-wrap: wrap; }
.lc-color-custom { display: flex; align-items: center; gap: 12px; padding: 10px 16px; border: 1.5px solid ${colors.border}; border-radius: 10px; cursor: pointer; background: ${colors.white}; }
.lc-color-custom:hover { border-color: ${colors.primaryLight}; }
.lc-color-custom input[type=color] { position: absolute; width: 0; height: 0; opacity: 0; padding: 0; border: 0; }
.lc-color-swatch { width: 32px; height: 32px; border-radius: 8px; border: 1px solid #00000015; flex-shrink: 0; }
.lc-color-info { display: flex; flex-direction: column; }
.lc-color-info strong { font-size: 13px; color: ${colors.textDark}; }
.lc-color-info span { font-family: 'JetBrains Mono', monospace; font-size: 11px; color: ${colors.textGray}; }
.lc-color-eyedrop { display: inline-flex; align-items: center; gap: 8px; padding: 10px 16px; border: 1.5px solid ${colors.border}; border-radius: 10px; background: ${colors.white}; color: ${colors.textBody}; font-size: 13px; cursor: pointer; transition: all .18s; }
.lc-color-eyedrop:hover, .lc-color-eyedrop.active { border-color: ${colors.primary}; color: ${colors.primary}; }

/* Eyedropper panel */
.lc-eyedrop-panel { margin-top: 16px; padding: 16px; background: ${colors.bgLight}; border: 1px solid ${colors.border}; border-radius: 12px; }
.lc-eyedrop-canvas { max-width: 100%; border-radius: 8px; cursor: crosshair; display: block; }
.lc-eyedrop-actions { display: flex; align-items: center; justify-content: space-between; margin-top: 12px; }
.lc-eyedrop-preview { display: inline-flex; align-items: center; gap: 8px; font-family: 'JetBrains Mono', monospace; font-size: 12px; color: ${colors.textBody}; }
.lc-eyedrop-preview span { width: 22px; height: 22px; border-radius: 6px; border: 1px solid #00000020; }

/* Quote modal */
.lc-modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,.5); z-index: 1000; display: flex; align-items: center; justify-content: center; padding: 20px; animation: lcFade .2s ease; }
.lc-modal { position: relative; background: ${colors.white}; border-radius: 18px; padding: 36px; width: 100%; max-width: 520px; max-height: 90vh; overflow-y: auto; box-shadow: 0 24px 60px rgba(0,0,0,.25); }
.lc-modal-close { position: absolute; top: 18px; right: 18px; background: none; border: none; font-size: 18px; color: ${colors.textGray}; cursor: pointer; line-height: 1; }
.lc-modal-title { font-family: 'Newsreader', serif; font-size: 26px; font-weight: 500; color: ${colors.textDark}; margin: 0 0 6px; }
.lc-modal-sub { font-size: 14px; color: ${colors.textGray}; margin: 0 0 22px; line-height: 1.5; }
.lc-modal-design { display: flex; align-items: center; gap: 16px; background: ${colors.bgLight}; border: 1px solid ${colors.border}; border-radius: 12px; padding: 14px 16px; margin-bottom: 22px; }
.lc-modal-thumb { width: 56px; height: 56px; flex-shrink: 0; display: flex; align-items: center; }
.lc-modal-specs { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
.lc-modal-prod { font-family: 'Newsreader', serif; font-size: 16px; font-weight: 500; color: ${colors.textDark}; }
.lc-modal-detail { font-size: 12px; color: ${colors.textGray}; }
.lc-form { display: flex; flex-direction: column; gap: 12px; margin-bottom: 20px; }
.lc-form-row { display: flex; gap: 12px; }
.lc-input { flex: 1; min-width: 0; font-family: 'Inter', sans-serif; font-size: 14px; padding: 12px 14px; border: 1.5px solid ${colors.border}; border-radius: 8px; color: ${colors.textDark}; outline: none; transition: border-color .18s; }
.lc-input:focus { border-color: ${colors.primary}; }
.lc-textarea { resize: vertical; min-height: 96px; width: 100%; box-sizing: border-box; }
.lc-hint-line { display: block; margin-top: 10px; font-size: 12.5px; color: ${colors.textLight}; line-height: 1.5; }
.lc-hint-line strong { color: ${colors.primary}; font-weight: 600; }
.lc-modal-submit { width: 100%; justify-content: center; padding: 14px; border: none; cursor: pointer; }
.lc-modal-submit:disabled { background: ${colors.border}; color: ${colors.textLight}; cursor: not-allowed; }
.lc-modal-note { display: block; text-align: center; font-size: 12px; color: ${colors.textLight}; margin-top: 12px; }
.lc-modal-success { text-align: center; padding: 12px 0; }
.lc-success-check { width: 60px; height: 60px; border-radius: 50%; background: ${colors.success}; color: #fff; font-size: 30px; display: flex; align-items: center; justify-content: center; margin: 0 auto 18px; }
.lc-design-link { display: inline-block; margin-top: 14px; color: ${colors.primary}; font-size: 14px; font-weight: 600; text-decoration: none; }
.lc-design-link:hover { text-decoration: underline; }

/* Responsive */
@media (max-width: 900px) {
  .lc-body { flex-direction: column; }
  .lc-summary { width: 100%; position: static; order: -1; }
  .lc-summary-preview { max-width: 200px; margin: 0 auto 20px; }
  .lc-cards-grid { grid-template-columns: 1fr 1fr; }
  .lc-uploads { grid-template-columns: 1fr; }
  .lc-picker-grid { grid-template-columns: 1fr; }
}
@media (max-width: 560px) {
  .lc-h2 { font-size: 24px; }
  .lc-cards-2 { grid-template-columns: 1fr; }
  .lc-swatches { grid-template-columns: repeat(2, 1fr); }
  .lc-progress-label { display: none; }
  .lc-progress-line { width: 24px; }
  .lc-color-tools { flex-direction: column; }
  .lc-form-row { flex-direction: column; }
  .lc-modal { padding: 28px 20px; }
}
`;
