// ========== ProductDetailModal — datos detallados de un producto ==========
// Recibe { product, company } y renderiza un modal con todo lo que el
// catálogo tenga en product.detail. Si un campo no está, simplemente
// no se renderiza (graceful degradation).

function ProductDetailModal({ open, onClose, product, company }) {
  if (!open || !product) return null;

  const d = product.detail || {};
  const ramo = product.ramo;

  return (
    <div
      onClick={onClose}
      style={{ position:'fixed', inset:0, background:'rgba(8,12,24,0.7)', display:'grid', placeItems:'center', padding:20, zIndex:6000, overflow:'auto' }}>
      <div
        onClick={e=>e.stopPropagation()}
        style={{ width:'min(720px,100%)', background:'#fff', borderRadius:20, overflow:'hidden', maxHeight:'90vh', display:'flex', flexDirection:'column', boxShadow:'0 30px 80px -20px rgba(0,0,0,0.45)' }}>

        {/* Header */}
        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', gap:14, flexShrink:0 }}>
          <CompanyLogo company={company} size={56}/>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:11, color:'var(--muted)', fontFamily:'JetBrains Mono, monospace', letterSpacing:'0.06em', textTransform:'uppercase' }}>{company.name} · {ramo.toUpperCase()}</div>
            <div style={{ fontWeight:800, fontSize:20, letterSpacing:'-0.02em', marginTop:2, display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
              {product.nombre}
              {d.verified && (
                <span style={{ fontSize:10, background:'#1A7A42', color:'#fff', padding:'3px 8px', borderRadius:6, fontFamily:'JetBrains Mono, monospace', letterSpacing:'0.04em', fontWeight:700 }}>
                  ✓ VERIFICADO
                </span>
              )}
            </div>
            {product.desc && <div style={{ fontSize:13, color:'var(--ink-2)', marginTop:3 }}>{product.desc}</div>}
            {d.verified && window.HOLAI_VERIFIED_AT && (
              <div style={{ fontSize:10, color:'var(--muted)', marginTop:4, fontFamily:'JetBrains Mono, monospace' }}>
                URL VERIFICADA AL {window.HOLAI_VERIFIED_AT}
              </div>
            )}
          </div>
          <button onClick={onClose} aria-label="Cerrar"
            style={{ background:'var(--bg-warm)', border:0, borderRadius:'50%', width:32, height:32, cursor:'pointer', fontSize:20, lineHeight:1, color:'var(--ink-2)' }}>×</button>
        </div>

        {/* Body scrollable */}
        <div style={{ overflow:'auto', padding:'20px 24px', flex:1 }}>

          {/* Precio destacado */}
          {product.desde && (
            <div style={{ display:'flex', alignItems:'baseline', gap:10, marginBottom:18 }}>
              <span style={{ fontSize:11, fontFamily:'JetBrains Mono, monospace', color:'var(--muted)', letterSpacing:'0.06em' }}>DESDE</span>
              <span style={{ fontSize:28, fontWeight:800, letterSpacing:'-0.03em' }}>${product.desde.toLocaleString('es-CL')}</span>
              <span style={{ fontSize:13, color:'var(--muted)' }}>/ {product.unit}</span>
            </div>
          )}

          {/* Sección: Capital / Cobertura */}
          {(d.capital || d.coberturas || d.coberturasIncluidas || d.deducible) && (
            <Section title="Capital y cobertura" ico="shield">
              {d.capital && (
                <Field label="Capital asegurado"
                  value={d.capital.label ||
                    (d.capital.min && d.capital.max
                      ? `${d.capital.unit || ''} ${d.capital.min.toLocaleString('es-CL')} a ${d.capital.max.toLocaleString('es-CL')}`
                      : d.capital.min
                        ? `Desde ${d.capital.unit || ''} ${d.capital.min.toLocaleString('es-CL')}`
                        : '—')}/>
              )}
              {Array.isArray(d.coberturas) && d.coberturas.length > 0 && (
                <Field label="Coberturas" value={<TagList items={d.coberturas}/>}/>
              )}
              {Array.isArray(d.coberturasIncluidas) && d.coberturasIncluidas.length > 0 && (
                <Field label="Incluye" value={<TagList items={d.coberturasIncluidas}/>}/>
              )}
              {d.deducible && (
                <Field label="Deducible" value={`${d.deducible.monto}${d.deducible.unit || ''} (${d.deducible.tipo})`}/>
              )}
            </Section>
          )}

          {/* Sección: Económicos (ahorro / apv / rentas) */}
          {(d.tasaGarantizada !== undefined || d.rentabilidadHist !== undefined ||
            d.comisionAnual !== undefined || d.aporteMinimo || d.regimenAPV ||
            d.modalidades || d.beneficiarios || d.costoCobertura || d.gastoAsegurador ||
            d.beneficiosAdicionales) && (
            <Section title="Datos económicos" ico="trend">
              {typeof d.tasaGarantizada === 'number' && (
                <Field label="Tasa garantizada"
                  value={<span><strong>{(d.tasaGarantizada * 100).toFixed(2)}%</strong> anual {d.moneda === 'UF' ? 'en UF' : ''}</span>}
                  hint="Mínimo garantizado por la compañía"/>
              )}
              {typeof d.rentabilidadHist === 'number' && (
                <Field label="Rentabilidad histórica"
                  value={<span><strong>{(d.rentabilidadHist * 100).toFixed(2)}%</strong> anual promedio</span>}
                  hint="Histórico — no garantiza retornos futuros"/>
              )}
              {d.costoCobertura && (
                <Field label="Costo de cobertura"
                  value={d.costoCobertura.label || (typeof d.costoCobertura.pct === 'number' ? `${(d.costoCobertura.pct*100).toFixed(1)}% de la prima` : '—')}
                  hint="Parte de la prima que financia la cobertura por fallecimiento"/>
              )}
              {d.gastoAsegurador && (
                <Field label="Gasto asegurador"
                  value={d.gastoAsegurador.label || (typeof d.gastoAsegurador.pct === 'number' ? `${(d.gastoAsegurador.pct*100).toFixed(2)}% anual` : '—')}
                  hint="Cargo de administración sobre el saldo acumulado"/>
              )}
              {Array.isArray(d.beneficiosAdicionales) && d.beneficiosAdicionales.length > 0 && (
                <Field label="Beneficios adicionales" value={<TagList items={d.beneficiosAdicionales}/>}/>
              )}
              {typeof d.comisionAnual === 'number' && (
                <Field label="Comisión anual" value={`${(d.comisionAnual * 100).toFixed(2)}% sobre saldo`}/>
              )}
              {d.regimenAPV && (
                <Field label="Régimen APV" value={d.regimenAPV} hint="A: bonificación fiscal · B: rebaja tributaria"/>
              )}
              {d.aporteMinimo && (
                <Field label="Aporte mínimo"
                  value={`${d.aporteMinimo.unit || ''} ${(d.aporteMinimo.monto || '').toLocaleString?.('es-CL') || d.aporteMinimo.monto} ${d.aporteMinimo.periodicidad ? '· ' + d.aporteMinimo.periodicidad : ''}`}/>
              )}
              {Array.isArray(d.modalidades) && d.modalidades.length > 0 && (
                <Field label="Modalidades" value={<TagList items={d.modalidades}/>}/>
              )}
              {d.beneficiarios && (
                <Field label="Beneficiarios / reversión" value={d.beneficiarios}/>
              )}
            </Section>
          )}

          {/* Sección: Edades */}
          {(d.edadIngresoMin || d.edadIngresoMax || d.edadPermanencia) && (
            <Section title="Edades" ico="user">
              {(d.edadIngresoMin || d.edadIngresoMax) && (
                <Field label="Edad de ingreso"
                  value={`${d.edadIngresoMin || 0}${d.edadIngresoMax ? ` a ${d.edadIngresoMax}` : '+'} años`}/>
              )}
              {d.edadPermanencia && (
                <Field label="Permanencia máxima"
                  value={d.edadPermanencia === 'vitalicio' ? 'Vitalicia' : `Hasta los ${d.edadPermanencia} años`}/>
              )}
            </Section>
          )}

          {/* Sección: Salud (Isapres / complementarios) */}
          {(d.copagoAmbulatorio !== undefined || d.copagoHospital !== undefined ||
            d.redPrestadores || d.topeAnual || d.maternidadCubierta !== undefined) && (
            <Section title="Cobertura de salud" ico="heart">
              {typeof d.copagoAmbulatorio === 'number' && (
                <Field label="Cobertura ambulatoria" value={`${Math.round(d.copagoAmbulatorio * 100)}%`}/>
              )}
              {typeof d.copagoHospital === 'number' && (
                <Field label="Cobertura hospitalaria" value={`${Math.round(d.copagoHospital * 100)}%`}/>
              )}
              {d.redPrestadores && (
                <Field label="Red de prestadores"
                  value={d.redPrestadores === 'cerrada' ? 'Cerrada (solo red propia)'
                    : d.redPrestadores === 'preferente' ? 'Preferente (mejor copago en red)'
                    : 'Libre elección'}/>
              )}
              {d.topeAnual && d.topeAnual.monto && (
                <Field label="Tope anual" value={`${d.topeAnual.unit || ''} ${d.topeAnual.monto.toLocaleString('es-CL')}`}/>
              )}
              {typeof d.maternidadCubierta === 'boolean' && (
                <Field label="Maternidad" value={d.maternidadCubierta ? '✓ Cubierta' : '✗ Sin cobertura'}/>
              )}
            </Section>
          )}

          {/* Sección: Condiciones */}
          {(typeof d.carenciaMeses === 'number' || d.examenesMedicos || d.preexistencias) && (
            <Section title="Condiciones de suscripción" ico="file">
              {typeof d.carenciaMeses === 'number' && (
                <Field label="Carencia" value={d.carenciaMeses === 0 ? 'Sin carencia' : `${d.carenciaMeses} meses`}/>
              )}
              {d.examenesMedicos && (
                <Field label="Exámenes médicos" value={d.examenesMedicos}/>
              )}
              {d.preexistencias && (
                <Field label="Preexistencias" value={d.preexistencias}/>
              )}
            </Section>
          )}

          {/* Notas / disclaimers */}
          {Array.isArray(d.notas) && d.notas.length > 0 && (
            <Section title="Importante" ico="bell" tone="warn">
              <ul style={{ margin:0, paddingLeft:18, fontSize:13, color:'var(--ink-2)', lineHeight:1.6 }}>
                {d.notas.map((n, i) => <li key={i}>{n}</li>)}
              </ul>
            </Section>
          )}

          {/* Si no hay detalle */}
          {!product.detail && (
            <div style={{ padding:'24px 0', textAlign:'center', color:'var(--muted)', fontSize:14 }}>
              Aún no tenemos datos detallados de este producto. Consultá en <a href={company.url} target="_blank" rel="noopener noreferrer" style={{ color:'var(--accent)', fontWeight:600 }}>{company.name}</a>.
            </div>
          )}

          {/* Banner de datos referenciales (siempre visible salvo si verified) */}
          {!d.verified && (
            <div style={{
              marginTop:14, padding:'10px 14px', background:'rgba(255,216,77,0.14)',
              border:'1px solid rgba(255,216,77,0.45)', borderRadius:10,
              fontSize:11.5, color:'#8C6B16', lineHeight:1.55,
            }}>
              <strong>⚠ Datos referenciales.</strong> Los valores numéricos (capital, tasas, edades, primas) son <strong>rangos típicos del mercado chileno</strong>, no están scrapeados del sitio oficial. Para precios, condiciones y vigencia exactos, cotizá directo en {company.name}.
            </div>
          )}
        </div>

        {/* Footer: links a folleto y sitio */}
        <div style={{ padding:'16px 24px', borderTop:'1px solid var(--line)', display:'flex', gap:10, flexWrap:'wrap', flexShrink:0, alignItems:'center' }}>
          <CompareToggleButton company={company} product={product}/>
          {d.brochureUrl && (
            <a href={d.brochureUrl} target="_blank" rel="noopener noreferrer"
              className="btn btn-outline btn-sm" style={{ textDecoration:'none' }}>
              <I.file size={14}/> Folleto / CGC
            </a>
          )}
          {d.cmfUrl && (
            <a href={d.cmfUrl} target="_blank" rel="noopener noreferrer"
              className="btn btn-outline btn-sm" style={{ textDecoration:'none' }}>
              <I.shield size={14}/> Póliza en CMF
            </a>
          )}
          <a href={d.productoUrl || company.url} target="_blank" rel="noopener noreferrer"
            style={{
              flex:1, minWidth:200, padding:'10px 16px', textDecoration:'none', textAlign:'center',
              background: company.brand?.bg || 'var(--ink)',
              color:      company.brand?.txt || '#fff',
              borderRadius:10, fontSize:13, fontWeight:700,
            }}>
            Cotizar en {company.name} →
          </a>
        </div>
      </div>
    </div>
  );
}

// ── Subcomponentes ──────────────────────────────────────────────────────────

function Section({ title, ico, tone, children }) {
  const IconCmp = ico && I[ico];
  const bg = tone === 'warn' ? 'rgba(255,216,77,0.12)' : 'transparent';
  const border = tone === 'warn' ? '1px solid rgba(255,216,77,0.45)' : '1px solid var(--line)';
  return (
    <div style={{ background:bg, border, borderRadius:12, padding:'14px 16px', marginBottom:12 }}>
      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10 }}>
        {IconCmp && <IconCmp size={14}/>}
        <div className="eyebrow" style={{ fontSize:10 }}>{title}</div>
      </div>
      {children}
    </div>
  );
}

function Field({ label, value, hint }) {
  return (
    <div style={{ display:'grid', gridTemplateColumns:'140px 1fr', gap:12, padding:'6px 0', alignItems:'baseline', fontSize:13 }}>
      <div style={{ color:'var(--muted)', fontFamily:'JetBrains Mono, monospace', fontSize:11, letterSpacing:'0.04em', textTransform:'uppercase' }}>{label}</div>
      <div>
        <div style={{ color:'var(--ink)', fontWeight:600 }}>{value}</div>
        {hint && <div style={{ fontSize:11, color:'var(--muted)', marginTop:2 }}>{hint}</div>}
      </div>
    </div>
  );
}

function TagList({ items }) {
  return (
    <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
      {items.map((it, i) => (
        <span key={i} style={{
          fontSize:11, padding:'3px 10px', borderRadius:999,
          background:'var(--bg-warm)', color:'var(--ink-2)', fontWeight:600,
        }}>{it}</span>
      ))}
    </div>
  );
}

window.ProductDetailModal = ProductDetailModal;
