// Componentes compartidos: Header, Footer, VehicleCard, WhatsApp, placeholder de auto
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// --- ICONOS (SVG inline) ---
const Icon = {
  Arrow: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  ArrowDown: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 5v14M5 13l7 7 7-7"/></svg>,
  Search: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.5-4.5"/></svg>,
  Whatsapp: (p) => <svg {...p} viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1-.2.3-.7.9-.9 1.1-.2.2-.3.2-.6.1-1.6-.8-2.7-1.4-3.7-3.2-.3-.5.3-.5.8-1.5.1-.2 0-.4 0-.5s-.7-1.6-.9-2.2c-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1 2.9 1.2 3.1c.1.2 2.1 3.2 5.1 4.5 1.9.8 2.6.9 3.5.7.6-.1 1.7-.7 2-1.4.2-.7.2-1.2.2-1.4-.1-.1-.3-.2-.6-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.2-1.3c1.4.8 3.1 1.3 4.8 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2zm5.8 14.5c-.2.7-1.3 1.3-1.9 1.4-.5.1-1.1.1-1.8-.1-.4-.1-.9-.3-1.6-.6-2.9-1.2-4.7-4.1-4.9-4.3-.1-.2-1.1-1.5-1.1-2.9 0-1.3.7-2 .9-2.3.2-.3.5-.3.7-.3h.5c.2 0 .4 0 .6.5.2.5.7 1.8.8 1.9.1.1.1.2 0 .4-.1.1-.1.2-.3.4-.1.1-.3.3-.4.4-.1.1-.3.3-.1.5.1.3.6 1.1 1.4 1.7 1 .8 1.8 1.1 2.1 1.2.3.1.4.1.6-.1.1-.2.7-.8.8-1.1.1-.2.3-.2.5-.1.2.1 1.4.7 1.7.8.3.1.5.2.5.3.1.2.1.7-.1 1.3z"/></svg>,
  Phone: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92z"/></svg>,
  MapPin: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>,
  Filter: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/></svg>,
  Grid: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>,
  Check: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20 6L9 17l-5-5"/></svg>,
  Rotate: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>,
  X: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M18 6L6 18M6 6l12 12"/></svg>
};

// --- Placeholder de auto: SVG silueta sobre fondo ---
const CarPlaceholder = ({ label, rotation = 0, accent }) => {
  // Silueta de auto genérica, gira sobre el eje vertical (sólo escala X)
  const scaleX = Math.cos((rotation * Math.PI) / 180);
  const skew = Math.sin((rotation * Math.PI) / 180) * 5;
  return (
    <div className="car-ph">
      <svg viewBox="0 0 400 140" preserveAspectRatio="xMidYMid meet" style={{transform: `scaleX(${Math.max(0.15, Math.abs(scaleX))}) skewX(${skew}deg)`, transformOrigin: 'center'}}>
        <defs>
          <linearGradient id="cg" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#2c2a25"/>
            <stop offset="1" stopColor="#0a0a0a"/>
          </linearGradient>
        </defs>
        {/* Cuerpo */}
        <path d="M40 100 L70 60 Q90 40 130 36 L240 32 Q280 32 310 52 L360 75 L370 95 L370 110 Q370 116 364 116 L320 116 Q316 100 300 100 Q284 100 280 116 L120 116 Q116 100 100 100 Q84 100 80 116 L46 116 Q40 116 40 110 Z" fill="url(#cg)" stroke="#3a372f" strokeWidth="1"/>
        {/* Vidrios */}
        <path d="M100 60 L130 42 L240 40 Q270 40 290 56 L300 70 L100 70 Z" fill="#15140f" opacity="0.9"/>
        <line x1="190" y1="42" x2="190" y2="70" stroke="#2a2823" strokeWidth="1"/>
        {/* Ruedas */}
        <circle cx="100" cy="116" r="18" fill="#080808" stroke="#2a2823" strokeWidth="1"/>
        <circle cx="100" cy="116" r="8" fill={accent || "#1a1916"}/>
        <circle cx="300" cy="116" r="18" fill="#080808" stroke="#2a2823" strokeWidth="1"/>
        <circle cx="300" cy="116" r="8" fill={accent || "#1a1916"}/>
        {/* Highlight */}
        <path d="M70 60 L90 50 L230 46 Q260 46 280 60" fill="none" stroke="rgba(243,237,226,0.07)" strokeWidth="1"/>
      </svg>
      {label && <div className="car-ph-mark" style={{position:'absolute', bottom: 12, left: 16}}>{label}</div>}
    </div>
  );
};

// --- HEADER ---
const Header = ({ current, onNav }) => {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', on);
    on();
    return () => window.removeEventListener('scroll', on);
  }, []);
  // Bloquea el scroll del body mientras el menú móvil está abierto
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);
  // Cerrar el menú al navegar (mobile)
  const go = (...args) => { setMenuOpen(false); onNav(...args); };
  return (
    <header className={'site-header' + (menuOpen ? ' menu-open' : '')} style={scrolled ? {background:'rgba(10,10,10,0.92)'} : null}>
      <div className="container">
        <div className="site-header-row">
          <a className="brand" onClick={(e)=>{e.preventDefault(); go('home');}} href="#home">
            <img src="logo-omega.png" alt="OMEGA Automotores" className="brand-logo"/>
            <div className="brand-sub">Mendoza · Argentina</div>
          </a>
          <nav id="omega-nav" className={menuOpen ? 'nav-links open' : 'nav-links'}>
            <a href="#home" className={current==='home'?'active':''} onClick={(e)=>{e.preventDefault(); go('home');}}>Inicio</a>
            <a href="#catalogo" className={current==='catalogo'?'active':''} onClick={(e)=>{e.preventDefault(); go('catalogo');}}>Catálogo</a>
            <a href="#financiacion" onClick={(e)=>{e.preventDefault(); go('home','financiacion');}}>Financiación</a>
            <a href="#nosotros" onClick={(e)=>{e.preventDefault(); go('home','nosotros');}}>Nosotros</a>
            <a href="#contacto" onClick={(e)=>{e.preventDefault(); go('home','contacto');}}>Contacto</a>
          </nav>
          <div className="header-actions">
            <a className="btn btn-accent btn-sm header-wa" href={`https://wa.me/${window.OMEGA_CONFIG.whatsapp}`} target="_blank" rel="noopener" style={{whiteSpace:'nowrap'}}>
              Hablar ahora <Icon.Arrow width="14" height="14"/>
            </a>
            <button type="button" className="nav-toggle" aria-label={menuOpen ? 'Cerrar menú' : 'Abrir menú'} aria-expanded={menuOpen} aria-controls="omega-nav" onClick={()=>setMenuOpen(o=>!o)}>
              <span className={menuOpen ? 'nav-toggle-bars open' : 'nav-toggle-bars'}><i/><i/><i/></span>
            </button>
          </div>
        </div>
      </div>
      <div className="nav-scrim" onClick={()=>setMenuOpen(false)} aria-hidden="true"></div>
    </header>
  );
};

// --- WHATSAPP FLOATING ---
const WhatsappFloat = () => (
  <a className="wa-float" href={`https://wa.me/${window.OMEGA_CONFIG.whatsapp}?text=${encodeURIComponent('Hola OMEGA, me interesa un vehículo')}`} target="_blank" rel="noopener">
    <span className="wa-float-ic"><Icon.Whatsapp width="18" height="18"/></span>
    <span className="wa-float-label">Chatear con un asesor</span>
  </a>
);

// --- VEHICLE CARD ---
const VehicleCard = ({ v, onClick }) => {
  const { fmtPrecio, fmtKm } = window.OMEGA_HELPERS;
  return (
    <article className="vcard" onClick={() => onClick(v.id)}>
      <div className="vcard-img">
        {v.photos && v.photos.length > 0
          ? <img src={v.photos[0]} alt={`${v.marca} ${v.modelo}`} className="vcard-photo" loading="lazy"/>
          : <CarPlaceholder label={`${v.marca} · ${v.color}`}/>}
        {v.tag && <div className={`vcard-tag ${v.tag==='PREMIUM'||v.tag==='COLECCIÓN' ? 'gold' : v.tag==='DESTACADO' ? 'accent' : ''}`}>{v.tag}</div>}
        {v.photos && v.photos.length > 1 && (
          <div className="vcard-photo-count mono">
            <Icon.Grid width="11" height="11"/> {v.photos.length}
          </div>
        )}
      </div>
      <div className="vcard-body">
        <div className="vcard-meta">
          <span>{v.anio}</span>
          <span>{fmtKm(v.km)}</span>
          <span>{v.transmision === 'Automática' ? 'AT' : 'MT'}</span>
        </div>
        <h3 className="vcard-title">{v.marca}</h3>
        <div className="vcard-sub">{v.modelo}</div>
        <div className="vcard-foot">
          <div className="vcard-price">{fmtPrecio(v)}</div>
          <span className="vcard-cta">Ver ficha <Icon.Arrow width="14" height="14"/></span>
        </div>
      </div>
    </article>
  );
};

// --- REVEAL ON SCROLL ---
const Reveal = ({ children, delay = 0, className = '' }) => {
  const ref = useRef();
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          setTimeout(() => setShown(true), delay);
          obs.disconnect();
        }
      });
    }, { threshold: 0.15 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [delay]);
  return <div ref={ref} className={`reveal ${shown?'in':''} ${className}`}>{children}</div>;
};

// --- REQUEST CAR FORM: lead capture cuando el vehículo no está en stock ---
const RequestCarForm = ({ preset, variant = 'block' }) => {
  const { marcas, carrocerias } = window.OMEGA_DATA;
  const { fmtPrice } = window.OMEGA_HELPERS;
  const [form, setForm] = useState({
    marca: preset?.marca && preset.marca !== 'Todas' ? preset.marca : '',
    modelo: '',
    carroceria: preset?.carroceria && preset.carroceria !== 'Todas' ? preset.carroceria : '',
    anioDesde: '',
    precioMax: preset?.precioMax || 25000000,
    nombre: '', tel: '', email: '', comentarios: ''
  });
  const [sent, setSent] = useState(false);

  useEffect(() => {
    if (preset) {
      setForm(f => ({
        ...f,
        marca: preset.marca && preset.marca !== 'Todas' ? preset.marca : f.marca,
        carroceria: preset.carroceria && preset.carroceria !== 'Todas' ? preset.carroceria : f.carroceria,
        precioMax: preset.precioMax || f.precioMax
      }));
    }
  }, [preset]);

  const submit = (e) => {
    e.preventDefault();

    // Construir mensaje para WhatsApp
    const lines = [
      '🚗 *NUEVA SOLICITUD DE BÚSQUEDA · OMEGA*',
      '',
      '*Auto buscado*',
      `• Marca: ${form.marca || 'Cualquiera'}`,
      `• Modelo: ${form.modelo || '—'}`,
      `• Tipo: ${form.carroceria || 'Cualquiera'}`,
      `• Año desde: ${form.anioDesde || '—'}`,
      `• Presupuesto máximo: ${fmtPrice(form.precioMax)}`,
      '',
      '*Contacto*',
      `• Nombre: ${form.nombre}`,
      `• Teléfono: ${form.tel}`,
      `• Email: ${form.email}`,
      form.comentarios ? `\n*Comentarios:*\n${form.comentarios}` : ''
    ].filter(Boolean);
    const text = encodeURIComponent(lines.join('\n'));
    const url = `https://wa.me/${window.OMEGA_CONFIG.whatsapp}?text=${text}`;

    // Persistir en Supabase para que aparezca en la bandeja del admin
    if (window.OMEGA_STORE?.createLead) {
      window.OMEGA_STORE.createLead({
        tipo: 'busqueda',
        nombre: form.nombre,
        telefono: form.tel,
        email: form.email,
        marca_buscada: form.marca || null,
        modelo_buscado: form.modelo || null,
        carroceria_buscada: form.carroceria || null,
        anio_desde: form.anioDesde ? parseInt(form.anioDesde) : null,
        presupuesto: form.precioMax,
        mensaje: form.comentarios || null,
        payload: form
      }).catch(e => console.warn('Lead no se pudo guardar:', e));
    }

    // Abrir WhatsApp en nueva pestaña
    window.open(url, '_blank', 'noopener');

    setSent(true);
    setTimeout(() => setSent(false), 8000);
  };

  if (sent) {
    return (
      <div className={`req-form req-form-${variant} req-sent`}>
        <div className="req-sent-mark"><Icon.Check width="32" height="32"/></div>
        <div className="eyebrow" style={{color:'var(--accent-bright)'}}>Solicitud enviada</div>
        <h3 className="display-md" style={{fontSize:36, margin:'12px 0 12px'}}>Te lo conseguimos.</h3>
        <p style={{color:'var(--ink-dim)', maxWidth: 420, margin:'0 auto'}}>
          Recibimos tu pedido. Vamos a consultar con nuestra red de agencias y un asesor te contacta dentro de las próximas <strong style={{color:'var(--ink)'}}>24 horas hábiles</strong>.
        </p>
      </div>
    );
  }

  return (
    <form className={`req-form req-form-${variant}`} onSubmit={submit}>
      <div className="req-form-head">
        <div className="eyebrow" style={{color:'var(--accent-bright)'}}>Te lo buscamos · Red OMEGA</div>
        <h3 className="display-md" style={{fontSize: variant === 'modal' ? 32 : 44, margin:'12px 0 8px', maxWidth:'20ch'}}>
          ¿No lo encontr&aacute;s?<br/><span style={{color:'var(--accent)'}}>Te lo conseguimos.</span>
        </h3>
        <p style={{color:'var(--ink-dim)', maxWidth:520, marginBottom:28}}>
          Decinos qué auto buscás. Consultamos con nuestra red de agencias en Mendoza y el país, y te respondemos en menos de 24h con opciones reales.
        </p>
      </div>

      <div className="req-grid">
        <div className="field">
          <label className="field-label">Marca</label>
          <select className="select" value={form.marca} onChange={e=>setForm({...form, marca:e.target.value})}>
            <option value="">Cualquier marca</option>
            {marcas.filter(m=>m!=='Todas').map(m => <option key={m}>{m}</option>)}
          </select>
        </div>
        <div className="field">
          <label className="field-label">Modelo (opcional)</label>
          <input className="input" placeholder="Ej: Hilux SRX, Corolla XEi..." value={form.modelo} onChange={e=>setForm({...form, modelo:e.target.value})}/>
        </div>
        <div className="field">
          <label className="field-label">Tipo</label>
          <select className="select" value={form.carroceria} onChange={e=>setForm({...form, carroceria:e.target.value})}>
            <option value="">Cualquier tipo</option>
            {carrocerias.filter(c=>c!=='Todas').map(c => <option key={c}>{c}</option>)}
          </select>
        </div>
        <div className="field">
          <label className="field-label">Año desde (opcional)</label>
          <input className="input" type="number" min="2010" max="2025" placeholder="2020" value={form.anioDesde} onChange={e=>setForm({...form, anioDesde:e.target.value})}/>
        </div>
        <div className="field req-field-wide">
          <label className="field-label">Presupuesto máximo · {fmtPrice(form.precioMax)}</label>
          <input type="range" min="3000000" max="80000000" step="500000" value={form.precioMax}
                 onChange={e=>setForm({...form, precioMax:+e.target.value})} className="range-input"/>
        </div>
      </div>

      <div className="rule" style={{margin:'24px 0 8px'}}/>

      <div className="eyebrow" style={{marginTop:16, marginBottom:8}}>Tus datos · para contactarte</div>
      <div className="req-grid">
        <div className="field req-field-wide">
          <label className="field-label">Nombre completo</label>
          <input className="input" required value={form.nombre} onChange={e=>setForm({...form, nombre:e.target.value})}/>
        </div>
        <div className="field">
          <label className="field-label">WhatsApp / Teléfono</label>
          <input className="input" type="tel" required placeholder="+54 9 261..." value={form.tel} onChange={e=>setForm({...form, tel:e.target.value})}/>
        </div>
        <div className="field">
          <label className="field-label">Email</label>
          <input className="input" type="email" required value={form.email} onChange={e=>setForm({...form, email:e.target.value})}/>
        </div>
        <div className="field req-field-wide">
          <label className="field-label">Comentarios (opcional)</label>
          <textarea className="input" rows="2" placeholder="Tengo un auto para entregar como parte de pago / busco un color específico / urgente..." value={form.comentarios} onChange={e=>setForm({...form, comentarios:e.target.value})}/>
        </div>
      </div>

      <button className="btn btn-accent btn-lg btn-block" type="submit" style={{marginTop:28}}>
        <Icon.Whatsapp width="16" height="16"/> Enviar solicitud por WhatsApp <Icon.Arrow width="14" height="14"/>
      </button>
      <p className="mono" style={{fontSize:10, color:'var(--ink-mute)', letterSpacing:'0.12em', textTransform:'uppercase', marginTop:16, textAlign:'center'}}>
        Se abre WhatsApp con tu pedido ya escrito · sin compromiso
      </p>
    </form>
  );
};

// --- MODAL WRAPPER ---
const Modal = ({ open, onClose, children }) => {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.body.style.overflow = 'hidden';
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onKey); };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-body" onClick={e=>e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Cerrar">
          <Icon.X width="22" height="22"/>
        </button>
        {children}
      </div>
    </div>
  );
};

// Expose globally
Object.assign(window, { Icon, CarPlaceholder, Header, WhatsappFloat, VehicleCard, Reveal, RequestCarForm, Modal });
