// detail.jsx — vista ficha completa de un vestido

function FichaSection({ title, theme, children }) {
  return (
    <div style={{
      background: theme.card, borderRadius: 16,
      border: `0.5px solid ${theme.border}`,
      padding: '14px 16px', marginBottom: 10,
    }}>
      <div style={{
        fontSize: 10.5, fontWeight: 600, letterSpacing: 0.8,
        color: theme.muted, textTransform: 'uppercase',
        marginBottom: 10,
      }}>{title}</div>
      {children}
    </div>
  );
}

function KVTable({ rows, theme }) {
  // rows: [{ label, cells: [{k,v}, ...] }]
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {rows.map((r, i) => (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '1fr', gap: 3,
          paddingBottom: i < rows.length - 1 ? 8 : 0,
          borderBottom: i < rows.length - 1 ? `0.5px dashed ${theme.border}` : 'none',
        }}>
          <div style={{
            fontFamily: theme.serif, fontSize: 14, color: theme.ink, fontWeight: 500,
          }}>{r.label}</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '2px 12px' }}>
            {r.cells.filter(c => c.v).map((c, j) => (
              <span key={j} style={{ fontSize: 12, color: theme.muted, lineHeight: 1.5 }}>
                <span style={{ color: theme.mutedSoft }}>{c.k}</span>{' '}
                <span style={{ color: theme.ink }}>{c.v}</span>
              </span>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function DetailView({ vestido, theme, onBack, onEdit, onDuplicate, onDelete }) {
  if (!vestido) return null;
  const tejidos = (vestido.tejidos || []).filter(t => t.composicion);
  const forros = (vestido.forros || []).filter(t => t.composicion);
  const entretelas = (vestido.entretelas || []).filter(t => t.composicion);
  const fornRows = Object.entries(vestido.fornituras || {})
    .filter(([_, f]) => f && (f.fabrica || f.color || f.medida || f.cantidad))
    .map(([key, f]) => ({
      label: window.FORNITURAS_LABELS[key] || key,
      cells: [
        { k: 'Fábrica', v: f.fabrica },
        { k: 'Color', v: f.color },
        { k: 'Medida', v: f.medida },
        { k: 'Cantidad', v: f.cantidad },
      ],
    }));

  return (
    <div style={{
      height: '100%', display: 'flex', flexDirection: 'column',
      background: theme.bg,
    }}>
      {/* header con back */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 16px 10px', flexShrink: 0,
      }}>
        <button onClick={onBack} style={{
          display: 'flex', alignItems: 'center', gap: 4, background: 'transparent',
          border: 0, color: theme.accent, font: 'inherit', fontSize: 15, cursor: 'pointer',
          padding: 0,
        }}>
          <svg width="10" height="16" viewBox="0 0 10 16">
            <path d="M8 2L2 8l6 6" stroke={theme.accent} strokeWidth="2"
                  fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          Catálogo
        </button>
        <div style={{ display: 'flex', gap: 4 }}>
          <button onClick={onDuplicate} title="Duplicar" style={iconBtn(theme)}>
            <svg width="16" height="16" viewBox="0 0 16 16">
              <rect x="5" y="5" width="9" height="9" rx="1.5" fill="none" stroke={theme.ink} strokeWidth="1.3"/>
              <path d="M11 5V3.5A1.5 1.5 0 009.5 2H3.5A1.5 1.5 0 002 3.5v6A1.5 1.5 0 003.5 11H5"
                    fill="none" stroke={theme.ink} strokeWidth="1.3"/>
            </svg>
          </button>
          <button onClick={onEdit} title="Editar" style={iconBtn(theme)}>
            <svg width="16" height="16" viewBox="0 0 16 16">
              <path d="M11 2l3 3-8 8H3v-3l8-8z" fill="none" stroke={theme.ink} strokeWidth="1.3"
                    strokeLinejoin="round"/>
            </svg>
          </button>
          <button onClick={onDelete} title="Eliminar" style={iconBtn(theme)}>
            <svg width="16" height="16" viewBox="0 0 16 16">
              <path d="M3 5h10M6 5V3h4v2M5 5l.5 9h5L11 5" fill="none" stroke={theme.ink}
                    strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      </div>

      {/* content scroll */}
      <div style={{ flex: 1, overflow: 'auto', padding: '0 14px 24px' }}>
        {/* Cabecera: foto + modelo + temporada */}
        <div style={{
          background: theme.card, borderRadius: 22,
          border: `0.5px solid ${theme.border}`, overflow: 'hidden',
          marginBottom: 12,
        }}>
          <div style={{ aspectRatio: '1 / 1', background: theme.placeholderBg }}>
            {vestido.foto ? (
              <img src={vestido.foto} alt={vestido.modelo}
                   style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
            ) : (
              <window.DressPlaceholder seed={(vestido.modelo || '').charCodeAt(0) || 0}
                                tone={theme.accent} bg={theme.placeholderBg} />
            )}
          </div>
          <div style={{ padding: '16px 18px 18px' }}>
            <div style={{
              fontFamily: theme.serif, fontSize: 30, fontWeight: 500, color: theme.ink,
              lineHeight: 1, letterSpacing: 0.2,
            }}>{vestido.modelo || 'Sin nombre'}</div>
            {vestido.temporada && (
              <div style={{
                fontSize: 12, color: theme.muted, letterSpacing: 0.8,
                textTransform: 'uppercase', marginTop: 6,
              }}>{vestido.temporada}</div>
            )}
          </div>
        </div>

        {tejidos.length > 0 && (
          <FichaSection title="Tejidos" theme={theme}>
            <KVTable theme={theme} rows={tejidos.map((t, i) => ({
              label: `Tejido ${i + 1} — ${t.composicion}`,
              cells: [{ k: 'Consumo', v: t.consumo }, { k: 'Ancho', v: t.ancho }],
            }))} />
          </FichaSection>
        )}

        {forros.length > 0 && (
          <FichaSection title="Forros" theme={theme}>
            <KVTable theme={theme} rows={forros.map((t, i) => ({
              label: `Forro ${i + 1} — ${t.composicion}`,
              cells: [{ k: 'Consumo', v: t.consumo }, { k: 'Ancho', v: t.ancho }],
            }))} />
          </FichaSection>
        )}

        {entretelas.length > 0 && (
          <FichaSection title="Entretelas" theme={theme}>
            <KVTable theme={theme} rows={entretelas.map((t, i) => ({
              label: `Entretela ${i + 1} — ${t.composicion}`,
              cells: [{ k: 'Consumo', v: t.consumo }, { k: 'Ancho', v: t.ancho }],
            }))} />
          </FichaSection>
        )}

        {fornRows.length > 0 && (
          <FichaSection title="Fornituras" theme={theme}>
            <KVTable theme={theme} rows={fornRows} />
          </FichaSection>
        )}

        {vestido.forniturasEspeciales && (
          <FichaSection title="Fornituras especiales" theme={theme}>
            <div style={{ fontSize: 13.5, color: theme.ink, lineHeight: 1.5 }}>
              {vestido.forniturasEspeciales}
            </div>
          </FichaSection>
        )}

        {vestido.observaciones && (
          <FichaSection title="Observaciones" theme={theme}>
            <div style={{
              fontSize: 13.5, color: theme.ink, lineHeight: 1.5,
              fontStyle: 'italic',
            }}>{vestido.observaciones}</div>
          </FichaSection>
        )}
      </div>
    </div>
  );
}

function iconBtn(theme) {
  return {
    width: 34, height: 34, borderRadius: 10,
    background: theme.card, border: `0.5px solid ${theme.border}`,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', padding: 0,
  };
}

Object.assign(window, { DetailView });
