// Sellcore — Página de catálogo completo (/catalogo/). Lee window.SC_CATALOG.
const { Ico, MARK } = window.SC_Site;
const { useState, useMemo } = React;

const DATA = window.SC_CATALOG || { categorias: [], equipos: [], fotoBase: '', tono: () => 'neutral' };
// Foto: usa el campo "foto" si está; si no, prueba <ID>.jpg automáticamente.
const FOTO = (e) => (DATA.fotoBase || '') + (e.foto || (e.id + '.jpg'));

// ------------------------------------------------------------- Media del equipo
function EquipoMedia({ equipo, height = 176 }) {
  const [err, setErr] = React.useState(false);
  React.useEffect(() => setErr(false), [equipo.id]);
  return (
    <div style={{
      height, position: 'relative', overflow: 'hidden',
      background: 'linear-gradient(135deg, var(--ink-050), var(--ink-100))',
      display: 'grid', placeItems: 'center', color: 'var(--ink-300)',
    }}>
      {!err
        ? <img src={FOTO(equipo)} alt={equipo.nombre} loading="lazy"
            style={{ width: '100%', height: '100%', objectFit: equipo.fit || 'cover', padding: equipo.fit === 'contain' ? 14 : 0, boxSizing: 'border-box' }}
            onError={() => setErr(true)} />
        : <Ico name={equipo.icono || 'Package'} size={54} stroke={1.4} />}
    </div>
  );
}

// --------------------------------------------------------------------- Card
function EquipoCard({ equipo, onOpen }) {
  return (
    <window.SC.Card interactive elevation="flat" padding="none" style={{ overflow: 'hidden' }}>
      <div onClick={() => onOpen(equipo)} style={{ cursor: 'pointer' }}>
        <EquipoMedia equipo={equipo} />
        <div style={{ padding: '20px 20px 0' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{equipo.categoria}</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-300)' }}>{equipo.id}</span>
          </div>
          <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 19, margin: '6px 0 8px', color: 'var(--ink-900)' }}>{equipo.nombre}</h3>
          <p style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--text-body)', margin: '0 0 12px', minHeight: 42 }}>{equipo.descripcion}</p>
          {equipo.opcionales && equipo.opcionales.length > 0 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
              {equipo.opcionales.map((o) => (
                <span key={o.nombre} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 600, color: 'var(--brand-cyan, #0a7ea4)', background: 'var(--ink-050)', border: '1px solid var(--border-subtle)', padding: '3px 9px', borderRadius: 99 }}>
                  <Ico name="Plus" size={11} />Opcional: {o.nombre}
                </span>
              ))}
            </div>
          )}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', padding: '0 20px 20px' }}>
        <window.SC.Button variant="secondary" size="sm" style={{ flex: 1 }}
          onClick={() => onOpen(equipo)}>Ver ficha</window.SC.Button>
        <window.SC.Button variant="accent" size="sm" trailingIcon={<Ico name="Plus" size={14} />}
          onClick={() => { window.SC_CART && window.SC_CART.add(equipo); }}>Agregar</window.SC.Button>
      </div>
    </window.SC.Card>
  );
}

// -------------------------------------------------------------------- Modal
function EquipoModal({ equipo, onClose }) {
  const [opts, setOpts] = React.useState({});
  React.useEffect(() => { setOpts({}); }, [equipo && equipo.id]);
  if (!equipo) return null;
  const toggle = (nombre) => setOpts((p) => Object.assign({}, p, { [nombre]: !p[nombre] }));
  const seleccionadas = (equipo.opcionales || []).filter((o) => opts[o.nombre]).map((o) => o.nombre);
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(11,18,32,0.55)',
      backdropFilter: 'blur(4px)', display: 'grid', placeItems: 'center', padding: 24,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--white)', borderRadius: 'var(--radius-2xl)', boxShadow: 'var(--shadow-xl)',
        width: 'min(720px, 100%)', maxHeight: '88vh', overflow: 'auto',
      }}>
        <div style={{ position: 'relative' }}>
          <EquipoMedia equipo={equipo} height={220} />
          <button onClick={onClose} aria-label="Cerrar" style={{
            position: 'absolute', top: 14, right: 14, width: 36, height: 36, borderRadius: 10,
            border: 'none', background: 'rgba(255,255,255,0.9)', cursor: 'pointer',
            display: 'grid', placeItems: 'center', color: 'var(--ink-800)', boxShadow: 'var(--shadow-md)',
          }}><Ico name="X" size={18} /></button>
        </div>
        <div style={{ padding: 28 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap' }}>
            <div>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{equipo.categoria} · {equipo.id}</span>
              <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 30, letterSpacing: '-0.02em', margin: '8px 0 0', color: 'var(--ink-900)' }}>{equipo.nombre}</h2>
            </div>
          </div>
          <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--text-body)', margin: '14px 0 0' }}>{equipo.descripcion}</p>

          {equipo.specs && equipo.specs.length > 0 && (
            <div style={{ marginTop: 24 }}>
              <div className="sc-eyebrow" style={{ marginBottom: 12 }}>Ficha técnica</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 28px' }}>
                {equipo.specs.map(([k, v], i) => (
                  <div key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '11px 0', borderBottom: '1px solid var(--border-subtle)' }}>
                    <span style={{ fontSize: 14, color: 'var(--text-muted)' }}>{k}</span>
                    <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-900)', textAlign: 'right' }}>{v}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {equipo.opcionales && equipo.opcionales.length > 0 && (
            <div style={{ marginTop: 24 }}>
              <div className="sc-eyebrow" style={{ marginBottom: 12 }}>Opcionales · selecciona para agregar</div>
              {equipo.opcionales.map((o) => {
                const on = !!opts[o.nombre];
                return (
                  <div key={o.nombre} onClick={() => toggle(o.nombre)} style={{
                    display: 'flex', gap: 12, padding: '12px 14px', marginBottom: 8, cursor: 'pointer',
                    border: '1px solid ' + (on ? 'var(--brand-green)' : 'var(--border-default)'), borderRadius: 'var(--radius-lg)',
                    background: on ? 'rgba(0,212,84,0.06)' : 'transparent',
                  }}>
                    <div style={{
                      width: 24, height: 24, borderRadius: 7, flex: 'none', marginTop: 1, display: 'grid', placeItems: 'center',
                      border: '2px solid ' + (on ? 'var(--brand-green)' : 'var(--border-strong, #c7ced7)'),
                      background: on ? 'var(--brand-green)' : 'transparent', color: '#fff',
                    }}>{on && <Ico name="Check" size={15} />}</div>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--ink-900)' }}>{o.nombre}</div>
                      {o.detalle && <div style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--text-body)', marginTop: 2 }}>{o.detalle}</div>}
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          <div style={{ display: 'flex', gap: 12, marginTop: 26 }}>
            <window.SC.Button variant="accent" size="lg" trailingIcon={<Ico name="Plus" size={16} />}
              onClick={() => { window.SC_CART && window.SC_CART.add(equipo, seleccionadas); onClose(); }}>
              {seleccionadas.length ? 'Agregar con ' + seleccionadas.length + ' opcional' + (seleccionadas.length > 1 ? 'es' : '') : 'Agregar a la cotización'}
            </window.SC.Button>
            <window.SC.Button variant="secondary" size="lg" onClick={onClose}>Seguir viendo</window.SC.Button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ------------------------------------------------------- "El equipo que buscas no está?"
function catToast(msg) {
  if (typeof document === 'undefined') return;
  let el = document.getElementById('toast');
  if (!el) { el = document.createElement('div'); el.id = 'toast'; document.body.appendChild(el); }
  el.innerHTML = '';
  const card = document.createElement('div');
  card.style.cssText = 'background:var(--ink-900);color:#fff;padding:14px 20px;border-radius:14px;box-shadow:var(--shadow-xl);font-family:var(--font-body);font-weight:600;font-size:14px;display:flex;gap:10px;align-items:center';
  card.innerHTML = '<span style="width:8px;height:8px;border-radius:9px;background:var(--brand-green)"></span>' + msg;
  el.appendChild(card); el.classList.add('show');
  clearTimeout(window.__ct); window.__ct = setTimeout(() => el.classList.remove('show'), 2800);
}

function BuscasForm() {
  const [c, setC] = React.useState({});
  const EMAIL = (typeof window !== 'undefined' && window.SC_CART_CONTACT_EMAIL) || 'ventas@sellcore.cl';
  const set = (k) => (e) => setC(Object.assign({}, c, { [k]: e.target.value }));
  const inp = { width: '100%', boxSizing: 'border-box', padding: '12px 14px', borderRadius: 10, border: '1px solid var(--border-inverse)', background: 'rgba(255,255,255,0.06)', color: 'var(--white)', fontFamily: 'var(--font-body)', fontSize: 14, outline: 'none' };
  const enviar = () => {
    if (!c.equipo || !c.nombre || !c.email || !c.telefono) return catToast('Completa el equipo, nombre, email y teléfono.');
    if (!/.+@.+\..+/.test(c.email)) return catToast('Ingresa un email válido.');
    const cuerpo = 'Equipo buscado: ' + c.equipo + '\n\nNombre: ' + c.nombre + '\nEmail: ' + c.email + '\nTeléfono: ' + c.telefono + '\n\nMensaje:\n' + (c.mensaje || '-') + '\n';
    window.location.href = 'mailto:' + EMAIL + '?subject=' + encodeURIComponent('Equipo solicitado — Sellcore') + '&body=' + encodeURIComponent(cuerpo);
    setC({}); catToast('Abrimos tu correo — te ayudamos a conseguirlo.');
  };
  return (
    <section style={{ background: 'var(--ink-900)', color: 'var(--white)', padding: '76px 28px' }}>
      <div style={{ maxWidth: 'var(--container-xl)', margin: '0 auto', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 40, alignItems: 'center' }}>
        <div>
          <span className="sc-eyebrow" style={{ color: 'var(--brand-green)' }}>Te la hacemos fácil</span>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(24px, 5.6vw, 36px)', letterSpacing: '-0.025em', lineHeight: 1.1, margin: '12px 0 0', color: 'var(--white)' }}>
            ¿El equipo que buscas no está?
          </h2>
          <p style={{ fontSize: 17, lineHeight: 1.55, color: 'var(--text-on-dark-muted)', margin: '14px 0 0', maxWidth: 440 }}>
            No importa — <strong style={{ color: 'var(--white)' }}>lo conseguimos por ti</strong>. Cuéntanos qué necesitas y te contactamos con una propuesta.
          </p>
        </div>
        <div>
          <input placeholder="¿Qué equipo buscas?" value={c.equipo || ''} onChange={set('equipo')} style={inp} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 12 }}>
            <input placeholder="Nombre" value={c.nombre || ''} onChange={set('nombre')} style={inp} />
            <input placeholder="Teléfono" value={c.telefono || ''} onChange={set('telefono')} style={inp} />
          </div>
          <input placeholder="Email" value={c.email || ''} onChange={set('email')} style={{ ...inp, marginTop: 12 }} />
          <input placeholder="Mensaje (opcional)" value={c.mensaje || ''} onChange={set('mensaje')} style={{ ...inp, marginTop: 12 }} />
          <window.SC.Button variant="accent" size="lg" onClick={enviar} style={{ width: '100%', marginTop: 14 }} trailingIcon={<Ico name="ArrowRight" size={16} />}>Solicitar equipo</window.SC.Button>
        </div>
      </div>
    </section>
  );
}

// --------------------------------------------------------------------- Page
function CatalogPage({ onCta }) {
  const [cat, setCat] = useState('Todos');
  const [q, setQ] = useState('');
  const [sel, setSel] = useState(null);

  const chips = ['Todos', ...DATA.categorias.map(c => c.nombre)];

  // Pre-filtro por ?cat= (desde el dropdown "Rental" del menú).
  React.useEffect(() => {
    const p = new URLSearchParams(window.location.search).get('cat');
    if (p && chips.indexOf(p) !== -1) setCat(p);
  }, []);

  const filtered = useMemo(() => {
    const needle = q.trim().toLowerCase();
    return DATA.equipos.filter(e => {
      if (cat !== 'Todos' && e.categoria !== cat) return false;
      if (!needle) return true;
      const hay = [e.nombre, e.categoria, e.id, e.descripcion,
        ...(e.specs || []).flat()].join(' ').toLowerCase();
      return hay.includes(needle);
    });
  }, [cat, q]);

  return (
    <React.Fragment>
      {/* Encabezado oscuro */}
      <section style={{ background: 'var(--ink-900)', color: 'var(--white)', padding: '64px 28px 56px' }}>
        <div style={{ maxWidth: 'var(--container-2xl)', margin: '0 auto' }}>
          <span className="sc-eyebrow" style={{ color: 'var(--text-on-dark-muted)' }}>Catálogo de equipos</span>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(30px, 7.5vw, 48px)', letterSpacing: '-0.03em', lineHeight: 1.05, margin: '14px 0 0', color: 'var(--white)', maxWidth: 640 }}>
            Toda la flota Sellcore, en un solo lugar.
          </h1>
          <p style={{ fontSize: 17, lineHeight: 1.55, color: 'var(--text-on-dark-muted)', margin: '16px 0 0', maxWidth: 560 }}>
            Filtra por categoría o busca el equipo que necesitas. Cotiza en línea y recíbelo en obra.
          </p>
        </div>
      </section>

      {/* Barra de filtros + búsqueda (sticky) */}
      <div style={{ position: 'sticky', top: 70, zIndex: 40, background: 'rgba(255,255,255,0.9)', backdropFilter: 'blur(12px)', borderBottom: '1px solid var(--border-default)' }}>
        <div style={{ maxWidth: 'var(--container-2xl)', margin: '0 auto', padding: '16px 28px', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {chips.map(c => (
              <window.SC.Tag key={c} selectable selected={cat === c} onClick={() => setCat(c)}>{c}</window.SC.Tag>
            ))}
          </div>
          <div style={{ position: 'relative', minWidth: 260 }}>
            <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)', display: 'grid', placeItems: 'center' }}>
              <Ico name="Search" size={16} />
            </span>
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar equipo, categoría o spec…"
              style={{
                width: '100%', height: 42, padding: '0 14px 0 38px', borderRadius: 'var(--radius-lg)',
                border: '1px solid var(--border-default)', background: 'var(--white)',
                fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-900)', outline: 'none',
              }} />
          </div>
        </div>
      </div>

      {/* Grilla */}
      <section style={{ background: 'var(--surface-app)', padding: '40px 28px 92px', minHeight: '50vh' }}>
        <div style={{ maxWidth: 'var(--container-2xl)', margin: '0 auto' }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-muted)', marginBottom: 20 }}>
            {filtered.length} {filtered.length === 1 ? 'equipo' : 'equipos'}{cat !== 'Todos' ? ' · ' + cat : ''}
          </div>

          {filtered.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '80px 0', color: 'var(--text-muted)' }}>
              <Ico name="Search" size={36} stroke={1.4} />
              <p style={{ fontSize: 16, marginTop: 14 }}>No encontramos equipos para esa búsqueda.</p>
              <window.SC.Button variant="secondary" size="sm" onClick={() => { setQ(''); setCat('Todos'); }} style={{ marginTop: 8 }}>Limpiar filtros</window.SC.Button>
            </div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 22 }}>
              {filtered.map(e => <EquipoCard key={e.id} equipo={e} onOpen={setSel} />)}
            </div>
          )}
        </div>
      </section>

      <BuscasForm />

      <EquipoModal equipo={sel} onClose={() => setSel(null)} onCta={(e) => { setSel(null); onCta(e); }} />
    </React.Fragment>
  );
}

window.SC_CatalogPage = { CatalogPage };
