const { Input, Button, BrandIcon, Select } = window.GrupoHaykDesignSystem_364dc7;
const { useState: useStateQ, useRef: useRefQ } = React;

const QM_CSS = `
.qm-overlay{ position:fixed; inset:0; background:rgba(10,22,41,.55); backdrop-filter:blur(3px);
  display:flex; align-items:center; justify-content:center; padding:24px; z-index:100;
  animation:qm-fade var(--dur-base) var(--ease-standard); }
@keyframes qm-fade{ from{ opacity:0; } to{ opacity:1; } }
.qm{ background:#fff; border-radius:var(--radius-xl); width:100%; max-width:660px; overflow:hidden;
  box-shadow:var(--shadow-lg); animation:qm-rise var(--dur-slow) var(--ease-out);
  display:flex; flex-direction:column; max-height:92vh; }
@keyframes qm-rise{ from{ transform:translateY(12px); opacity:0; } to{ transform:none; opacity:1; } }
.qm__head{ position:relative; background:var(--navy-700); padding:22px 26px; overflow:hidden; flex:none; }
.qm__head::before{ content:""; position:absolute; inset:0;
  background-image:url('assets/patterns/patron-verde.svg'); background-size:160px; opacity:.4; }
.qm__head h3{ position:relative; font-family:var(--font-display); font-weight:700; font-size:var(--fs-h4);
  color:#fff; margin:0; }
.qm__head p{ position:relative; font-family:var(--font-body); font-size:13px; color:var(--navy-100); margin:6px 0 0; }
.qm__close{ position:absolute; top:18px; right:18px; z-index:2; width:30px; height:30px; border-radius:50%;
  border:none; background:rgba(255,255,255,.14); color:#fff; font-size:16px; cursor:pointer; line-height:1; }
.qm__close:hover{ background:rgba(255,255,255,.24); }
.qm__body{ padding:6px 26px 24px; overflow-y:auto; }
.qm__row{ display:grid; grid-template-columns:1fr 1fr; gap:12px; }
.qm__row3{ display:grid; grid-template-columns:1fr 1fr 1fr; gap:12px; }
@media(max-width:560px){ .qm__row, .qm__row3{ grid-template-columns:1fr; } }
/* section blocks */
.qm__sec{ margin-top:20px; padding-top:18px; border-top:1px solid var(--border-subtle);
  display:flex; flex-direction:column; gap:12px; }
.qm__sec:first-child{ border-top:none; }
.qm__sec-head{ display:flex; align-items:center; gap:10px; }
.qm__sec-num{ width:24px; height:24px; border-radius:50%; background:var(--navy-700); color:#fff; flex:none;
  font-family:var(--font-body); font-weight:800; font-size:12px; display:flex; align-items:center; justify-content:center; }
.qm__sec-title{ font-family:var(--font-display); font-weight:600; font-size:15px; color:var(--text-primary); }
/* multi-route uploader */
.qm__multi-toggle{ display:flex; align-items:flex-start; gap:10px; font-family:var(--font-body);
  font-size:14px; color:var(--text-secondary); cursor:pointer; line-height:1.45; }
.qm__multi-toggle input{ margin-top:3px; accent-color:var(--green-600); width:16px; height:16px; }
.qm__drop{ border:1.5px dashed var(--navy-300); border-radius:var(--radius-md); background:var(--navy-50);
  padding:18px; display:flex; align-items:center; gap:14px; cursor:pointer;
  transition:border-color var(--dur-fast) var(--ease-standard), background var(--dur-fast) var(--ease-standard); }
.qm__drop:hover{ border-color:var(--green-600); background:var(--green-50); }
.qm__drop-txt{ font-family:var(--font-body); }
.qm__drop-txt b{ display:block; font-size:14px; color:var(--text-primary); font-weight:700; }
.qm__drop-txt span{ font-size:12px; color:var(--text-secondary); }
.qm__file{ display:flex; align-items:center; gap:8px; font-family:var(--font-body); font-size:13px;
  font-weight:700; color:var(--green-700); }
.qm__foot{ padding:16px 26px 24px; border-top:1px solid var(--border-subtle); flex:none; background:#fff; }
.qm__ok{ padding:48px 26px; text-align:center; display:flex; flex-direction:column; align-items:center; gap:14px; }
.qm__ok h3{ font-family:var(--font-display); font-weight:700; font-size:var(--fs-h4); color:var(--text-primary); margin:0; }
.qm__ok p{ font-family:var(--font-body); color:var(--text-secondary); margin:0; max-width:34ch; }
`;
{
  const _p = document.getElementById('qm-css'); if (_p) _p.remove();
  const s = document.createElement('style'); s.id = 'qm-css'; s.textContent = QM_CSS; document.head.appendChild(s);
}

const UNIDADES = ['Cam 1.5', 'Ram 3.5', 'Rabón', 'Tortón', 'Trailer 53"', 'Reefer 53"'];

function SecHead({ n, title }) {
  return (
    <div className="qm__sec-head">
      <span className="qm__sec-num">{n}</span>
      <span className="qm__sec-title">{title}</span>
    </div>
  );
}

function QuoteModal({ onClose }) {
  const [sent, setSent] = useStateQ(false);
  const [multi, setMulti] = useStateQ(false);
  const [fileName, setFileName] = useStateQ('');
  const [sending, setSending] = useStateQ(false);
  const [sendError, setSendError] = useStateQ('');
  const fileRef = useRefQ(null);
  const formRef = useRefQ(null);

  async function enviar() {
    setSending(true); setSendError('');
    try {
      const fd = new FormData();
      const inputs = formRef.current.querySelectorAll('input, select');
      const names = ['nombre','telefono','cargo','correo','origen','destino','unidad','tipo_carga','peso','volumen'];
      let i = 0;
      inputs.forEach((el) => {
        if (el.type === 'checkbox') { fd.append('rutas_multiples', el.checked ? '1' : '0'); return; }
        if (el.type === 'file') { if (el.files[0]) fd.append('documento', el.files[0]); return; }
        if (i < names.length) fd.append(names[i++], el.value);
      });
      const r = await fetch('api/cotizar.php', { method: 'POST', body: fd });
      const j = await r.json();
      if (!j.ok) throw new Error(j.error || 'Error al enviar');
      setSent(true);
    } catch (e) { setSendError(e.message); }
    setSending(false);
  }

  return (
    <div className="qm-overlay" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="qm" role="dialog" aria-modal="true">
        <button className="qm__close" onClick={onClose} aria-label="Cerrar">✕</button>
        {!sent ? (
          <>
            <div className="qm__head">
              <h3>Cotiza tu envío</h3>
              <p>Respuesta a la medida en menos de 24 horas.</p>
            </div>
            <div className="qm__body" ref={formRef}>
              <div className="qm__sec">
                <SecHead n="1" title="Información de contacto" />
                <div className="qm__row">
                  <Input label="Nombre" placeholder="Nombre completo" autoComplete="name" />
                  <Input label="Teléfono" type="tel" placeholder="55 0000 0000" autoComplete="tel" />
                </div>
                <div className="qm__row">
                  <Input label="Cargo" placeholder="Ej. Jefe de logística" />
                  <Input label="Correo" type="email" placeholder="nombre@empresa.com" autoComplete="email" />
                </div>
              </div>

              <div className="qm__sec">
                <SecHead n="2" title="Ruta" />
                <div className="qm__row">
                  <Input label="Origen" placeholder="Ciudad / estado" />
                  <Input label="Destino" placeholder="Ciudad / estado" />
                </div>
              </div>

              <div className="qm__sec">
                <SecHead n="3" title="Carga" />
                <div className="qm__row">
                  <Select label="Tipo de unidad" placeholder="Selecciona una unidad" options={UNIDADES} />
                  <Select label="Tipo de carga" placeholder="Selecciona el tipo"
                    options={[['seco', 'Seco'], ['refrigerado', 'Refrigerado']]} />
                </div>
                <div className="qm__row">
                  <Input label="Peso" placeholder="Ej. 12 ton" inputMode="decimal" />
                  <Input label="Volumen (pallets)" placeholder="Ej. 24 pallets" inputMode="numeric" />
                </div>
              </div>

              <div className="qm__sec">
                <SecHead n="4" title="Rutas múltiples (opcional)" />
                <label className="qm__multi-toggle">
                  <input type="checkbox" checked={multi} onChange={(e) => setMulti(e.target.checked)} />
                  <span>Tengo <b>varias rutas</b> por cotizar y quiero adjuntar mi documento (Excel, PDF o CSV) para recibir una cotización completa.</span>
                </label>
                {multi && (
                  <>
                    <div className="qm__drop" onClick={() => fileRef.current && fileRef.current.click()}>
                      <BrandIcon name="carga" size={38} />
                      <div className="qm__drop-txt">
                        <b>Adjunta tu documento de rutas</b>
                        <span>Excel, PDF o CSV · máx. 10 MB · haz clic para seleccionar</span>
                      </div>
                    </div>
                    <input ref={fileRef} type="file" accept=".xlsx,.xls,.csv,.pdf" style={{ display: 'none' }}
                      onChange={(e) => setFileName(e.target.files[0] ? e.target.files[0].name : '')} />
                    {fileName && <div className="qm__file">✓ {fileName}</div>}
                  </>
                )}
              </div>
            </div>
            <div className="qm__foot">
              {sendError && <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--status-danger)', fontWeight: 700, marginBottom: 10 }}>{sendError}</div>}
              <Button variant="cta" size="lg" block arrow disabled={sending} onClick={enviar}>{sending ? 'Enviando…' : 'Solicitar cotización'}</Button>
            </div>
          </>
        ) : (
          <div className="qm__ok">
            <BrandIcon name="seguridad" size={56} title="Enviado" />
            <h3>¡Solicitud recibida!</h3>
            <p>Gracias. Un especialista de Haykù revisará tu ruta{multi ? 's' : ''} y te contactará en menos de 24 horas.</p>
            <Button variant="primary" onClick={onClose}>Cerrar</Button>
          </div>
        )}
      </div>
    </div>
  );
}
window.QuoteModal = QuoteModal;
