// components.jsx — tarjetas grid/lista, ficha detalle, chips, placeholder

// ─────────────────────────────────────────────────────────────
// Placeholder de imagen (cuando no hay foto del vestido)
// Dibuja la silueta simplificada de un vestido con tono del tema.
// ─────────────────────────────────────────────────────────────
function DressPlaceholder({ seed = 0, tone = '#B89C7A', bg = '#F4EEE4' }) {
  // pequeñas variaciones de silueta según seed para que no todos iguales
  const variants = [
    // princesa
    { d: 'M50 22 L60 22 L62 38 L78 86 L32 86 L48 38 L50 22 Z' },
    // sirena
    { d: 'M52 22 L58 22 L60 40 L55 62 L78 88 L32 88 L55 62 L50 40 L52 22 Z' },
    // columna
    { d: 'M52 22 L58 22 L62 38 L66 86 L44 86 L48 38 L52 22 Z' },
    // vaporosa
    { d: 'M50 24 L60 24 L64 40 L84 88 L26 88 L46 40 L50 24 Z' },
  ];
  const v = variants[seed % variants.length];
  return (
    <svg viewBox="0 0 110 100" preserveAspectRatio="xMidYMid meet"
         style={{ width: '100%', height: '100%', display: 'block', background: bg }}>
      {/* hanger suggestion */}
      <circle cx="55" cy="16" r="3" fill="none" stroke={tone} strokeOpacity="0.3" strokeWidth="0.8"/>
      <path d="M55 19 L55 22" stroke={tone} strokeOpacity="0.3" strokeWidth="0.8"/>
      {/* dress */}
      <path d={v.d} fill={tone} fillOpacity="0.22" stroke={tone} strokeOpacity="0.55" strokeWidth="0.8" strokeLinejoin="round"/>
      {/* waist line */}
      <path d="M48 40 Q55 42 62 40" stroke={tone} strokeOpacity="0.4" strokeWidth="0.6" fill="none"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Color swatch (punto) usado en chips y tarjetas
// ─────────────────────────────────────────────────────────────
function ColorDot({ hex, size = 10, border = 'rgba(0,0,0,0.12)' }) {
  return (
    <span style={{
      display: 'inline-block', width: size, height: size, borderRadius: '50%',
      background: hex, border: `0.5px solid ${border}`, flexShrink: 0,
    }} />
  );
}

// Helper: extrae colores únicos de fornituras de un vestido
function coloresDeVestido(v) {
  const set = new Set();
  Object.values(v.fornituras || {}).forEach(f => {
    if (f && f.color && f.color.trim()) set.add(f.color.trim());
  });
  return [...set];
}

function tejidosDeVestido(v) {
  return (v.tejidos || []).filter(t => t && t.composicion && t.composicion.trim())
    .map(t => t.composicion.trim());
}

// ─────────────────────────────────────────────────────────────
// Tarjeta (vista grid)
// ─────────────────────────────────────────────────────────────
function CatalogCard({ vestido, theme, density, onOpen }) {
  const tejidos = tejidosDeVestido(vestido);
  const colores = coloresDeVestido(vestido);
  const pad = density === 'compacta' ? 10 : 14;
  return (
    <button
      onClick={() => onOpen(vestido.id)}
      style={{
        background: theme.card, border: `0.5px solid ${theme.border}`,
        borderRadius: 18, padding: 0, textAlign: 'left', cursor: 'pointer',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
        boxShadow: '0 1px 2px rgba(60,40,20,0.04), 0 4px 12px rgba(60,40,20,0.04)',
        font: 'inherit', color: 'inherit',
      }}>
      <div style={{ aspectRatio: '3 / 4', position: 'relative', background: theme.placeholderBg }}>
        {vestido.foto ? (
          <img src={vestido.foto} alt={vestido.modelo}
               style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
        ) : (
          <DressPlaceholder seed={(vestido.modelo || '').charCodeAt(0) || 0}
                            tone={theme.accent} bg={theme.placeholderBg} />
        )}
        {vestido.temporada && (
          <div style={{
            position: 'absolute', top: 8, left: 8,
            background: theme.chipBg, color: theme.chipFg,
            fontSize: 10.5, fontWeight: 500, letterSpacing: 0.3,
            padding: '3px 8px', borderRadius: 999,
            border: `0.5px solid ${theme.border}`,
            backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
            whiteSpace: 'nowrap',
          }}>{vestido.temporada}</div>
        )}
      </div>
      <div style={{ padding: pad, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{
          fontFamily: theme.serif, fontSize: density === 'compacta' ? 17 : 19,
          fontWeight: 500, color: theme.ink, letterSpacing: 0.1,
          lineHeight: 1.1,
        }}>{vestido.modelo || 'Sin nombre'}</div>
        {tejidos.length > 0 && (
          <div style={{
            fontSize: 11.5, color: theme.muted, lineHeight: 1.35,
            display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
            overflow: 'hidden',
          }}>
            {tejidos.slice(0, 2).join(' · ')}
            {tejidos.length > 2 && ` +${tejidos.length - 2}`}
          </div>
        )}
        {colores.length > 0 && (
          <div style={{ display: 'flex', gap: 4, marginTop: 2 }}>
            {colores.slice(0, 5).map(c => {
              const match = window.COLORES.find(x => x.nombre === c);
              return <ColorDot key={c} hex={match?.hex || '#ccc'} />;
            })}
          </div>
        )}
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Fila (vista lista densa)
// ─────────────────────────────────────────────────────────────
function CatalogRow({ vestido, theme, onOpen, isLast }) {
  const tejidos = tejidosDeVestido(vestido);
  const colores = coloresDeVestido(vestido);
  return (
    <button
      onClick={() => onOpen(vestido.id)}
      style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '10px 14px', background: 'transparent', border: 0,
        borderBottom: isLast ? 'none' : `0.5px solid ${theme.border}`,
        textAlign: 'left', cursor: 'pointer', font: 'inherit', color: 'inherit',
        width: '100%',
      }}>
      <div style={{
        width: 44, height: 58, borderRadius: 8, overflow: 'hidden', flexShrink: 0,
        background: theme.placeholderBg, border: `0.5px solid ${theme.border}`,
      }}>
        {vestido.foto ? (
          <img src={vestido.foto} alt={vestido.modelo}
               style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        ) : (
          <DressPlaceholder seed={(vestido.modelo || '').charCodeAt(0) || 0}
                            tone={theme.accent} bg={theme.placeholderBg} />
        )}
      </div>
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 2 }}>
        <div style={{
          display: 'flex', alignItems: 'baseline', gap: 8,
        }}>
          <span style={{
            fontFamily: theme.serif, fontSize: 16, fontWeight: 500, color: theme.ink,
          }}>{vestido.modelo || 'Sin nombre'}</span>
          {vestido.temporada && (
            <span style={{
              fontSize: 10.5, color: theme.muted, letterSpacing: 0.3,
            }}>{vestido.temporada}</span>
          )}
        </div>
        {tejidos.length > 0 && (
          <div style={{
            fontSize: 11.5, color: theme.muted, lineHeight: 1.3,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{tejidos.join(' · ')}</div>
        )}
        {colores.length > 0 && (
          <div style={{ display: 'flex', gap: 3, marginTop: 2 }}>
            {colores.slice(0, 6).map(c => {
              const match = window.COLORES.find(x => x.nombre === c);
              return <ColorDot key={c} hex={match?.hex || '#ccc'} size={8} />;
            })}
          </div>
        )}
      </div>
      <svg width="8" height="14" viewBox="0 0 8 14" style={{ flexShrink: 0, opacity: 0.35 }}>
        <path d="M1 1l6 6-6 6" stroke={theme.ink} strokeWidth="1.5" fill="none"
              strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Chip de filtro
// ─────────────────────────────────────────────────────────────
function FilterChip({ label, active, onClick, theme, colorDot }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '6px 11px', borderRadius: 999,
        background: active ? theme.accent : theme.card,
        color: active ? '#fff' : theme.ink,
        border: `0.5px solid ${active ? theme.accent : theme.border}`,
        fontSize: 12, fontWeight: 500, cursor: 'pointer',
        whiteSpace: 'nowrap', flexShrink: 0, font: 'inherit',
        letterSpacing: 0.1,
      }}>
      {colorDot && <ColorDot hex={colorDot} size={9} border={active ? 'rgba(255,255,255,0.5)' : 'rgba(0,0,0,0.12)'} />}
      <span style={{ fontSize: 12, fontWeight: active ? 600 : 500 }}>{label}</span>
    </button>
  );
}

Object.assign(window, {
  DressPlaceholder, ColorDot,
  coloresDeVestido, tejidosDeVestido,
  CatalogCard, CatalogRow, FilterChip,
});
