// catalog.jsx — vista catálogo con filtros y toggle grid/lista

function FiltersBar({ state, setState, theme, vestidos }) {
  // Colecciones derivadas de los datos + catálogos fijos
  const temporadasDisponibles = React.useMemo(() => {
    const s = new Set(vestidos.map(v => v.temporada).filter(Boolean));
    return [...s].sort();
  }, [vestidos]);

  const tejidosDisponibles = React.useMemo(() => {
    const s = new Set();
    vestidos.forEach(v => (v.tejidos || []).forEach(t => {
      if (t.composicion) {
        // Extraer "tipo" del principio de la composición (primera palabra compuesta)
        const parts = t.composicion.split(/[\s,]/);
        const main = parts.slice(0, 2).join(' ').trim();
        if (main) s.add(t.composicion.trim());
      }
    }));
    return [...s].sort();
  }, [vestidos]);

  const coloresDisponibles = React.useMemo(() => {
    const s = new Set();
    vestidos.forEach(v => window.coloresDeVestido(v).forEach(c => s.add(c)));
    return [...s].sort();
  }, [vestidos]);

  const toggle = (group, val) => {
    const cur = new Set(state[group]);
    if (cur.has(val)) cur.delete(val); else cur.add(val);
    setState({ ...state, [group]: [...cur] });
  };
  const clear = () => setState({ ...state, temporadas: [], tejidos: [], colores: [], q: '' });

  const totalActivos = state.temporadas.length + state.tejidos.length + state.colores.length + (state.q ? 1 : 0);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {/* search */}
      <div style={{ position: 'relative', padding: '0 14px' }}>
        <svg width="14" height="14" viewBox="0 0 14 14" style={{
          position: 'absolute', left: 26, top: '50%', transform: 'translateY(-50%)',
          opacity: 0.5,
        }}>
          <circle cx="6" cy="6" r="4.5" fill="none" stroke={theme.muted} strokeWidth="1.3"/>
          <path d="M9.5 9.5L13 13" stroke={theme.muted} strokeWidth="1.3" strokeLinecap="round"/>
        </svg>
        <input type="search" value={state.q}
               onChange={e => setState({ ...state, q: e.target.value })}
               placeholder="Buscar modelo u observaciones…"
               style={{
                 width: '100%', height: 38, padding: '0 14px 0 34px', borderRadius: 12,
                 border: `0.5px solid ${theme.border}`,
                 background: theme.input, color: theme.ink,
                 fontSize: 14, font: 'inherit', outline: 'none',
                 WebkitAppearance: 'none', boxSizing: 'border-box',
               }} />
      </div>

      {/* filter groups */}
      <FilterGroup label="Temporada" theme={theme}>
        {temporadasDisponibles.map(t => (
          <window.FilterChip key={t} label={t} theme={theme}
                             active={state.temporadas.includes(t)}
                             onClick={() => toggle('temporadas', t)} />
        ))}
      </FilterGroup>

      <FilterGroup label="Tejido" theme={theme}>
        {tejidosDisponibles.map(t => (
          <window.FilterChip key={t} label={t} theme={theme}
                             active={state.tejidos.includes(t)}
                             onClick={() => toggle('tejidos', t)} />
        ))}
      </FilterGroup>

      <FilterGroup label="Color" theme={theme}>
        {coloresDisponibles.map(c => {
          const match = window.COLORES.find(x => x.nombre === c);
          return (
            <window.FilterChip key={c} label={c} theme={theme}
                               colorDot={match?.hex || '#ccc'}
                               active={state.colores.includes(c)}
                               onClick={() => toggle('colores', c)} />
          );
        })}
      </FilterGroup>

      {totalActivos > 0 && (
        <div style={{ padding: '0 14px' }}>
          <button onClick={clear} style={{
            background: 'transparent', border: 0, color: theme.muted,
            fontSize: 12, cursor: 'pointer', padding: '4px 0', textDecoration: 'underline',
            textUnderlineOffset: 3,
          }}>Limpiar filtros ({totalActivos})</button>
        </div>
      )}
    </div>
  );
}

function FilterGroup({ label, theme, children }) {
  const kids = React.Children.toArray(children).filter(Boolean);
  if (kids.length === 0) return null;
  return (
    <div>
      <div style={{
        fontSize: 10.5, fontWeight: 600, letterSpacing: 0.6,
        color: theme.muted, textTransform: 'uppercase',
        padding: '0 14px 5px',
      }}>{label}</div>
      <div style={{
        display: 'flex', gap: 6, overflowX: 'auto', padding: '0 14px 2px',
        scrollbarWidth: 'none',
      }}
      className="no-scrollbar">
        {kids}
      </div>
    </div>
  );
}

function CatalogView({ vestidos, theme, density, view, setView, filters, setFilters, onOpen, onAdd }) {
  // Apply filters
  const filtered = React.useMemo(() => {
    return vestidos.filter(v => {
      if (filters.temporadas.length && !filters.temporadas.includes(v.temporada)) return false;
      if (filters.tejidos.length) {
        const tjs = (v.tejidos || []).map(t => (t.composicion || '').trim());
        if (!filters.tejidos.some(f => tjs.includes(f))) return false;
      }
      if (filters.colores.length) {
        const cs = window.coloresDeVestido(v);
        if (!filters.colores.some(c => cs.includes(c))) return false;
      }
      if (filters.q) {
        const q = filters.q.toLowerCase();
        const haystack = [
          v.modelo, v.temporada, v.observaciones, v.forniturasEspeciales,
          ...(v.tejidos || []).map(t => t.composicion),
        ].filter(Boolean).join(' ').toLowerCase();
        if (!haystack.includes(q)) return false;
      }
      return true;
    });
  }, [vestidos, filters]);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: theme.bg }}>
      {/* header title + add */}
      <div style={{
        padding: '12px 16px 4px', flexShrink: 0,
        display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{
            fontSize: 11, letterSpacing: 1.2, textTransform: 'uppercase',
            color: theme.muted, fontWeight: 600,
          }}>Atelier</div>
          <div style={{
            fontFamily: theme.serif, fontSize: 32, fontWeight: 500, color: theme.ink,
            lineHeight: 1, letterSpacing: 0.3, marginTop: 2,
          }}>Catálogo</div>
        </div>
        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          {/* view toggle */}
          <div style={{
            display: 'flex', background: theme.subtle, borderRadius: 10,
            border: `0.5px solid ${theme.border}`, padding: 2,
          }}>
            <button onClick={() => setView('grid')} style={viewTabStyle(theme, view === 'grid')}>
              <GridIcon active={view === 'grid'} theme={theme}/>
            </button>
            <button onClick={() => setView('list')} style={viewTabStyle(theme, view === 'list')}>
              <ListIcon active={view === 'list'} theme={theme}/>
            </button>
          </div>
          <button onClick={onAdd} style={{
            width: 34, height: 34, borderRadius: 10,
            background: theme.accent, border: 0, color: '#fff',
            fontSize: 22, cursor: 'pointer', padding: 0, lineHeight: 1,
            boxShadow: '0 2px 6px rgba(180,140,100,0.25)',
          }} title="Añadir vestido">+</button>
        </div>
      </div>

      {/* count */}
      <div style={{ padding: '6px 16px 10px', flexShrink: 0 }}>
        <div style={{ fontSize: 12, color: theme.muted }}>
          {filtered.length} {filtered.length === 1 ? 'vestido' : 'vestidos'}
          {filtered.length !== vestidos.length && ` de ${vestidos.length}`}
        </div>
      </div>

      {/* filters */}
      <div style={{ flexShrink: 0, paddingBottom: 12 }}>
        <FiltersBar state={filters} setState={setFilters} theme={theme} vestidos={vestidos} />
      </div>

      {/* content */}
      <div style={{ flex: 1, overflow: 'auto', padding: '0 14px 24px' }}>
        {filtered.length === 0 ? (
          <EmptyState theme={theme} hasFilters={vestidos.length > 0} onAdd={onAdd}/>
        ) : view === 'grid' ? (
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 1fr',
            gap: density === 'compacta' ? 8 : 12,
          }}>
            {filtered.map(v => (
              <window.CatalogCard key={v.id} vestido={v} theme={theme}
                                  density={density} onOpen={onOpen} />
            ))}
          </div>
        ) : (
          <div style={{
            background: theme.card, borderRadius: 16,
            border: `0.5px solid ${theme.border}`, overflow: 'hidden',
          }}>
            {filtered.map((v, i) => (
              <window.CatalogRow key={v.id} vestido={v} theme={theme}
                                 onOpen={onOpen} isLast={i === filtered.length - 1} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function viewTabStyle(theme, active) {
  return {
    width: 30, height: 30, borderRadius: 8,
    background: active ? theme.card : 'transparent',
    boxShadow: active ? '0 1px 2px rgba(60,40,20,0.1)' : 'none',
    border: 0, cursor: 'pointer', padding: 0,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  };
}

function GridIcon({ active, theme }) {
  const c = active ? theme.ink : theme.muted;
  return (
    <svg width="14" height="14" viewBox="0 0 14 14">
      <rect x="1" y="1" width="5" height="5" rx="1" fill={c}/>
      <rect x="8" y="1" width="5" height="5" rx="1" fill={c}/>
      <rect x="1" y="8" width="5" height="5" rx="1" fill={c}/>
      <rect x="8" y="8" width="5" height="5" rx="1" fill={c}/>
    </svg>
  );
}
function ListIcon({ active, theme }) {
  const c = active ? theme.ink : theme.muted;
  return (
    <svg width="14" height="14" viewBox="0 0 14 14">
      <rect x="1" y="2" width="12" height="1.6" rx="0.5" fill={c}/>
      <rect x="1" y="6.2" width="12" height="1.6" rx="0.5" fill={c}/>
      <rect x="1" y="10.4" width="12" height="1.6" rx="0.5" fill={c}/>
    </svg>
  );
}

function EmptyState({ theme, hasFilters, onAdd }) {
  return (
    <div style={{
      padding: '40px 20px', textAlign: 'center',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14,
    }}>
      <div style={{ width: 56, height: 56 }}>
        <window.DressPlaceholder seed={1} tone={theme.accent} bg={theme.placeholderBg}/>
      </div>
      <div>
        <div style={{
          fontFamily: theme.serif, fontSize: 18, color: theme.ink, fontWeight: 500,
        }}>
          {hasFilters ? 'No hay vestidos con estos filtros' : 'Aún no hay vestidos'}
        </div>
        <div style={{ fontSize: 13, color: theme.muted, marginTop: 4, lineHeight: 1.4 }}>
          {hasFilters
            ? 'Prueba a quitar alguno o usar la búsqueda.'
            : 'Añade el primer vestido para empezar tu catálogo.'}
        </div>
      </div>
      {!hasFilters && (
        <button onClick={onAdd} style={{
          background: theme.accent, color: '#fff', border: 0,
          height: 38, padding: '0 18px', borderRadius: 10,
          fontSize: 14, fontWeight: 500, cursor: 'pointer',
        }}>Añadir vestido</button>
      )}
    </div>
  );
}

Object.assign(window, { CatalogView });
