// Cotizador interactivo — STFLOW
const { useState, useEffect, useMemo } = React;

const PRODUCTS = [
  { id: 'remera',  name: 'Remera',       ico: '👕', base: 180, desc: 'Algodón peinado 24/1' },
  { id: 'gorra',   name: 'Gorra',        ico: '🧢', base: 260, desc: 'Trucker, snapback o cerrada' },
  { id: 'buzo',    name: 'Buzo',         ico: '🧥', base: 480, desc: 'Canguro o redondo' },
  { id: 'polo',    name: 'Polo',         ico: '👔', base: 320, desc: 'Piqué algodón corporativo' },
  { id: 'tote',    name: 'Tote bag',     ico: '👜', base: 140, desc: 'Crudo 100% algodón' },
  { id: 'taza',    name: 'Taza',         ico: '☕', base: 110, desc: 'Cerámica sublimable' },
];

const TECHNIQUES = {
  remera: [
    { id: 'dtf',    name: 'DTF',          note: 'Full color, todo tipo de tela', cost: 150 },
    { id: 'sub',    name: 'Sublimación',  note: 'Poliéster claro', cost: 110 },
    { id: 'seri',   name: 'Serigrafía',   note: '30+ unidades', cost: 70 },
    { id: 'vin',    name: 'Vinilo',       note: 'Texto / números', cost: 60 },
  ],
  gorra: [
    { id: 'bord',   name: 'Bordado',      note: 'Premium · recomendado', cost: 240 },
    { id: 'dtf',    name: 'DTF',          note: 'Full color', cost: 140 },
    { id: 'sub',    name: 'Sublimación',  note: 'Gorras claras', cost: 120 },
  ],
  buzo: [
    { id: 'dtf',    name: 'DTF',          note: 'Full color', cost: 220 },
    { id: 'bord',   name: 'Bordado',      note: 'Logo pequeño', cost: 280 },
    { id: 'seri',   name: 'Serigrafía',   note: '30+ unidades', cost: 110 },
  ],
  polo: [
    { id: 'bord',   name: 'Bordado',      note: 'Recomendado corporativo', cost: 260 },
    { id: 'dtf',    name: 'DTF',          note: 'Full color', cost: 160 },
  ],
  tote: [
    { id: 'dtf',    name: 'DTF',          note: 'Full color', cost: 130 },
    { id: 'seri',   name: 'Serigrafía',   note: '30+ unidades', cost: 70 },
    { id: 'vin',    name: 'Vinilo',       note: 'Texto plano', cost: 60 },
  ],
  taza: [
    { id: 'sub',    name: 'Sublimación',  note: 'Full color', cost: 90 },
  ],
};

const ADDONS = [
  { id: 'packaging', name: 'Packaging kraft + tarjeta', desc: 'Bolsita kraft, sticker y tarjeta de agradecimiento', price: 40 },
  { id: 'etiqueta',  name: 'Etiqueta con tu marca',      desc: 'Etiqueta cosida interna con tu logo',               price: 60 },
  { id: 'back',      name: 'Estampa en la espalda',      desc: 'Segunda posición de estampado',                      price: 120 },
  { id: 'urgente',   name: 'Producción express',         desc: 'Entrega en 5 días hábiles (vs 10-15)',               price: 150 },
];

function volumeDiscount(qty) {
  if (qty >= 100) return 0.20;
  if (qty >= 50)  return 0.15;
  if (qty >= 20)  return 0.10;
  return 0;
}

function fmt(n) {
  return '$' + Math.round(n).toLocaleString('es-MX');
}

function Quoter() {
  const [step, setStep] = useState(0);
  const [productId, setProductId] = useState(null);
  const [techId, setTechId] = useState(null);
  const [qty, setQty] = useState(10);
  const [addons, setAddons] = useState({});

  const product = PRODUCTS.find(p => p.id === productId);
  const techniques = productId ? TECHNIQUES[productId] : [];
  const technique = techniques.find(t => t.id === techId);

  // Reset technique when product changes
  useEffect(() => {
    if (productId && techId && !TECHNIQUES[productId].some(t => t.id === techId)) {
      setTechId(null);
    }
  }, [productId]);

  const calc = useMemo(() => {
    if (!product || !technique) return null;
    const addonPrice = Object.entries(addons)
      .filter(([, on]) => on)
      .reduce((s, [id]) => s + (ADDONS.find(a => a.id === id)?.price || 0), 0);
    const unitCost = product.base + technique.cost + addonPrice + 50; // 50 = packaging base + control
    const margin = 2.4;
    const rawUnitPrice = unitCost * margin;
    const discount = volumeDiscount(qty);
    const unitPrice = rawUnitPrice * (1 - discount);
    const subtotal = unitPrice * qty;
    const profit = (unitPrice - unitCost) * qty;
    return {
      unitCost,
      rawUnitPrice,
      unitPrice,
      subtotal,
      profit,
      discount,
      addonPrice,
    };
  }, [product, technique, qty, addons]);

  const canNext = (step === 0 && productId) || (step === 1 && techId) || step === 2 || step === 3;

  const goNext = () => setStep(s => Math.min(s + 1, 3));
  const goBack = () => setStep(s => Math.max(s - 1, 0));

  const sendWhatsApp = () => {
    if (!product || !technique || !calc) return;
    const activeAddons = Object.entries(addons)
      .filter(([, on]) => on)
      .map(([id]) => ADDONS.find(a => a.id === id).name)
      .join(', ') || 'ninguno';
    const msg =
`Hola STFLOW! Quiero cotizar:
• Producto: ${product.name}
• Técnica: ${technique.name}
• Cantidad: ${qty}
• Adicionales: ${activeAddons}
• Estimado: ${fmt(calc.subtotal)} MX
¿Me pasan detalles?`;
    window.open(`https://wa.me/525572888676?text=${encodeURIComponent(msg)}`, '_blank');
  };

  const steps = [
    { label: 'Producto' },
    { label: 'Técnica' },
    { label: 'Cantidad' },
    { label: 'Extras' },
  ];

  return (
    <div className="quoter" id="cotizador-box">
      <div className="quoter-main">
        {/* Steps indicator */}
        <div className="steps">
          {steps.map((s, i) => (
            <button
              key={i}
              className={`step ${i === step ? 'active' : ''} ${i < step ? 'done' : ''}`}
              onClick={() => {
                // only allow going back, or forward if previous is filled
                if (i <= step) setStep(i);
                else if ((i === 1 && productId) || (i === 2 && techId) || (i === 3 && techId)) setStep(i);
              }}
            >
              <span className="num">{i < step ? '✓' : i + 1}</span>
              {s.label}
            </button>
          ))}
        </div>

        {step === 0 && <Step0 {...{productId, setProductId}} />}
        {step === 1 && <Step1 {...{product, techniques, techId, setTechId}} />}
        {step === 2 && <Step2 {...{qty, setQty, product}} />}
        {step === 3 && <Step3 {...{addons, setAddons}} />}

        <div className="nav-btns">
          <button className="btn btn-ghost" onClick={goBack} disabled={step === 0} style={{opacity: step===0 ? 0.3 : 1}}>
            ← Atrás
          </button>
          {step < 3 ? (
            <button className="btn btn-primary" onClick={goNext} disabled={!canNext} style={{opacity: canNext ? 1 : 0.3}}>
              Siguiente →
            </button>
          ) : (
            <button className="btn btn-primary" onClick={sendWhatsApp}>
              Enviar por WhatsApp →
            </button>
          )}
        </div>
      </div>

      {/* Summary panel */}
      <aside className="quoter-summary">
        <SummaryPanel {...{product, technique, qty, addons, calc, sendWhatsApp}} />
      </aside>
    </div>
  );
}

function Step0({ productId, setProductId }) {
  return (
    <>
      <h3 className="q-title">¿Qué producto querés cotizar?</h3>
      <p className="q-sub">Elegí la prenda o artículo base. Después elegimos la técnica de estampado.</p>
      <div className="product-grid">
        {PRODUCTS.map(p => (
          <button
            key={p.id}
            className={`product-tile ${productId === p.id ? 'selected' : ''}`}
            onClick={() => setProductId(p.id)}
          >
            <span className="chk">{productId === p.id ? '✓' : ''}</span>
            <div className="ico">{p.ico}</div>
            <div className="nm">{p.name}</div>
            <div className="pr">desde {fmt(p.base)}</div>
          </button>
        ))}
      </div>
    </>
  );
}

function Step1({ product, techniques, techId, setTechId }) {
  return (
    <>
      <h3 className="q-title">Elegí la técnica de estampado</h3>
      <p className="q-sub">Para <b style={{color:'var(--cyan)'}}>{product.name}</b> estas son las opciones disponibles.</p>
      <div className="option-row">
        {techniques.map(t => (
          <button
            key={t.id}
            className={`opt ${techId === t.id ? 'selected' : ''}`}
            onClick={() => setTechId(t.id)}
          >
            <div className="nm">{t.name}</div>
            <div className="note">{t.note}</div>
          </button>
        ))}
      </div>
    </>
  );
}

function Step2({ qty, setQty, product }) {
  const presets = [1, 10, 20, 50, 100];
  const discount = volumeDiscount(qty);
  return (
    <>
      <h3 className="q-title">¿Cuántas unidades?</h3>
      <p className="q-sub">A partir de 20 unidades aplicamos descuentos automáticos por volumen.</p>
      <div className="qty-row">
        <div className="qty-label">
          <b>{qty}</b>
          <span style={{textAlign:'right'}}>
            {discount > 0 ? (
              <span style={{color:'var(--cyan)', fontWeight:600}}>−{Math.round(discount*100)}% VOL</span>
            ) : 'sin descuento'}
            <span style={{display:'block', color:'var(--text-mute)', marginTop:2, fontSize:10}}>
              {product.name.toLowerCase()}
            </span>
          </span>
        </div>
        <input
          type="range"
          min="1"
          max="200"
          value={qty}
          onChange={e => setQty(parseInt(e.target.value))}
          className="slider"
        />
        <div className="qty-presets">
          {presets.map(p => (
            <button
              key={p}
              className={`preset ${qty === p ? 'active' : ''}`}
              onClick={() => setQty(p)}
            >
              {p} {p === 1 ? 'unidad' : 'uds'}
            </button>
          ))}
        </div>
      </div>
    </>
  );
}

function Step3({ addons, setAddons }) {
  const toggle = id => setAddons(a => ({ ...a, [id]: !a[id] }));
  return (
    <>
      <h3 className="q-title">Extras</h3>
      <p className="q-sub">Adicionales opcionales. Podés saltarlos si no te hacen falta.</p>
      <div className="addons">
        {ADDONS.map(a => (
          <div
            key={a.id}
            className={`addon ${addons[a.id] ? 'on' : ''}`}
            onClick={() => toggle(a.id)}
          >
            <div className="info">
              <div className="nm">{a.name}</div>
              <div className="desc">{a.desc}</div>
            </div>
            <div style={{display:'flex', alignItems:'center', gap: 16}}>
              <span className="pr">+{fmt(a.price)}/u</span>
              <div className="toggle" />
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

function SummaryPanel({ product, technique, qty, addons, calc, sendWhatsApp }) {
  if (!product || !technique || !calc) {
    return (
      <div className="empty-summary">
        <div className="big">Armá tu pedido</div>
        <div>Completá los pasos y vas a ver acá tu cotización en vivo, actualizada al instante.</div>
      </div>
    );
  }
  const activeAddons = ADDONS.filter(a => addons[a.id]);
  return (
    <>
      <div className="sum-head">Total estimado</div>
      <div className="sum-total">{fmt(calc.subtotal)}</div>
      <div className="sum-currency">Pesos mexicanos · IVA incluido</div>
      <div className="sum-unit">
        <b>{fmt(calc.unitPrice)}</b> por unidad × <b>{qty}</b>
      </div>

      <div className="sum-divider" />

      <div className="sum-list">
        <div className="sum-row"><span className="k">Producto</span><span className="v">{product.name}</span></div>
        <div className="sum-row"><span className="k">Técnica</span><span className="v">{technique.name}</span></div>
        <div className="sum-row"><span className="k">Cantidad</span><span className="v">{qty} uds</span></div>
        {activeAddons.length > 0 && (
          <div className="sum-row">
            <span className="k">Extras</span>
            <span className="v" style={{textAlign:'right', maxWidth:180, fontSize:11, lineHeight:1.4}}>
              {activeAddons.map(a => a.name).join(' · ')}
            </span>
          </div>
        )}
        {calc.discount > 0 && (
          <div className="sum-row strong">
            <span className="k">Descuento volumen</span>
            <span className="v">−{Math.round(calc.discount*100)}%</span>
          </div>
        )}
      </div>

      <div className="sum-cta">
        <button className="btn btn-primary" onClick={sendWhatsApp}>
          Confirmar por WhatsApp
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.174.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51a13 13 0 0 0-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.9 9.9 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.82 9.82 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.8 11.8 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.9 11.9 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.82 11.82 0 0 0-3.48-8.413"/></svg>
        </button>
        <div className="sum-small">estimado orientativo · cotización final 1-3 días hábiles</div>
      </div>
    </>
  );
}

window.Quoter = Quoter;
