// app.jsx — Orchestrator

const STORAGE_KEY = 'a1broker_lead_v1';
const EMAIL_TO = 'info@a1broker.com.ar'; // destino del email (fallback mailto)
// WA_NUMBER se carga desde /api/config al arrancar

// Las llamadas /api/* siempre van al mismo origen (el frontend-server hace proxy en dev,
// DO hace proxy en producción). API_BASE siempre vacío = ruta relativa.
const API_BASE = '';

// ─────────────────────────────────────────────────────────────
// Address/contact/locality validators at submit time
// ─────────────────────────────────────────────────────────────
function validateStep(step, data) {
  const v = data[step.id];
  if (step.kind === 'address') {
    const err = {};
    if (V.notJunk(v && v.calle)) err.calle = V.notJunk(v && v.calle);
    if (V.required(v && v.numero)) err.numero = V.required(v && v.numero);
    return Object.keys(err).length ? err : null;
  }
  if (step.kind === 'locality') {
    const err = {};
    if (V.notJunk(v && v.localidad)) err.localidad = V.notJunk(v && v.localidad);
    const cp = (v && v.cp || '').replace(/\D/g, '');
    if (!cp || cp.length < 4) err.cp = 'Código postal inválido';
    return Object.keys(err).length ? err : null;
  }
  if (step.kind === 'contact') {
    const err = {};
    if (V.email(v && v.email)) err.email = V.email(v && v.email);
    if (V.phoneAr(v && v.tel)) err.tel = V.phoneAr(v && v.tel);
    return Object.keys(err).length ? err : null;
  }
  if (step.kind === 'home-m2') {
    const err = {};
    if (V.positiveNum(v && v.cubiertos)) err.cubiertos = V.positiveNum(v && v.cubiertos);
    return Object.keys(err).length ? err : null;
  }
  if (step.kind === 'ap-norep') {
    const err = {};
    if (V.cuit(v && v.cuit)) err.cuit = V.cuit(v && v.cuit);
    if (V.positiveNum(v && v.suma)) err.suma = V.positiveNum(v && v.suma);
    return Object.keys(err).length ? err : null;
  }
  if (step.optional) return null;
  if (step.validate) return step.validate(v);
  if (step.kind === 'options' || step.kind === 'yesno') return V.required(v);
  if (step.kind === 'multi') return V.required(v);
  return null;
}

// ─────────────────────────────────────────────────────────────
// Label formatters for summary
// ─────────────────────────────────────────────────────────────
function fmt(step, value) {
  if (value === undefined || value === null || value === '') return null;
  switch (step.kind) {
    case 'address':
      return [value.calle, value.numero, value.piso].filter(Boolean).join(' ');
    case 'locality':
      return [value.localidad, value.cp && `(CP ${value.cp})`].filter(Boolean).join(' ');
    case 'contact':
      return `${value.email || ''}${value.tel ? ` · +54 ${value.tel}` : ''}`;
    case 'date':
      return new Date(value).toLocaleDateString('es-AR');
    case 'yesno':
      return value === 'si' ? 'Sí' : 'No';
    case 'options':
      const o = (step.options || []).find(x => x.value === value);
      return o ? o.label : value;
    case 'multi':
      if (!Array.isArray(value)) return null;
      return value.map(v => {
        const o = (step.options || []).find(x => x.value === v);
        return o ? o.label : v;
      }).join(', ');
    case 'file':
      return value && value.name ? `📎 ${value.name}` : null;
    case 'files':
      if (!Array.isArray(value) || !value.length) return null;
      return `📎 ${value.length} archivo${value.length > 1 ? 's' : ''}: ${value.map(f => f.name).join(', ')}`;
    case 'discount-upload':
      if (!Array.isArray(value) || !value.length) return null;
      return `📎 ${value.length} archivo${value.length > 1 ? 's' : ''} adjunto${value.length > 1 ? 's' : ''}`;
    case 'auto-details':
      const d = value || {};
      return [d.chasis && `Chasis: ${d.chasis}`, d.motor && `Motor: ${d.motor}`,
              d.km && `${d.km} km`, d.color && `Color: ${d.color}`,
              d.cubiertas && `Cubiertas: ${d.cubiertas}`].filter(Boolean).join(' · ');
    case 'auto-equip':
      const e = value || {};
      return [e.alarma && `Alarma: ${e.alarma === 'si' ? 'Sí' : 'No'}`,
              e.llave && `Llave: ${e.llave}`,
              e.gnc && `GNC: ${e.gnc === 'si' ? 'Sí' : 'No'}`].filter(Boolean).join(' · ');
    case 'home-m2':
      const m = value || {};
      return [m.cubiertos && `${m.cubiertos} m² cubiertos`,
              m.descubiertos && `${m.descubiertos} m² descubiertos`].filter(Boolean).join(' · ');
    case 'ap-norep':
      const n = value || {};
      return [n.cuit && `CUIT: ${n.cuit}`, n.suma && `Suma: $${n.suma}`].filter(Boolean).join(' · ');
    case 'travel-dates':
      const t = value || {};
      return [t.salida && `Sale ${t.salida}`, t.regreso && `Vuelve ${t.regreso}`].filter(Boolean).join(' · ');
    case 'travel-pre':
      const p = value || {};
      if (p.tiene === 'no') return 'No';
      if (p.tiene === 'si') return `Sí${p.detalle ? ' · ' + p.detalle : ''}`;
      return null;
    default:
      return typeof value === 'string' ? value : JSON.stringify(value);
  }
}

// Friendly labels for summary rows
const PERSONAL_LABELS = {
  nombre: 'Nombre',
  dni: 'DNI / CUIL',
  nacimiento: 'Nacimiento',
  domicilio: 'Domicilio',
  localidad: 'Localidad',
  contacto: 'Contacto',
  descuento: 'Documentación',
};

// ─────────────────────────────────────────────────────────────
// Build plain-text summary for email/WhatsApp
// ─────────────────────────────────────────────────────────────
function buildTextSummary(data, riskValue) {
  const lines = [];
  const risk = RISK_CATEGORIES.find(r => r.value === riskValue);
  lines.push(`🛡️ NUEVA COTIZACIÓN A1 BROKER`);
  lines.push(`#${(riskValue || '').toUpperCase()}`);
  lines.push('');
  const FILE_KINDS = ['file', 'files', 'discount-upload'];
  lines.push(`── Datos personales ──`);
  PERSONAL_STEPS.forEach(s => {
    const v = fmt(s, data[s.id]);
    if (v) {
      const prefix = FILE_KINDS.includes(s.kind) ? `[ARCHIVOS:${s.id}] ` : '';
      lines.push(`${PERSONAL_LABELS[s.id] || s.id}: ${prefix}${v}`);
    }
  });
  lines.push('');
  lines.push(`── Riesgo: ${risk ? risk.label : riskValue} ──`);
  (RISK_FLOWS[riskValue] || []).forEach(s => {
    const v = fmt(s, data[s.id]);
    if (v) {
      const prefix = FILE_KINDS.includes(s.kind) ? `[ARCHIVOS:${s.id}] ` : '';
      lines.push(`${s.title}: ${prefix}${v}`);
    }
  });
  const premium = Array.isArray(data.descuento) && data.descuento.length > 0;
  if (premium) {
    lines.push('');
    lines.push('🏷️ ETIQUETA: PREMIUM 5% OFF (adjuntó documentación)');
  }
  return lines.join('\n');
}

// ─────────────────────────────────────────────────────────────
// Tweaks panel
// ─────────────────────────────────────────────────────────────
const PALETTES = {
  azul:    { brand900: '#0A2540', brand800: '#0F3563', brand700: '#134785', brand600: '#1E63B8', brand500: '#2A7DE1', brand100: '#E7F0FB', brand50: '#F3F7FC' },
  verde:   { brand900: '#052E1F', brand800: '#064E3B', brand700: '#065F46', brand600: '#047857', brand500: '#10B981', brand100: '#D1FAE5', brand50: '#ECFDF5' },
  indigo:  { brand900: '#1E1B4B', brand800: '#312E81', brand700: '#3730A3', brand600: '#4338CA', brand500: '#6366F1', brand100: '#E0E7FF', brand50: '#EEF2FF' },
  carbon:  { brand900: '#0F172A', brand800: '#1E293B', brand700: '#334155', brand600: '#475569', brand500: '#64748B', brand100: '#E2E8F0', brand50: '#F1F5F9' },
};

function applyTweaks(tweaks) {
  const root = document.documentElement;
  const p = PALETTES[tweaks.palette] || PALETTES.azul;
  root.style.setProperty('--brand-900', p.brand900);
  root.style.setProperty('--brand-800', p.brand800);
  root.style.setProperty('--brand-700', p.brand700);
  root.style.setProperty('--brand-600', p.brand600);
  root.style.setProperty('--brand-500', p.brand500);
  root.style.setProperty('--brand-100', p.brand100);
  root.style.setProperty('--brand-50', p.brand50);
}

function TweaksPanel({ tweaks, setTweaks }) {
  const update = (patch) => {
    const next = { ...tweaks, ...patch };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*');
  };
  return (
    <div className="tweaks-panel">
      <header>
        <span>Tweaks</span>
        <span style={{ opacity: 0.6, fontSize: 11 }}>A1 Broker</span>
      </header>
      <div className="body">
        <div>
          <label>Paleta</label>
          <div className="swatches">
            {Object.entries(PALETTES).map(([k, p]) => (
              <button key={k}
                className={'swatch' + (tweaks.palette === k ? ' active' : '')}
                style={{ background: p.brand700 }}
                onClick={() => update({ palette: k })}
                title={k} />
            ))}
          </div>
        </div>
        <div>
          <label>Densidad</label>
          <select value={tweaks.density} onChange={e => update({ density: e.target.value })}>
            <option value="comfortable">Cómoda</option>
            <option value="compact">Compacta</option>
          </select>
        </div>
        <div>
          <label>Emojis en iconos</label>
          <select value={tweaks.emojis ? 'si' : 'no'} onChange={e => update({ emojis: e.target.value === 'si' })}>
            <option value="si">Sí</option>
            <option value="no">No (solo texto)</option>
          </select>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Main App
// ─────────────────────────────────────────────────────────────
function App() {
  // Persisted state
  const [state, setState] = useState(() => {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (raw) return JSON.parse(raw);
    } catch (e) {}
    return { phase: 'welcome', data: {}, stepIdx: 0, riskIdx: 0, risk: null };
  });
  const [error, setError] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [cotizacionId, setCotizacionId] = useState(null);
  const [waNumber, setWaNumber] = useState('5491161883339');
  const [tweaks, setTweaks] = useState(window.__TWEAKS || { palette: 'azul', density: 'comfortable', emojis: true });
  const [tweaksOpen, setTweaksOpen] = useState(false);

  // Persist
  useEffect(() => {
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); } catch (e) {}
  }, [state]);

  // Cargar config pública desde el backend
  useEffect(() => {
    fetch(`${API_BASE}/api/config`)
      .then(r => r.json())
      .then(cfg => { if (cfg.waNumber) setWaNumber(cfg.waNumber); })
      .catch(() => {}); // fallback al default si el backend no responde
  }, []);

  // Apply tweaks
  useEffect(() => { applyTweaks(tweaks); }, [tweaks]);

  // Tweaks host integration
  useEffect(() => {
    const onMsg = (e) => {
      if (!e.data) return;
      if (e.data.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  // Build the steps list dynamically based on phase
  const activeSteps = useMemo(() => {
    if (state.phase === 'personal') return PERSONAL_STEPS;
    if (state.phase === 'risk-form') return RISK_FLOWS[state.risk] || [];
    return [];
  }, [state.phase, state.risk]);

  // Visible steps (after showIf filtering) — consistent index across render
  const visibleSteps = useMemo(() =>
    activeSteps.filter(s => !s.showIf || s.showIf(state.data)),
  [activeSteps, state.data]);

  const totalSteps = useMemo(() => {
    // Full journey total for progress:
    // personal + risk-picker + risk flow (estimate) + summary
    const riskFlowLen = state.risk ? (RISK_FLOWS[state.risk] || []).filter(s => !s.showIf || s.showIf(state.data)).length : 0;
    return PERSONAL_STEPS.length + 1 + riskFlowLen + 1;
  }, [state.risk, state.data]);

  const currentOverallIdx = useMemo(() => {
    if (state.phase === 'welcome') return 0;
    if (state.phase === 'personal') return state.stepIdx;
    if (state.phase === 'risk-pick') return PERSONAL_STEPS.length;
    if (state.phase === 'risk-form') return PERSONAL_STEPS.length + 1 + state.riskIdx;
    if (state.phase === 'summary') return totalSteps - 1;
    return totalSteps;
  }, [state, totalSteps]);

  const setField = (id, value) => {
    setState(s => ({ ...s, data: { ...s.data, [id]: value } }));
    setError(null);
  };

  const handleStart = () => {
    setState(s => ({ ...s, phase: 'personal', stepIdx: 0 }));
  };

  const handleBack = () => {
    setError(null);
    setState(s => {
      if (s.phase === 'personal') {
        if (s.stepIdx === 0) return { ...s, phase: 'welcome' };
        return { ...s, stepIdx: s.stepIdx - 1 };
      }
      if (s.phase === 'risk-pick') return { ...s, phase: 'personal', stepIdx: PERSONAL_STEPS.length - 1 };
      if (s.phase === 'risk-form') {
        if (s.riskIdx === 0) return { ...s, phase: 'risk-pick' };
        // skip invisible prev steps
        const flow = RISK_FLOWS[s.risk] || [];
        let idx = s.riskIdx - 1;
        while (idx > 0 && flow[idx].showIf && !flow[idx].showIf(s.data)) idx--;
        return { ...s, riskIdx: idx };
      }
      if (s.phase === 'summary') {
        const flow = RISK_FLOWS[s.risk] || [];
        const visible = flow.filter(st => !st.showIf || st.showIf(s.data));
        return { ...s, phase: 'risk-form', riskIdx: Math.max(0, visible.length - 1) };
      }
      return s;
    });
  };

  const handleNext = () => {
    if (state.phase === 'personal') {
      const step = PERSONAL_STEPS[state.stepIdx];
      const err = validateStep(step, state.data);
      if (err) { setError(err); return; }
      setError(null);
      if (state.stepIdx + 1 < PERSONAL_STEPS.length) {
        setState(s => ({ ...s, stepIdx: s.stepIdx + 1 }));
      } else {
        setState(s => ({ ...s, phase: 'risk-pick' }));
      }
    } else if (state.phase === 'risk-pick') {
      if (!state.risk) { setError('Seleccioná un tipo de seguro'); return; }
      setError(null);
      setState(s => ({ ...s, phase: 'risk-form', riskIdx: 0 }));
    } else if (state.phase === 'risk-form') {
      const flow = RISK_FLOWS[state.risk] || [];
      const step = flow[state.riskIdx];
      const err = validateStep(step, state.data);
      if (err) { setError(err); return; }
      setError(null);
      // next visible
      let nextIdx = state.riskIdx + 1;
      while (nextIdx < flow.length && flow[nextIdx].showIf && !flow[nextIdx].showIf(state.data)) nextIdx++;
      if (nextIdx >= flow.length) {
        setState(s => ({ ...s, phase: 'summary' }));
      } else {
        setState(s => ({ ...s, riskIdx: nextIdx }));
      }
    }
  };

  const handleRestart = () => {
    if (!confirm('¿Empezar de cero? Se van a borrar los datos cargados.')) return;
    localStorage.removeItem(STORAGE_KEY);
    setState({ phase: 'welcome', data: {}, stepIdx: 0, riskIdx: 0, risk: null });
    setError(null);
  };

  // Sube un archivo individual a S3 y devuelve sus metadatos
  const uploadFileFn = async (file) => {
    const formData = new FormData();
    formData.append('files', file);
    const res = await fetch(`${API_BASE}/api/upload`, { method: 'POST', body: formData });
    if (!res.ok) throw new Error('Error al subir archivo.');
    const { files: uploaded } = await res.json();
    return uploaded[0]; // { key, name, url, size }
  };

  const handleSubmit = async () => {
    setSubmitting(true);
    setError(null);
    try {
      // Los archivos ya fueron subidos paso a paso — sólo guardamos en MongoDB
      // Se guarda como dict {fieldId: [files]} para poder mostrarlos inline en /c/:id
      const archivos = {};
      Object.entries(state.data).forEach(([fieldId, v]) => {
        if (Array.isArray(v) && v.length && v[0] && v[0].key) archivos[fieldId] = v;
        else if (v && v.key) archivos[fieldId] = [v];
      });

      const saveRes = await fetch(`${API_BASE}/api/cotizacion`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          data: state.data,
          risk: state.risk,
          archivos,
          resumenTexto: buildTextSummary(state.data, state.risk),
        }),
      });
      if (!saveRes.ok) throw new Error('Error al guardar la cotización.');
      const saveData = await saveRes.json();
      setCotizacionId(saveData.id);
      setState(s => ({ ...s, phase: 'success' }));
    } catch (err) {
      console.error('[handleSubmit]', err);
      setError('Hubo un error al enviar. Verificá tu conexión e intentá de nuevo.');
    } finally {
      setSubmitting(false);
    }
  };

  const handleWhatsapp = () => {
    const link = cotizacionId
      ? `${window.location.origin}/c/${cotizacionId}`
      : window.location.origin;
    const text = `Hola! Ya completé mi solicitud de cotización en A1 Broker 🛡️\nPodés verla acá: ${link}`;
    const url = `https://wa.me/${waNumber}?text=${encodeURIComponent(text)}`;
    window.open(url, '_blank');
  };

  const handleCorrect = () => {
    setState(s => ({ ...s, phase: 'personal', stepIdx: 0, riskIdx: 0 }));
    setError(null);
  };

  // ─── Render ───────────────────────────────────────────────
  const renderContent = () => {
    if (state.phase === 'welcome') {
      return <WelcomeScreen onStart={handleStart} />;
    }

    if (state.phase === 'success') {
      const risk = RISK_CATEGORIES.find(r => r.value === state.risk);
      return (
        <div className="app">
          <SuccessScreen
            data={state.data}
            riskLabel={risk ? risk.label : state.risk}
            cotizacionId={cotizacionId}
            onRestart={handleRestart}
            onCorrect={handleCorrect}
            onOpenWhatsapp={handleWhatsapp}
          />
        </div>
      );
    }

    // Personal + risk-pick + risk-form + summary share AppBar
    return (
      <div className="app">
        <AppBar
          onBack={handleBack}
          step={currentOverallIdx}
          total={totalSteps}
          onRestart={handleRestart}
        />
        {state.phase === 'personal' && renderPersonal()}
        {state.phase === 'risk-pick' && renderRiskPick()}
        {state.phase === 'risk-form' && renderRiskForm()}
        {state.phase === 'summary' && renderSummary()}
      </div>
    );
  };

  const renderPersonal = () => {
    const step = PERSONAL_STEPS[state.stepIdx];
    return (
      <Screen footer={
        <PrimaryButton onClick={handleNext} icon={
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style={{ marginLeft: 4 }}>
            <path d="M5 12h14M13 6l6 6-6 6" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        }>Siguiente</PrimaryButton>
      }>
        <QHeader eyebrow={`Datos personales · ${state.stepIdx + 1}/${PERSONAL_STEPS.length}`}
          title={step.title} subtitle={step.subtitle} />
        <StepRenderer key={`personal-${state.stepIdx}`} step={step} data={state.data} setField={setField} error={error} uploadFn={uploadFileFn} />
      </Screen>
    );
  };

  const renderRiskPick = () => {
    return (
      <Screen footer={
        <PrimaryButton onClick={handleNext} disabled={!state.risk} icon={
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style={{ marginLeft: 4 }}>
            <path d="M5 12h14M13 6l6 6-6 6" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        }>Siguiente</PrimaryButton>
      }>
        <QHeader eyebrow="Tipo de seguro"
          title="¿Qué querés cotizar?"
          subtitle="Elegí una sola categoría. Después te hacemos las preguntas específicas de ese riesgo." />
        <RiskCategoryGrid value={state.risk}
          onChange={(v) => { setState(s => ({ ...s, risk: v })); setError(null); }}
          options={RISK_CATEGORIES} />
        {error && (
          <div style={{ marginTop: 12, fontSize: 13, color: 'var(--err)', textAlign: 'center' }}>
            {error}
          </div>
        )}
      </Screen>
    );
  };

  const renderRiskForm = () => {
    const flow = RISK_FLOWS[state.risk] || [];
    const step = flow[state.riskIdx];
    if (!step) return null;
    const visible = flow.filter(s => !s.showIf || s.showIf(state.data));
    const visIdx = visible.findIndex(s => s.id === step.id);
    const isLast = visIdx === visible.length - 1;
    const risk = RISK_CATEGORIES.find(r => r.value === state.risk);
    return (
      <Screen footer={
        <div style={{ display: 'flex', gap: 10 }}>
          {step.optional && (
            <button onClick={() => { setError(null); handleNextSkip(); }}
              style={{
                padding: '16px 20px', background: 'transparent',
                color: 'var(--ink-500)', fontWeight: 600, fontSize: 14,
                border: '1.5px solid var(--ink-200)', borderRadius: 14,
              }}>
              Saltear
            </button>
          )}
          <div style={{ flex: 1 }}>
            <PrimaryButton onClick={handleNext} icon={
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style={{ marginLeft: 4 }}>
                <path d="M5 12h14M13 6l6 6-6 6" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            }>{isLast ? 'Ver resumen' : 'Siguiente'}</PrimaryButton>
          </div>
        </div>
      }>
        <QHeader eyebrow={`${risk ? risk.icon + ' ' + risk.label : ''} · ${visIdx + 1}/${visible.length}`}
          title={step.title} subtitle={step.subtitle} />
        <StepRenderer key={`risk-${state.risk}-${state.riskIdx}`} step={step} data={state.data} setField={setField} error={error} uploadFn={uploadFileFn} />
      </Screen>
    );
  };

  // For optional skip button — jumps forward without validating
  const handleNextSkip = () => {
    if (state.phase !== 'risk-form') return handleNext();
    const flow = RISK_FLOWS[state.risk] || [];
    let nextIdx = state.riskIdx + 1;
    while (nextIdx < flow.length && flow[nextIdx].showIf && !flow[nextIdx].showIf(state.data)) nextIdx++;
    if (nextIdx >= flow.length) setState(s => ({ ...s, phase: 'summary' }));
    else setState(s => ({ ...s, riskIdx: nextIdx }));
  };

  const renderSummary = () => {
    const personalRows = PERSONAL_STEPS
      .map(s => [PERSONAL_LABELS[s.id] || s.id, fmt(s, state.data[s.id])]);
    const riskFlow = RISK_FLOWS[state.risk] || [];
    const riskRows = riskFlow
      .filter(s => !s.showIf || s.showIf(state.data))
      .map(s => [s.title, fmt(s, state.data[s.id])]);
    const risk = RISK_CATEGORIES.find(r => r.value === state.risk);
    const premium = Array.isArray(state.data.descuento) && state.data.descuento.length > 0;

    return (
      <Screen footer={
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <PrimaryButton onClick={handleSubmit} disabled={submitting} icon={
            submitting ? null : (
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style={{ marginLeft: 4 }}>
                <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            )
          }>{submitting ? 'Enviando…' : 'Enviar solicitud'}</PrimaryButton>
          {error && (
            <div style={{ textAlign: 'center', fontSize: 13, color: 'var(--err)' }}>{error}</div>
          )}
        </div>
      }>
        <QHeader eyebrow="Últimos pasos"
          title="Revisá tus datos"
          subtitle="Si está todo bien, tocá 'Enviar solicitud' y te contactamos en breve." />

        {premium && (
          <div style={{ marginBottom: 14 }}>
            <Banner tone="success" icon="🎁">
              <strong>¡Sumaste 5% OFF!</strong> Tu lead entra como PREMIUM por adjuntar documentación.
            </Banner>
          </div>
        )}

        <div style={{
          padding: 14, borderRadius: 14, marginBottom: 14,
          background: 'var(--brand-50)', border: '1px solid var(--brand-100)',
          display: 'flex', gap: 12, alignItems: 'center',
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12,
            background: 'var(--brand-600)', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 22, flexShrink: 0,
          }}>{risk ? risk.icon : '🛡️'}</div>
          <div>
            <div style={{ fontSize: 11, color: 'var(--brand-700)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              Cotizando
            </div>
            <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--ink-900)' }}>
              {risk ? risk.label : state.risk}
            </div>
          </div>
        </div>

        <SummarySection title="Datos personales" rows={personalRows} />
        <SummarySection title={`Detalles de ${risk ? risk.label : 'riesgo'}`} rows={riskRows} />

        <div style={{ fontSize: 11.5, color: 'var(--ink-400)', textAlign: 'center', marginTop: 4 }}>
          Tus datos se envían de forma segura a A1 Broker.
        </div>
      </Screen>
    );
  };

  // Desktop / responsive shell
  return (
    <div className="app-shell">
      <div className="app-content">
        {renderContent()}
      </div>
      {tweaksOpen && <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
