// form.jsx — formulario de alta/edición replicando la ficha de taller

function Field({ label, children, theme }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
      <span style={{
        fontSize: 10.5, fontWeight: 600, letterSpacing: 0.6,
        color: theme.muted, textTransform: 'uppercase',
      }}>{label}</span>
      {children}
    </label>
  );
}

function inputStyle(theme) {
  return {
    width: '100%', boxSizing: 'border-box', minWidth: 0,
    height: 38, padding: '0 12px', borderRadius: 10,
    border: `0.5px solid ${theme.border}`,
    background: theme.input, color: theme.ink,
    fontSize: 14, font: 'inherit', outline: 'none',
    WebkitAppearance: 'none',
  };
}
function textareaStyle(theme) {
  return { ...inputStyle(theme), height: 'auto', padding: '10px 12px', lineHeight: 1.4, resize: 'vertical', minHeight: 70 };
}

function FormSection({ title, subtitle, theme, children, action }) {
  return (
    <div style={{
      background: theme.card, borderRadius: 16,
      border: `0.5px solid ${theme.border}`,
      padding: '14px 14px 16px', marginBottom: 12,
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
        <div>
          <div style={{
            fontFamily: theme.serif, fontSize: 17, fontWeight: 500, color: theme.ink, lineHeight: 1.1,
          }}>{title}</div>
          {subtitle && (
            <div style={{ fontSize: 11, color: theme.muted, marginTop: 2 }}>{subtitle}</div>
          )}
        </div>
        {action}
      </div>
      {children}
    </div>
  );
}

function MaterialRow({ item, onChange, onRemove, idx, canRemove, theme }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', gap: 8,
      padding: '10px 10px', borderRadius: 12,
      background: theme.subtle, marginBottom: 8, position: 'relative',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{
          fontSize: 10.5, fontWeight: 600, letterSpacing: 0.5, color: theme.muted,
          textTransform: 'uppercase',
        }}>#{idx + 1}</div>
        {canRemove && (
          <button onClick={onRemove} type="button" style={{
            background: 'transparent', border: 0, color: theme.muted, cursor: 'pointer',
            fontSize: 11, padding: 4,
          }}>Quitar</button>
        )}
      </div>
      <Field label="Composición" theme={theme}>
        <input type="text" value={item.composicion} style={inputStyle(theme)}
               onChange={e => onChange({ ...item, composicion: e.target.value })}
               placeholder="ej. Mikado 100% seda" />
      </Field>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <Field label="Consumo" theme={theme}>
          <input type="text" value={item.consumo} style={inputStyle(theme)}
                 onChange={e => onChange({ ...item, consumo: e.target.value })}
                 placeholder="3,2 m" />
        </Field>
        <Field label="Ancho" theme={theme}>
          <input type="text" value={item.ancho} style={inputStyle(theme)}
                 onChange={e => onChange({ ...item, ancho: e.target.value })}
                 placeholder="140 cm" />
        </Field>
      </div>
    </div>
  );
}

function MaterialGroup({ label, items, onItemsChange, maxItems, theme }) {
  const add = () => onItemsChange([...items, { composicion: '', consumo: '', ancho: '' }]);
  const update = (i, v) => onItemsChange(items.map((x, idx) => idx === i ? v : x));
  const remove = (i) => onItemsChange(items.filter((_, idx) => idx !== i));
  return (
    <FormSection
      title={label}
      subtitle={`hasta ${maxItems}`}
      theme={theme}
      action={items.length < maxItems && (
        <button type="button" onClick={add} style={{
          background: 'transparent', border: `0.5px solid ${theme.border}`,
          color: theme.accent, borderRadius: 999, padding: '4px 10px',
          fontSize: 11, fontWeight: 500, cursor: 'pointer',
        }}>+ Añadir</button>
      )}>
      {items.map((it, i) => (
        <MaterialRow key={i} item={it} idx={i} theme={theme}
                     canRemove={items.length > 1}
                     onChange={(v) => update(i, v)} onRemove={() => remove(i)} />
      ))}
    </FormSection>
  );
}

function FornituraRow({ fkey, f, onChange, theme }) {
  const label = window.FORNITURAS_LABELS[fkey];
  const [expanded, setExpanded] = React.useState(!!(f.fabrica || f.color || f.medida || f.cantidad));
  const hasData = f.fabrica || f.color || f.medida || f.cantidad;
  return (
    <div style={{
      borderBottom: `0.5px solid ${theme.border}`,
      padding: '8px 0',
    }}>
      <button type="button" onClick={() => setExpanded(e => !e)} style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        width: '100%', background: 'transparent', border: 0, padding: '2px 0',
        font: 'inherit', color: 'inherit', cursor: 'pointer',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            fontFamily: theme.serif, fontSize: 15, fontWeight: 500, color: theme.ink,
          }}>{label}</span>
          {hasData && !expanded && (
            <span style={{
              fontSize: 11, color: theme.muted, letterSpacing: 0.2,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              maxWidth: 180,
            }}>
              {[f.fabrica, f.color, f.medida, f.cantidad].filter(Boolean).join(' · ')}
            </span>
          )}
        </div>
        <span style={{
          fontSize: 18, color: theme.muted, transform: expanded ? 'rotate(45deg)' : 'none',
          transition: 'transform .15s', lineHeight: 1,
        }}>+</span>
      </button>
      {expanded && (
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 10,
        }}>
          <Field label="Fábrica" theme={theme}>
            <input type="text" value={f.fabrica} style={inputStyle(theme)}
                   onChange={e => onChange({ ...f, fabrica: e.target.value })} />
          </Field>
          <Field label="Color" theme={theme}>
            <input type="text" value={f.color} style={inputStyle(theme)}
                   onChange={e => onChange({ ...f, color: e.target.value })}
                   list="colores-catalogo" />
          </Field>
          <Field label="Medida" theme={theme}>
            <input type="text" value={f.medida} style={inputStyle(theme)}
                   onChange={e => onChange({ ...f, medida: e.target.value })} />
          </Field>
          <Field label="Cantidad" theme={theme}>
            <input type="text" value={f.cantidad} style={inputStyle(theme)}
                   onChange={e => onChange({ ...f, cantidad: e.target.value })} />
          </Field>
        </div>
      )}
    </div>
  );
}

function FormView({ initial, theme, onCancel, onSave, title }) {
  const [v, setV] = React.useState(() => initial || window.VESTIDO_VACIO());
  const fileRef = React.useRef(null);

  const handleFoto = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => setV(prev => ({ ...prev, foto: reader.result }));
    reader.readAsDataURL(file);
  };

  const save = () => {
    if (!v.modelo.trim()) {
      alert('Pon al menos un nombre de modelo');
      return;
    }
    onSave(v);
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: theme.bg }}>
      <datalist id="colores-catalogo">
        {window.COLORES.map(c => <option key={c.id} value={c.nombre} />)}
      </datalist>

      {/* header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 16px 10px', flexShrink: 0,
      }}>
        <button onClick={onCancel} style={{
          background: 'transparent', border: 0, color: theme.accent,
          font: 'inherit', fontSize: 15, cursor: 'pointer', padding: 0,
        }}>Cancelar</button>
        <div style={{
          fontFamily: theme.serif, fontSize: 17, fontWeight: 500, color: theme.ink,
        }}>{title}</div>
        <button onClick={save} style={{
          background: 'transparent', border: 0, color: theme.accent,
          font: 'inherit', fontSize: 15, fontWeight: 600, cursor: 'pointer', padding: 0,
        }}>Guardar</button>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '0 14px 24px' }}>
        {/* ── Modelo ───────────────────────────── */}
        <FormSection title="Modelo" theme={theme}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {/* foto */}
            <div style={{
              aspectRatio: '4 / 3', borderRadius: 12, overflow: 'hidden',
              background: theme.placeholderBg, border: `0.5px solid ${theme.border}`,
              position: 'relative', cursor: 'pointer',
            }} onClick={() => fileRef.current?.click()}>
              {v.foto ? (
                <img src={v.foto} alt=""
                     style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              ) : (
                <window.DressPlaceholder seed={(v.modelo || '').charCodeAt(0) || 0}
                                          tone={theme.accent} bg={theme.placeholderBg} />
              )}
              <div style={{
                position: 'absolute', bottom: 8, right: 8,
                background: theme.chipBg, color: theme.chipFg,
                border: `0.5px solid ${theme.border}`,
                fontSize: 11, padding: '4px 10px', borderRadius: 999,
                backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
              }}>{v.foto ? 'Cambiar foto o boceto' : 'Añadir foto o boceto'}</div>
              <input ref={fileRef} type="file" accept="image/*"
                     style={{ display: 'none' }} onChange={handleFoto} />
            </div>
            <Field label="Nombre del modelo" theme={theme}>
              <input type="text" value={v.modelo} style={inputStyle(theme)}
                     onChange={e => setV({ ...v, modelo: e.target.value })}
                     placeholder="ej. Adela" />
            </Field>
            <Field label="Temporada" theme={theme}>
              <input type="text" value={v.temporada} style={inputStyle(theme)}
                     onChange={e => setV({ ...v, temporada: e.target.value })}
                     placeholder="ej. PV 25"
                     list="temporadas-catalogo" />
              <datalist id="temporadas-catalogo">
                {window.TEMPORADAS.map(t => <option key={t} value={t} />)}
              </datalist>
            </Field>
          </div>
        </FormSection>

        <MaterialGroup label="Tejidos" items={v.tejidos} maxItems={4} theme={theme}
                       onItemsChange={items => setV({ ...v, tejidos: items })} />
        <MaterialGroup label="Forros" items={v.forros} maxItems={2} theme={theme}
                       onItemsChange={items => setV({ ...v, forros: items })} />
        <MaterialGroup label="Entretelas" items={v.entretelas} maxItems={2} theme={theme}
                       onItemsChange={items => setV({ ...v, entretelas: items })} />

        {/* Fornituras */}
        <FormSection title="Fornituras" subtitle="rellena solo las que apliquen" theme={theme}>
          <div style={{ margin: '0 -4px' }}>
            {Object.keys(v.fornituras).map(fkey => (
              <FornituraRow key={fkey} fkey={fkey} f={v.fornituras[fkey]} theme={theme}
                            onChange={(nf) => setV({
                              ...v, fornituras: { ...v.fornituras, [fkey]: nf }
                            })} />
            ))}
          </div>
        </FormSection>

        <FormSection title="Fornituras especiales" theme={theme}>
          <textarea value={v.forniturasEspeciales} style={textareaStyle(theme)}
                    onChange={e => setV({ ...v, forniturasEspeciales: e.target.value })}
                    placeholder="Bordados, pedrería, aplicaciones…" />
        </FormSection>

        <FormSection title="Observaciones" theme={theme}>
          <textarea value={v.observaciones} style={textareaStyle(theme)}
                    onChange={e => setV({ ...v, observaciones: e.target.value })}
                    placeholder="Notas, pruebas, medidas especiales…" />
        </FormSection>

        <button onClick={save} style={{
          width: '100%', height: 48, borderRadius: 14,
          background: theme.accent, color: '#fff', border: 0,
          fontFamily: theme.serif, fontSize: 16, fontWeight: 500, letterSpacing: 0.3,
          cursor: 'pointer', marginTop: 4,
          boxShadow: '0 2px 8px rgba(180,140,100,0.25)',
        }}>Guardar vestido</button>
      </div>
    </div>
  );
}

Object.assign(window, { FormView });
