// DETALLE de vehículo — galería de fotos (o 360° fallback), ficha técnica, calculadora de cuotas
const DetailScreen = ({ vehicleId, onBack, onNav, onSelectVehicle }) => {
  const v = window.OMEGA_HELPERS.byId(vehicleId);
  const { fmtPrice, fmtPrecio, fmtKm } = window.OMEGA_HELPERS;
  const { vehicles } = window.OMEGA_DATA;

  const hasPhotos = v && v.photos && v.photos.length > 0;

  // Galería de fotos
  const [activePhoto, setActivePhoto] = useState(0);
  const [lightbox, setLightbox] = useState(false);

  // 360 viewer (fallback)
  const [rotation, setRotation] = useState(0);
  const [auto360, setAuto360] = useState(true);
  const dragRef = useRef({ active: false, startX: 0, startRot: 0 });
  useEffect(() => {
    if (hasPhotos || !auto360) return;
    let raf;
    let last = performance.now();
    const tick = (t) => {
      const dt = t - last; last = t;
      setRotation(r => (r + dt * 0.04) % 360);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [auto360, hasPhotos]);

  const onDown = (e) => {
    setAuto360(false);
    const x = (e.touches ? e.touches[0].clientX : e.clientX);
    dragRef.current = { active: true, startX: x, startRot: rotation };
  };
  const onMove = (e) => {
    if (!dragRef.current.active) return;
    const x = (e.touches ? e.touches[0].clientX : e.clientX);
    const dx = x - dragRef.current.startX;
    setRotation(((dragRef.current.startRot + dx * 0.6) % 360 + 360) % 360);
  };
  const onUp = () => { dragRef.current.active = false; };
  useEffect(() => {
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchmove', onMove);
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('touchend', onUp);
    };
  }, []);

  // Lightbox keyboard
  useEffect(() => {
    if (!lightbox) return;
    const onKey = (e) => {
      if (e.key === 'Escape') setLightbox(false);
      if (e.key === 'ArrowRight') setActivePhoto(p => (p+1) % v.photos.length);
      if (e.key === 'ArrowLeft') setActivePhoto(p => (p-1+v.photos.length) % v.photos.length);
    };
    document.body.style.overflow = 'hidden';
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onKey); };
  }, [lightbox, v]);

  // Calculadora de cuotas
  const [calc, setCalc] = useState({ anticipoPct: 30, plazo: 36 });
  const tnaAnual = 0.42; // 42% TNA estimada
  const result = useMemo(() => {
    if (!v) return null;
    const total = v.precio;
    const anticipo = Math.round(total * (calc.anticipoPct / 100));
    const capital = total - anticipo;
    const i = tnaAnual / 12;
    const n = calc.plazo;
    const cuota = capital * (i * Math.pow(1+i, n)) / (Math.pow(1+i, n) - 1);
    return { anticipo, capital, cuota: Math.round(cuota), total: Math.round(cuota * n) + anticipo };
  }, [v, calc]);

  if (!v) return <div style={{padding:120, textAlign:'center'}}>Vehículo no encontrado. <button className="btn" onClick={onBack}>Volver</button></div>;

  const related = vehicles.filter(x => x.carroceria === v.carroceria && x.id !== v.id).slice(0,3);

  return (
    <main className="detail-root">
      {/* Breadcrumb */}
      <div className="container detail-crumb">
        <button className="crumb-link mono" onClick={()=>onNav('home')}>Inicio</button>
        <span>/</span>
        <button className="crumb-link mono" onClick={()=>onNav('catalogo')}>Catálogo</button>
        <span>/</span>
        <span className="mono" style={{color:'var(--ink)'}}>{v.marca} · {v.modelo}</span>
      </div>

      <div className="container detail-top">
        {/* IZQUIERDA: galería de fotos o 360 fallback */}
        <div className="detail-visual">
          {hasPhotos ? (
            <React.Fragment>
              <div className="photo-main" onClick={() => setLightbox(true)}>
                <img src={v.photos[activePhoto]} alt={`${v.marca} ${v.modelo}`} key={activePhoto}/>
                <div className="photo-main-overlay">
                  <div className="photo-counter mono">{activePhoto + 1} / {v.photos.length}</div>
                  <div className="photo-zoom-hint mono">Click para ampliar</div>
                </div>
                {v.photos.length > 1 && (
                  <React.Fragment>
                    <button className="photo-nav photo-nav-prev" onClick={(e)=>{e.stopPropagation(); setActivePhoto(p=>(p-1+v.photos.length)%v.photos.length);}} aria-label="Anterior">‹</button>
                    <button className="photo-nav photo-nav-next" onClick={(e)=>{e.stopPropagation(); setActivePhoto(p=>(p+1)%v.photos.length);}} aria-label="Siguiente">›</button>
                  </React.Fragment>
                )}
              </div>
              <div className="photo-thumbs">
                {v.photos.map((p, i) => (
                  <button key={i} className={`photo-thumb ${i===activePhoto?'on':''}`} onClick={()=>setActivePhoto(i)}>
                    <img src={p} alt={`Foto ${i+1}`} loading="lazy"/>
                  </button>
                ))}
              </div>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <div className="viewer-360"
                   onMouseDown={onDown} onTouchStart={onDown}
                   style={{cursor: dragRef.current.active ? 'grabbing' : 'grab'}}>
                <CarPlaceholder label={`${v.marca} ${v.modelo} · ${v.color}`} rotation={rotation} accent="var(--accent)"/>
                <div className="viewer-overlay">
                  <div className="viewer-360-tag">
                    <Icon.Rotate width="14" height="14"/> 360° · arrastr&aacute; para girar
                  </div>
                  <div className="viewer-progress">
                    <div className="viewer-progress-bar" style={{width:`${(rotation/360)*100}%`}}/>
                  </div>
                </div>
                <div className="viewer-tag mono">{Math.round(rotation)}°</div>
              </div>
              <div className="thumb-row">
                {['EXTERIOR','INTERIOR','MOTOR','BAÚL','DETALLES','TABLERO'].map((t,i) => (
                  <div key={t} className={`thumb ${i===0?'on':''}`}>
                    <CarPlaceholder/>
                    <span className="thumb-label mono">{t}</span>
                  </div>
                ))}
              </div>
            </React.Fragment>
          )}
        </div>

        {/* DERECHA: precio, ficha, CTA */}
        <aside className="detail-meta">
          {v.tag && <div className={`vcard-tag ${v.tag==='PREMIUM'||v.tag==='COLECCIÓN' ? 'gold' : 'accent'}`} style={{position:'static', display:'inline-block', marginBottom:18}}>{v.tag}</div>}
          <div className="eyebrow">{v.anio} · {v.carroceria} · {v.color}</div>
          <h1 className="display-md" style={{margin:'10px 0 4px', fontSize:48}}>{v.marca}</h1>
          <div className="serif italic" style={{fontSize:24, color:'var(--ink-dim)', marginBottom:24}}>{v.modelo}</div>

          <div className="price-box">
            <div className="eyebrow">Precio público</div>
            <div className="price-large">{fmtPrecio(v)}</div>
            <div style={{color:'var(--ink-mute)', fontSize:13, marginTop:6}}>Acept&aacute; canje · financiación a medida · gestoría incluida</div>
          </div>

          <div className="quick-specs">
            <div className="qs"><div className="qs-l mono">AÑO</div><div className="qs-v">{v.anio}</div></div>
            <div className="qs"><div className="qs-l mono">KM</div><div className="qs-v">{fmtKm(v.km)}</div></div>
            <div className="qs"><div className="qs-l mono">COMBUSTIBLE</div><div className="qs-v">{v.combustible}</div></div>
            <div className="qs"><div className="qs-l mono">TRANSMISIÓN</div><div className="qs-v">{v.transmision}</div></div>
          </div>

          <div style={{display:'flex', flexDirection:'column', gap:10, marginTop:28}}>
            <a className="btn btn-accent btn-lg btn-block" href={`https://wa.me/${window.OMEGA_CONFIG.whatsapp}?text=${encodeURIComponent('Hola OMEGA, me interesa ' + v.marca + ' ' + v.modelo + ' (' + v.anio + ') — ' + window.OMEGA_HELPERS.fmtPrecio(v))}`} target="_blank">
              <Icon.Whatsapp width="14" height="14"/> Consultar por WhatsApp
            </a>
            <button className="btn btn-block">Reservar visita en showroom</button>
          </div>

          <div className="trust-row">
            <div className="trust"><Icon.Check width="14" height="14"/> Inspección 142 pts</div>
            <div className="trust"><Icon.Check width="14" height="14"/> Historial verificado</div>
            <div className="trust"><Icon.Check width="14" height="14"/> Gestoría incluida</div>
          </div>
        </aside>
      </div>

      {/* CALCULADORA DE CUOTAS */}
      <section className="detail-calc">
        <div className="container">
          <div className="calc-grid">
            <div>
              <div className="eyebrow">Financiación en vivo</div>
              <h2 className="display-md" style={{marginTop:10}}>Calcul&aacute; tu cuota.</h2>
              <p style={{color:'var(--ink-dim)', maxWidth:420, marginTop:12}}>Movimientos los slider y vé el resultado al instante. TNA estimada {Math.round(tnaAnual*100)}% — sujeta a aprobación.</p>
            </div>

            <div className="calc-controls">
              <div className="field" style={{marginBottom:32}}>
                <div className="calc-row">
                  <label className="field-label">Anticipo · {calc.anticipoPct}%</label>
                  <span className="mono" style={{color:'var(--ink)'}}>{fmtPrice(result.anticipo)}</span>
                </div>
                <input type="range" min="20" max="80" step="5" value={calc.anticipoPct}
                       onChange={e=>setCalc({...calc, anticipoPct:+e.target.value})}
                       className="range-input"/>
              </div>
              <div className="field">
                <div className="calc-row">
                  <label className="field-label">Plazo</label>
                  <span className="mono" style={{color:'var(--ink)'}}>{calc.plazo} cuotas</span>
                </div>
                <input type="range" min="12" max="60" step="6" value={calc.plazo}
                       onChange={e=>setCalc({...calc, plazo:+e.target.value})}
                       className="range-input"/>
              </div>
            </div>

            <div className="calc-result">
              <div className="eyebrow">Cuota mensual estimada</div>
              <div className="calc-cuota">
                <span className="calc-cuota-n">{fmtPrice(result.cuota)}</span>
              </div>
              <div className="calc-breakdown">
                <div className="cb-row"><span>Anticipo</span><span className="mono">{fmtPrice(result.anticipo)}</span></div>
                <div className="cb-row"><span>Capital a financiar</span><span className="mono">{fmtPrice(result.capital)}</span></div>
                <div className="cb-row"><span>Plazo</span><span className="mono">{calc.plazo} meses</span></div>
                <div className="cb-row total"><span>Total con intereses</span><span className="mono">{fmtPrice(result.total)}</span></div>
              </div>
              <button className="btn btn-accent btn-block" style={{marginTop:24}}>Pre-aprobar mi crédito</button>
            </div>
          </div>
        </div>
      </section>

      {/* FICHA TÉCNICA */}
      <section className="detail-specs">
        <div className="container">
          <div className="eyebrow">Ficha técnica completa</div>
          <h2 className="display-md" style={{marginTop:10, marginBottom:40}}>Especificaciones.</h2>
          <div className="specs-grid">
            <SpecBlock title="Identificación" rows={[
              ['Marca', v.marca], ['Modelo', v.modelo], ['Año', v.anio], ['Carrocería', v.carroceria], ['Color', v.color]
            ]}/>
            <SpecBlock title="Mecánica" rows={[
              ['Combustible', v.combustible], ['Transmisión', v.transmision], ['Tracción', v.carroceria==='Pickup'||v.modelo.includes('4x4')?'4x4':'Delantera'], ['Cilindrada', v.modelo.match(/\d\.\d/)?.[0] || '2.0'+'L'], ['Potencia (est.)', '170 CV']
            ]}/>
            <SpecBlock title="Estado" rows={[
              ['Kilometraje', fmtKm(v.km)], ['Inspección OMEGA', '142/142 aprobados'], ['Service oficial', 'Al día'], ['Documentación', 'Lista p/transferir'], ['Garantía', '3 meses · 5.000 km']
            ]}/>
            <SpecBlock title="Equipamiento" rows={[
              ['Airbags', '6'], ['ABS + ESP', 'Sí'], ['Climatizador', 'Bizona'], ['Multimedia', 'Pantalla 8" + CarPlay'], ['Cámara trasera', 'Sí']
            ]}/>
          </div>
        </div>
      </section>

      {/* RELACIONADOS */}
      {related.length > 0 && (
        <section className="section-block">
          <div className="container">
            <div className="section-head">
              <div>
                <div className="eyebrow">Te puede interesar</div>
                <h2 className="display-md" style={{marginTop:8}}>Otras unidades {v.carroceria}.</h2>
              </div>
              <button className="btn" onClick={()=>onNav('catalogo')}>Ver todas <Icon.Arrow width="14" height="14"/></button>
            </div>
            <div className="grid-vehicles grid-vehicles-3">
              {related.map(rv => <VehicleCard key={rv.id} v={rv} onClick={onSelectVehicle}/>)}
            </div>
          </div>
        </section>
      )}

      {/* LIGHTBOX */}
      {lightbox && hasPhotos && (
        <div className="lightbox" onClick={()=>setLightbox(false)}>
          <button className="lightbox-close" onClick={()=>setLightbox(false)} aria-label="Cerrar">
            <Icon.X width="24" height="24"/>
          </button>
          <button className="lightbox-nav lightbox-prev" onClick={(e)=>{e.stopPropagation(); setActivePhoto(p=>(p-1+v.photos.length)%v.photos.length);}}>‹</button>
          <img src={v.photos[activePhoto]} alt={`${v.marca} ${v.modelo}`} onClick={(e)=>e.stopPropagation()}/>
          <button className="lightbox-nav lightbox-next" onClick={(e)=>{e.stopPropagation(); setActivePhoto(p=>(p+1)%v.photos.length);}}>›</button>
          <div className="lightbox-counter mono">{activePhoto+1} / {v.photos.length}</div>
        </div>
      )}
    </main>
  );
};

const SpecBlock = ({ title, rows }) => (
  <div className="spec-block">
    <h4 className="spec-block-title serif">{title}</h4>
    <dl className="spec-list">
      {rows.map(([k,vv],i) => (
        <div className="spec-row" key={i}>
          <dt className="mono">{k}</dt>
          <dd>{vv}</dd>
        </div>
      ))}
    </dl>
  </div>
);

Object.assign(window, { DetailScreen });
