// ─────────────────────────────────────────────────────
// CONFIGURADOR — product specs + live pricing.
// ─────────────────────────────────────────────────────

const cfgFmtEur = (n) => n == null || Number.isNaN(Number(n))
  ? '—'
  : new Intl.NumberFormat('es-ES', { style:'currency', currency:'EUR', minimumFractionDigits:2, maximumFractionDigits:2 }).format(Number(n));

const cfgFieldLabel = (key) => String(key || '').replace(/_/g, ' ');

const cfgCollectSpecs = (specs, values) => {
  const out = {};
  (specs || []).forEach(s => {
    const v = values[s.nombre_campo];
    if (v === '' || v == null) return;
    if (s.tipo === 'number') out[s.nombre_campo] = Number(v);
    else out[s.nombre_campo] = v;
  });
  return out;
};

const SpecField = ({ spec, value, onChange }) => {
  const label = cfgFieldLabel(spec.nombre_campo);
  if (spec.tipo === 'select') {
    const opts = Array.isArray(spec.opciones) ? spec.opciones : [];
    return (
      <div className="field">
        <label>{label}{spec.requerido ? ' *' : ''}</label>
        <select value={value || ''} onChange={e => onChange(spec.nombre_campo, e.target.value)}>
          <option value="">—</option>
          {opts.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      </div>
    );
  }
  if (spec.tipo === 'bool') {
    return (
      <label className="cfg-bool">
        <input type="checkbox" checked={!!value} onChange={e => onChange(spec.nombre_campo, e.target.checked)}/>
        <span>{label}{spec.requerido ? ' *' : ''}</span>
      </label>
    );
  }
  return (
    <div className="field">
      <label>{label}{spec.requerido ? ' *' : ''}</label>
      <input
        type={spec.tipo === 'number' ? 'number' : 'text'}
        step="any"
        value={value || ''}
        onChange={e => onChange(spec.nombre_campo, e.target.value)}
      />
    </div>
  );
};

const PricingPanel = ({ pricing, loading, error }) => {
  if (loading) return <div className="panel-b muted" style={{fontSize:12}}>Calculando tarifa…</div>;
  if (error) return <div className="panel-b" style={{fontSize:12,color:'var(--err)'}}>{error}</div>;
  if (!pricing) return <div className="panel-b muted" style={{fontSize:12}}>Selecciona producto y medidas para cotizar.</div>;
  const desg = pricing.coste_desglose || {};
  const rows = Object.entries(desg).filter(([,v]) => typeof v === 'number' && v > 0);
  const extras = Array.isArray(desg.extras) ? desg.extras : [];
  const warnings = Array.isArray(pricing.warnings) ? pricing.warnings : [];
  return (
    <div className="panel-b">
      <div className="cfg-price-total">{cfgFmtEur(pricing.precio_unitario_eur)} <span>/ ud</span></div>
      <div className="cfg-price-sub">Línea ({pricing.unidades || 1} ud): <strong>{cfgFmtEur(pricing.precio_linea_eur)}</strong></div>
      <div className="cfg-price-grid">
        <div><span>Coste</span><strong>{cfgFmtEur(pricing.coste_total_eur)}</strong></div>
        <div><span>Margen</span><strong>{pricing.margen_pct != null ? `${Math.round(Number(pricing.margen_pct) * 100)}%` : '—'}</strong></div>
      </div>
      {(rows.length > 0 || extras.length > 0) && (
        <table className="tbl" style={{marginTop:12,fontSize:12}}>
          <tbody>
            {rows.map(([k,v]) => <tr key={k}><td>{cfgFieldLabel(k)}</td><td className="num right">{cfgFmtEur(v)}</td></tr>)}
            {extras.map((e, i) => <tr key={`e-${i}`}><td>+ {e.key} × {e.qty}</td><td className="num right">{cfgFmtEur(e.total)}</td></tr>)}
          </tbody>
        </table>
      )}
      {warnings.length > 0 && (
        <div className="cfg-warnings">{warnings.map((w, i) => <div key={i}>· {w}</div>)}</div>
      )}
    </div>
  );
};

const ConfiguradorView = ({ onToast }) => {
  const [tarifa, setTarifa] = React.useState(null);
  const [familias, setFamilias] = React.useState([]);
  const [productos, setProductos] = React.useState([]);
  const [familiaId, setFamiliaId] = React.useState('');
  const [selectedId, setSelectedId] = React.useState(null);
  const [producto, setProducto] = React.useState(null);
  const [values, setValues] = React.useState({});
  const [unidades, setUnidades] = React.useState(1);
  const [pricing, setPricing] = React.useState(null);
  const [pricingLoading, setPricingLoading] = React.useState(false);
  const [pricingError, setPricingError] = React.useState('');
  const [search, setSearch] = React.useState('');

  const toast = (msg, isErr) => onToast ? onToast(msg, isErr) : (isErr && console.error(msg));

  React.useEffect(() => {
    let alive = true;
    Promise.all([
      API.get('/api/configurador/tarifa-vigente').catch(() => null),
      API.get('/api/configurador/familias').catch(() => []),
    ]).then(([t, fs]) => {
      if (!alive) return;
      setTarifa(t);
      setFamilias(Array.isArray(fs) ? fs : []);
    });
    return () => { alive = false; };
  }, []);

  React.useEffect(() => {
    let alive = true;
    const params = familiaId ? { familia_id: familiaId } : undefined;
    API.get('/api/configurador/productos', params)
      .then(rows => {
        if (!alive) return;
        const list = Array.isArray(rows) ? rows : [];
        setProductos(list);
        if (!selectedId && list[0]) setSelectedId(list[0].id);
      })
      .catch(e => toast(e.message || 'Error al cargar productos', true));
    return () => { alive = false; };
  }, [familiaId]);

  React.useEffect(() => {
    if (!selectedId) { setProducto(null); return; }
    let alive = true;
    setProducto(null);
    setPricing(null);
    setPricingError('');
    API.get(`/api/configurador/producto/${selectedId}`)
      .then(p => {
        if (!alive) return;
        setProducto(p);
        const defaults = {};
        (p.especificaciones || []).forEach(s => { defaults[s.nombre_campo] = s.tipo === 'bool' ? false : ''; });
        setValues(defaults);
        setUnidades(1);
      })
      .catch(e => toast(e.message || 'Error al cargar producto', true));
    return () => { alive = false; };
  }, [selectedId]);

  React.useEffect(() => {
    if (!producto) return;
    const t = setTimeout(async () => {
      setPricingLoading(true);
      setPricingError('');
      try {
        const result = await API.post('/api/configurador/cotizar', {
          producto_id: producto.id,
          configuracion: cfgCollectSpecs(producto.especificaciones || [], values),
          unidades: Number(unidades) || 1,
        });
        setPricing(result);
      } catch (e) {
        setPricing(null);
        setPricingError(e.message || 'Error al cotizar');
      } finally {
        setPricingLoading(false);
      }
    }, 500);
    return () => clearTimeout(t);
  }, [producto && producto.id, JSON.stringify(values), unidades]);

  const filteredProducts = productos.filter(p => {
    const q = search.trim().toLowerCase();
    if (!q) return true;
    return [p.codigo, p.nombre, p.familia_nombre].some(v => String(v || '').toLowerCase().includes(q));
  });

  const setSpec = (key, value) => setValues(v => ({ ...v, [key]: value }));

  return (
    <>
      <div className="page-h">
        <div>
          <h1>Configurador</h1>
          <div className="sub">Cotización rápida por familia, producto y especificaciones</div>
        </div>
        <div className="page-h-actions">
          <span className="cfg-tarifa">
            <Icon name="sparkles" size={13}/>
            {tarifa ? `Tarifa v${tarifa.version} · IVA ${Math.round(Number(tarifa.constantes?.iva || 0.21) * 100)}%` : 'Tarifa vigente'}
          </span>
        </div>
      </div>

      <div className="cfg-layout">
        <div className="panel cfg-products">
          <div className="panel-h">
            Productos
            <span className="badge">{filteredProducts.length}</span>
          </div>
          <div className="panel-b" style={{display:'flex',flexDirection:'column',gap:10}}>
            <select value={familiaId} onChange={e => { setFamiliaId(e.target.value); setSelectedId(null); }} className="cfg-select">
              <option value="">Todas las familias</option>
              {familias.map(f => <option key={f.id} value={f.id}>{f.nombre}</option>)}
            </select>
            <div className="tb-search" style={{minWidth:0}}>
              <Icon name="search"/>
              <input placeholder="Buscar producto…" value={search} onChange={e => setSearch(e.target.value)}/>
            </div>
            <div className="cfg-product-list">
              {filteredProducts.map(p => (
                <button key={p.id} className={`cfg-product ${selectedId === p.id ? 'on' : ''}`} onClick={() => setSelectedId(p.id)}>
                  <span className="prod">{p.imagen_url ? <img src={p.imagen_url} alt=""/> : <Icon name="package" size={14}/>}</span>
                  <span>
                    <strong>{p.codigo}</strong>
                    <small>{p.nombre || p.familia_nombre}</small>
                  </span>
                  {p.status === 'NEEDS_MANUAL_INPUT' && <span className="pill warn"><span className="d"/>TODO</span>}
                </button>
              ))}
              {filteredProducts.length === 0 && <div className="muted" style={{fontSize:12,padding:12}}>Sin productos.</div>}
            </div>
          </div>
        </div>

        <div className="panel cfg-form-panel">
          <div className="panel-h">
            {producto ? `${producto.codigo} · ${producto.nombre || producto.familia_nombre}` : 'Especificaciones'}
            {producto && <span className="badge">{producto.pricing_kind || 'pricing'}</span>}
          </div>
          <div className="panel-b">
            {!producto && <div className="muted" style={{fontSize:12}}>Selecciona un producto.</div>}
            {producto && (
              <>
                <div className="fields-grid cols-3">
                  {(producto.especificaciones || []).map(s => (
                    <SpecField key={s.id || s.nombre_campo} spec={s} value={values[s.nombre_campo]} onChange={setSpec}/>
                  ))}
                  <div className="field">
                    <label>Unidades</label>
                    <input type="number" min="1" value={unidades} onChange={e => setUnidades(e.target.value)}/>
                  </div>
                </div>
                {(!producto.especificaciones || producto.especificaciones.length === 0) && (
                  <div className="muted" style={{fontSize:12}}>Este producto todavía no tiene especificaciones configuradas.</div>
                )}
              </>
            )}
          </div>
        </div>

        <div className="panel cfg-pricing">
          <div className="panel-h">Precio estimado</div>
          <PricingPanel pricing={pricing} loading={pricingLoading} error={pricingError}/>
        </div>
      </div>
    </>
  );
};

window.ConfiguradorView = ConfiguradorView;
