// Add Expense form — used as modal (desktop) or full-screen sheet (mobile).

const { useState: aeState, useMemo: aeMemo, useEffect: aeEffect, useRef: aeRef } = React;

function AddExpenseForm({ variant = "modal", onClose, onSave, onDelete, initial = null, accs: accsProp = null }) {
  const Icon = window.FinanzasIcon;
  const isEdit = !!initial;
  const liveAccs = accsProp || (window.finanzasStorage ? window.finanzasStorage.loadAccounts() : window.FINANZAS_ACCOUNTS);
  const defaultAcc = liveAccs[0]?.id || "efectivo";
  const defaultAccTo = liveAccs[1]?.id || liveAccs[0]?.id || "efectivo";
  const [type, setType] = aeState(initial ? (initial.amount > 0 ? "ingreso" : "gasto") : "gasto");
  const [amount, setAmount] = aeState(initial ? String(Math.abs(initial.amount)) : "");
  const [desc, setDesc] = aeState(initial?.desc || "");
  const [cat, setCat] = aeState(initial?.cat || null);
  const [acc, setAcc] = aeState(initial?.acc || defaultAcc);
  const [accTo, setAccTo] = aeState(defaultAccTo);
  const todayIso = new Date().toISOString().slice(0, 10);
  const initialDate = initial?.date ? String(initial.date).slice(0, 10) : todayIso;
  const [date, setDate] = aeState(initialDate);
  const [tags, setTags] = aeState((initial?.tags || []).filter(t => !t.startsWith("tr:")));

  // Auto-suggest category from description
  const suggested = aeMemo(() => window.suggestCategory(desc), [desc]);
  aeEffect(() => {
    if (suggested && !cat) setCat(suggested);
  }, [suggested]);

  const cats = type === "ingreso"
    ? window.FINANZAS_CATEGORIES.filter(c => c.id === "ingreso")
    : window.FINANZAS_CATEGORIES.filter(c => c.id !== "ingreso");

  const amountNum = parseFloat(amount || "0") || 0;
  const formattedAmount = amount === "" ? "0.00" : amountNum.toLocaleString("es-MX", { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  const isTransfer = type === "transferencia";
  const canSave = isTransfer
    ? (amountNum > 0 && acc && accTo && acc !== accTo)
    : (amountNum > 0 && desc.trim() && cat);

  const handleKeypad = (key) => {
    if (key === "back") {
      setAmount(a => a.slice(0, -1));
    } else if (key === ".") {
      if (!amount.includes(".")) setAmount(a => (a === "" ? "0." : a + "."));
    } else {
      if (amount.includes(".")) {
        const [, dec] = amount.split(".");
        if (dec && dec.length >= 2) return;
      }
      setAmount(a => (a === "0" ? key : a + key));
    }
  };

  const handleSave = () => {
    if (!canSave) return;
    const dateIso = `${date}T${new Date().toTimeString().slice(0, 5)}`;
    if (isTransfer) {
      onSave?.({
        kind: "transfer",
        amount: amountNum,
        from: acc, to: accTo,
        desc: desc.trim(),
        date: dateIso,
      });
      return;
    }
    onSave?.({
      ...(initial || {}),
      amount: (type === "ingreso" ? 1 : -1) * amountNum,
      desc: desc.trim(),
      cat, acc,
      tags,
      date: dateIso,
    });
  };

  const handleDelete = () => {
    if (!isEdit) return;
    if (!confirm("¿Borrar esta transacción?")) return;
    onDelete?.(initial);
  };

  const isMobile = variant === "sheet";

  // ───── MODAL (desktop) ──────────────────────────────────────
  if (!isMobile) {
    return (
      <div style={{
        position: "absolute", inset: 0, zIndex: 100,
        background: "rgba(13, 20, 48, 0.32)",
        backdropFilter: "blur(6px)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 24,
        animation: "finanzasFadeIn 220ms cubic-bezier(0.16,1,0.3,1)",
      }} onClick={onClose}>
        <div onClick={(e) => e.stopPropagation()} style={{
          background: "var(--bx-paper)",
          borderRadius: 14, width: 580, maxWidth: "100%",
          boxShadow: "0 32px 80px -24px rgba(13,20,48,.45)",
          overflow: "hidden",
          animation: "finanzasSlideUp 280ms cubic-bezier(0.16,1,0.3,1)",
        }}>
          {/* Header */}
          <div style={{
            padding: "20px 24px",
            display: "flex", alignItems: "center", justifyContent: "space-between",
            borderBottom: "1px solid var(--bx-line)",
          }}>
            <div style={{ display: "flex", gap: 4, background: "var(--bx-bg)", borderRadius: 8, padding: 4 }}>
              {[["gasto", "Gasto"], ["ingreso", "Ingreso"], ["transferencia", "Transferencia"]].map(([k, label]) => (
                <button key={k} onClick={() => { setType(k); setCat(null); }} style={{
                  padding: "6px 14px", fontSize: 12, fontWeight: 600,
                  fontFamily: "Inter, sans-serif",
                  letterSpacing: "0.04em", textTransform: "uppercase",
                  border: "none", borderRadius: 6, cursor: "pointer",
                  background: type === k ? "var(--bx-paper)" : "transparent",
                  color: type === k
                    ? (k === "ingreso" ? "var(--bx-success)"
                      : k === "transferencia" ? "var(--bx-navy-700)"
                      : "var(--bx-ink-1)")
                    : "var(--bx-ink-3)",
                  boxShadow: type === k ? "var(--bx-shadow-1)" : "none",
                  transition: "all 120ms",
                }}>{label}</button>
              ))}
            </div>
            <button onClick={onClose} style={{
              background: "transparent", border: "none", cursor: "pointer",
              width: 32, height: 32, borderRadius: 8,
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              color: "var(--bx-ink-3)",
            }}><Icon name="x" size={18} /></button>
          </div>

          {/* Amount */}
          <div style={{
            padding: "28px 24px",
            background: type === "ingreso" ? "rgba(42,138,95,0.06)"
              : isTransfer ? "rgba(26,42,94,0.04)" : "var(--bx-bg)",
            borderBottom: "1px solid var(--bx-line)",
            textAlign: "center",
            transition: "background 220ms",
          }}>
            <div style={{
              fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
              color: "var(--bx-ink-3)", fontWeight: 600, marginBottom: 8,
            }}>{type === "ingreso" ? "Ingreso en MXN" : isTransfer ? "Transferencia en MXN" : "Monto en MXN"}</div>
            <div style={{
              display: "inline-flex", alignItems: "baseline", gap: 6,
              fontFamily: "'Bebas Neue', sans-serif",
              color: type === "ingreso" ? "var(--bx-success)" : isTransfer ? "var(--bx-navy-700)" : "var(--bx-ink-1)",
            }}>
              <span style={{ fontSize: 32, opacity: amount === "" ? 0.4 : 1 }}>
                {type === "ingreso" ? "+" : isTransfer ? "" : "−"}$
              </span>
              <input
                value={formattedAmount}
                onChange={(e) => {
                  const v = e.target.value.replace(/[^\d.]/g, "");
                  setAmount(v);
                }}
                inputMode="decimal"
                style={{
                  background: "transparent", border: "none", outline: "none",
                  fontFamily: "'Bebas Neue', sans-serif",
                  fontSize: 64, color: "inherit", textAlign: "left",
                  width: `${Math.max(formattedAmount.length, 4) * 30}px`,
                  letterSpacing: "0.01em",
                  fontWeight: 400,
                  opacity: amount === "" ? 0.32 : 1,
                  padding: 0,
                }}
              />
            </div>
          </div>

          {/* Fields */}
          <div style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 16 }}>
            {isTransfer ? (
              <>
                <div style={{ display: "grid", gridTemplateColumns: "1fr auto 1fr", gap: 12, alignItems: "end" }}>
                  <Field label="Desde">
                    <AccountSelect value={acc} onChange={setAcc} accs={liveAccs} />
                  </Field>
                  <div style={{ paddingBottom: 10, color: "var(--bx-ink-3)" }}>
                    <Icon name="chevR" size={18} stroke={2} />
                  </div>
                  <Field label="Hacia">
                    <AccountSelect value={accTo} onChange={setAccTo} accs={liveAccs} />
                  </Field>
                </div>
                {acc && acc === accTo && (
                  <div style={{ fontSize: 12, color: "var(--bx-danger)" }}>
                    Origen y destino deben ser diferentes.
                  </div>
                )}
                <Field label="Nota (opcional)">
                  <input value={desc} onChange={(e) => setDesc(e.target.value)}
                    placeholder="ej. Pago tarjeta, mover ahorro"
                    style={inputStyle()} />
                </Field>
                <Field label="Fecha">
                  <input type="date" value={date} max={todayIso}
                    onChange={(e) => setDate(e.target.value)}
                    style={{ ...inputStyle(), fontFamily: "Inter, sans-serif" }} />
                </Field>
              </>
            ) : (
              <>
                <Field label="Descripción">
                  <input value={desc} onChange={(e) => setDesc(e.target.value)}
                    placeholder="ej. Starbucks Reforma"
                    style={inputStyle()} />
                  {suggested && cat === suggested && desc && (
                    <div style={{
                      fontSize: 11, color: "var(--bx-navy-700)", marginTop: 6,
                      display: "flex", alignItems: "center", gap: 6,
                    }}>
                      <Icon name="tag" size={11} />
                      Categoría sugerida: <strong>{window.catBy(suggested).label}</strong>
                    </div>
                  )}
                </Field>

                <Field label={type === "ingreso" ? "Tipo de ingreso" : "Categoría"}>
                  <CategoryGrid cats={cats} value={cat} onChange={setCat} />
                </Field>

                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  <Field label="Cuenta">
                    <AccountSelect value={acc} onChange={setAcc} accs={liveAccs} />
                  </Field>
                  <Field label="Fecha">
                    <input type="date" value={date} max={todayIso}
                      onChange={(e) => setDate(e.target.value)}
                      style={{ ...inputStyle(), fontFamily: "Inter, sans-serif" }} />
                  </Field>
                </div>
                <Field label="Etiquetas">
                  <TagPicker value={tags} onChange={setTags} />
                </Field>
              </>
            )}
          </div>

          {/* Footer */}
          <div style={{
            padding: "16px 24px",
            borderTop: "1px solid var(--bx-line)",
            display: "flex", justifyContent: "flex-end", gap: 12, alignItems: "center",
            background: "var(--bx-bg)",
          }}>
            {isEdit && (
              <button onClick={handleDelete} style={{
                padding: "10px 18px", fontSize: 12, fontFamily: "Inter, sans-serif",
                fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase",
                background: "transparent", color: "var(--bx-danger)", border: "none",
                borderRadius: 6, cursor: "pointer", marginRight: "auto",
              }}>Borrar</button>
            )}
            <button onClick={onClose} style={{
              padding: "10px 18px", fontSize: 12, fontFamily: "Inter, sans-serif",
              fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase",
              background: "transparent", color: "var(--bx-ink-2)", border: "none",
              borderRadius: 6, cursor: "pointer",
            }}>Cancelar</button>
            <button onClick={handleSave} disabled={!canSave} style={{
              padding: "12px 22px", fontSize: 13, fontFamily: "Inter, sans-serif",
              fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase",
              background: canSave ? "var(--bx-navy-700)" : "var(--bx-ink-4)",
              color: "#fff", border: "none", borderRadius: 6,
              cursor: canSave ? "pointer" : "not-allowed",
              transition: "background 120ms",
            }}>{isEdit ? "Actualizar" : isTransfer ? "Transferir" : `Guardar ${type}`}</button>
          </div>
        </div>
      </div>
    );
  }

  // ───── SHEET (mobile) ───────────────────────────────────────
  return (
    <div style={{
      position: "absolute", inset: 0, zIndex: 100,
      background: "rgba(13, 20, 48, 0.32)",
      display: "flex", alignItems: "flex-end", justifyContent: "stretch",
      animation: "finanzasFadeIn 220ms cubic-bezier(0.16,1,0.3,1)",
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: "var(--bx-paper)",
        borderTopLeftRadius: 20, borderTopRightRadius: 20,
        width: "100%", height: "92%",
        display: "flex", flexDirection: "column",
        animation: "finanzasSheetUp 320ms cubic-bezier(0.16,1,0.3,1)",
        overflow: "hidden",
      }}>
        {/* Grabber + tab type */}
        <div style={{ padding: "10px 0 0", display: "flex", justifyContent: "center" }}>
          <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--bx-line-2)" }} />
        </div>

        <div style={{
          padding: "16px 20px 12px",
          display: "flex", alignItems: "center", justifyContent: "space-between",
        }}>
          <div style={{ display: "flex", gap: 3, background: "var(--bx-bg)", borderRadius: 8, padding: 3 }}>
            {[["gasto", "Gasto"], ["ingreso", "Ingreso"], ["transferencia", "Transfer."]].map(([k, label]) => (
              <button key={k} onClick={() => { setType(k); setCat(null); }} style={{
                padding: "5px 10px", fontSize: 11, fontWeight: 600,
                fontFamily: "Inter, sans-serif",
                letterSpacing: "0.04em", textTransform: "uppercase",
                border: "none", borderRadius: 6, cursor: "pointer",
                background: type === k ? "var(--bx-paper)" : "transparent",
                color: type === k
                  ? (k === "ingreso" ? "var(--bx-success)"
                    : k === "transferencia" ? "var(--bx-navy-700)"
                    : "var(--bx-ink-1)")
                  : "var(--bx-ink-3)",
                boxShadow: type === k ? "var(--bx-shadow-1)" : "none",
              }}>{label}</button>
            ))}
          </div>
          <button onClick={onClose} style={{
            background: "var(--bx-bg)", border: "none", cursor: "pointer",
            width: 32, height: 32, borderRadius: 16,
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            color: "var(--bx-ink-2)",
          }}><Icon name="x" size={16} stroke={2} /></button>
        </div>

        {/* Amount input */}
        <div style={{
          padding: "12px 20px 20px",
          textAlign: "center",
          borderBottom: "1px solid var(--bx-line)",
        }}>
          <div style={{
            fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
            color: "var(--bx-ink-3)", fontWeight: 600, marginBottom: 6,
          }}>{type === "ingreso" ? "Ingreso" : isTransfer ? "Transferencia" : "Monto"} · MXN</div>
          <div style={{
            display: "inline-flex", alignItems: "baseline", justifyContent: "center", gap: 4,
            fontFamily: "'Bebas Neue', sans-serif",
            color: type === "ingreso" ? "var(--bx-success)" : isTransfer ? "var(--bx-navy-700)" : "var(--bx-ink-1)",
          }}>
            <span style={{ fontSize: 28, opacity: amount === "" ? 0.4 : 1 }}>
              {type === "ingreso" ? "+" : isTransfer ? "" : "−"}$
            </span>
            <input
              value={formattedAmount}
              onChange={(e) => setAmount(e.target.value.replace(/[^\d.]/g, ""))}
              inputMode="decimal"
              style={{
                background: "transparent", border: "none", outline: "none",
                fontFamily: "'Bebas Neue', sans-serif",
                fontSize: 56, color: "inherit", textAlign: "left",
                width: `${Math.max(formattedAmount.length, 4) * 26}px`,
                letterSpacing: "0.01em", fontWeight: 400, padding: 0,
                opacity: amount === "" ? 0.32 : 1,
              }}
            />
          </div>
        </div>

        {/* Form (scrollable) */}
        <div style={{ flex: 1, overflowY: "auto", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 14 }}>
          {isTransfer ? (
            <>
              <div>
                <div style={labelStyle()}>Desde</div>
                <AccountSelect value={acc} onChange={setAcc} accs={liveAccs} />
              </div>
              <div>
                <div style={labelStyle()}>Hacia</div>
                <AccountSelect value={accTo} onChange={setAccTo} accs={liveAccs} />
              </div>
              {acc && acc === accTo && (
                <div style={{ fontSize: 12, color: "var(--bx-danger)" }}>
                  Origen y destino deben ser diferentes.
                </div>
              )}
              <input value={desc} onChange={(e) => setDesc(e.target.value)}
                placeholder="Nota (opcional)"
                style={{ ...inputStyle(), fontSize: 15 }} />
              <div>
                <div style={labelStyle()}>Fecha</div>
                <input type="date" value={date} max={todayIso}
                  onChange={(e) => setDate(e.target.value)}
                  style={{ ...inputStyle(), fontSize: 14 }} />
              </div>
            </>
          ) : (
            <>
              <input value={desc} onChange={(e) => setDesc(e.target.value)}
                placeholder="¿En qué gastaste?"
                style={{ ...inputStyle(), fontSize: 15 }} />

              <div>
                <div style={labelStyle()}>{type === "ingreso" ? "Tipo" : "Categoría"}</div>
                <CategoryGrid cats={cats} value={cat} onChange={setCat} cols={4} />
              </div>

              <div>
                <div style={labelStyle()}>Cuenta</div>
                <AccountSelect value={acc} onChange={setAcc} accs={liveAccs} />
              </div>

              <div>
                <div style={labelStyle()}>Fecha</div>
                <input type="date" value={date} max={todayIso}
                  onChange={(e) => setDate(e.target.value)}
                  style={{ ...inputStyle(), fontSize: 14 }} />
              </div>
              <div>
                <div style={labelStyle()}>Etiquetas</div>
                <TagPicker value={tags} onChange={setTags} />
              </div>
            </>
          )}
        </div>

        {/* Save button */}
        <div style={{ padding: "12px 20px 24px", borderTop: "1px solid var(--bx-line)", display: "flex", gap: 10 }}>
          {isEdit && (
            <button onClick={handleDelete} style={{
              padding: "16px 20px",
              fontSize: 14, fontFamily: "Inter, sans-serif",
              fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase",
              background: "transparent", color: "var(--bx-danger)",
              border: "1px solid var(--bx-danger)", borderRadius: 10,
              cursor: "pointer",
            }}>Borrar</button>
          )}
          <button onClick={handleSave} disabled={!canSave} style={{
            flex: 1, padding: "16px",
            fontSize: 14, fontFamily: "Inter, sans-serif",
            fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase",
            background: canSave ? "var(--bx-navy-700)" : "var(--bx-ink-4)",
            color: "#fff", border: "none", borderRadius: 10,
            cursor: canSave ? "pointer" : "not-allowed",
          }}>{isEdit ? "Actualizar" : isTransfer ? "Transferir" : `Guardar ${type}`}</button>
        </div>
      </div>
    </div>
  );
}

// ───── small primitives ─────────────────────────────────────
function Field({ label, children }) {
  return (
    <div>
      <div style={labelStyle()}>{label}</div>
      {children}
    </div>
  );
}

function labelStyle() {
  return {
    fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase",
    color: "var(--bx-ink-3)", fontWeight: 600, marginBottom: 8,
    fontFamily: "Inter, sans-serif",
  };
}

function inputStyle() {
  return {
    width: "100%", padding: "10px 12px",
    background: "var(--bx-bg)",
    border: "1px solid var(--bx-line)",
    borderRadius: 8,
    fontSize: 14, fontFamily: "Inter, sans-serif", color: "var(--bx-ink-1)",
    outline: "none",
  };
}

function CategoryGrid({ cats, value, onChange, cols = 5 }) {
  const Icon = window.FinanzasIcon;
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 8 }}>
      {cats.map(c => {
        const sel = c.id === value;
        return (
          <button key={c.id} onClick={() => onChange(c.id)} style={{
            background: sel ? `${c.color}14` : "var(--bx-bg)",
            border: `1px solid ${sel ? c.color : "var(--bx-line)"}`,
            borderRadius: 10, padding: "10px 6px",
            display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
            cursor: "pointer", transition: "all 120ms",
          }}>
            <div style={{
              width: 30, height: 30, borderRadius: 15,
              background: sel ? c.color : `${c.color}1A`,
              color: sel ? "#fff" : c.color,
              display: "inline-flex", alignItems: "center", justifyContent: "center",
            }}>
              <Icon name={c.icon} size={15} stroke={2} />
            </div>
            <div style={{
              fontSize: 10, fontWeight: 600,
              color: sel ? c.color : "var(--bx-ink-2)",
              fontFamily: "Inter, sans-serif",
              textAlign: "center", lineHeight: 1.2,
            }}>{c.label}</div>
          </button>
        );
      })}
    </div>
  );
}

function AccountSelect({ value, onChange, accs: accsProp = null }) {
  const Icon = window.FinanzasIcon;
  const [open, setOpen] = aeState(false);
  const liveAccs = accsProp || (window.finanzasStorage ? window.finanzasStorage.loadAccounts() : window.FINANZAS_ACCOUNTS);
  const acc = window.accBy(value) || liveAccs[0];
  if (!acc) {
    return (
      <div style={{ ...inputStyle(), color: "var(--bx-ink-3)" }}>
        Sin cuentas. Crea una en Cuentas.
      </div>
    );
  }
  return (
    <div style={{ position: "relative" }}>
      <button onClick={() => setOpen(o => !o)} style={{
        ...inputStyle(),
        display: "flex", alignItems: "center", justifyContent: "space-between",
        cursor: "pointer", textAlign: "left",
      }}>
        <span style={{ display: "flex", gap: 8, alignItems: "center", overflow: "hidden" }}>
          <span style={{
            width: 8, height: 8, borderRadius: 4, background: acc.color, flexShrink: 0,
          }} />
          <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", fontSize: 13 }}>
            {acc.name}{acc.last4 ? ` ··${acc.last4}` : ""}
          </span>
        </span>
        <Icon name="chevDown" size={14} style={{ color: "var(--bx-ink-3)" }} />
      </button>
      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0,
          background: "var(--bx-paper)", border: "1px solid var(--bx-line)",
          borderRadius: 8, boxShadow: "var(--bx-shadow-3)", zIndex: 10,
          padding: 4,
        }}>
          {liveAccs.map(a => (
            <button key={a.id} onClick={() => { onChange(a.id); setOpen(false); }} style={{
              width: "100%", padding: "8px 10px",
              display: "flex", alignItems: "center", gap: 10,
              background: a.id === value ? "var(--bx-bg)" : "transparent",
              border: "none", borderRadius: 6, cursor: "pointer", textAlign: "left",
              fontSize: 13, color: "var(--bx-ink-1)", fontFamily: "Inter, sans-serif",
            }}>
              <span style={{ width: 8, height: 8, borderRadius: 4, background: a.color }} />
              <span style={{ flex: 1 }}>{a.name}{a.last4 ? ` ··${a.last4}` : ""}</span>
              <span style={{ fontSize: 11, color: "var(--bx-ink-3)" }}>{a.type}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function TagPicker({ value, onChange }) {
  const Icon = window.FinanzasIcon;
  const PRESET = ["recurring", "viaje", "trabajo", "importante", "regalo"];
  const LABELS = { recurring: "Recurrente", viaje: "Viaje", trabajo: "Trabajo", importante: "Importante", regalo: "Regalo" };
  const [custom, setCustom] = aeState("");
  const toggle = (t) => {
    onChange(value.includes(t) ? value.filter(x => x !== t) : [...value, t]);
  };
  const addCustom = () => {
    const t = custom.trim().toLowerCase().replace(/\s+/g, "-").slice(0, 20);
    if (!t || value.includes(t)) { setCustom(""); return; }
    onChange([...value, t]);
    setCustom("");
  };
  return (
    <div>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
        {PRESET.map(t => {
          const sel = value.includes(t);
          return (
            <button key={t} type="button" onClick={() => toggle(t)} style={{
              padding: "6px 12px", fontSize: 11, fontWeight: 600,
              fontFamily: "Inter, sans-serif", letterSpacing: "0.04em",
              background: sel ? "var(--bx-navy-700)" : "var(--bx-bg)",
              color: sel ? "#fff" : "var(--bx-ink-2)",
              border: `1px solid ${sel ? "var(--bx-navy-700)" : "var(--bx-line)"}`,
              borderRadius: 999, cursor: "pointer",
            }}>{LABELS[t] || t}</button>
          );
        })}
        {value.filter(t => !PRESET.includes(t)).map(t => (
          <button key={t} type="button" onClick={() => toggle(t)} style={{
            padding: "6px 12px", fontSize: 11, fontWeight: 600,
            fontFamily: "Inter, sans-serif", letterSpacing: "0.04em",
            background: "var(--bx-navy-700)", color: "#fff",
            border: "1px solid var(--bx-navy-700)",
            borderRadius: 999, cursor: "pointer",
            display: "inline-flex", alignItems: "center", gap: 4,
          }}>{t} <Icon name="x" size={10} stroke={2.5} /></button>
        ))}
      </div>
      <div style={{ display: "flex", gap: 6, marginTop: 8 }}>
        <input value={custom} onChange={(e) => setCustom(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addCustom())}
          placeholder="Nueva etiqueta…"
          style={{ ...inputStyle(), fontSize: 12, padding: "8px 10px" }} />
        <button type="button" onClick={addCustom} style={{
          padding: "8px 14px", fontSize: 12, fontWeight: 600,
          background: "var(--bx-bg)", color: "var(--bx-ink-2)",
          border: "1px solid var(--bx-line)", borderRadius: 8, cursor: "pointer",
        }}>+</button>
      </div>
    </div>
  );
}

Object.assign(window, { AddExpenseForm });
