/* ANISAN — safety fallbacks. The UI kit prefers the compiled design-system
   components (window.ANISANDesignSystem_*). For components that gained NEW
   capabilities this turn (Select optgroup support, LedgerRow `category`), we
   capability-detect and OVERRIDE a stale bundle rather than defer with `||`,
   so classification works regardless of bundle-compile timing. */

window.Dialog = window.Dialog || function ({ open, title, onClose, children, footer, width = 460 }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div onMouseDown={(e) => { if (e.target === e.currentTarget) onClose && onClose(); }}
      style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(15,13,11,0.66)", backdropFilter: "blur(2px)", display: "grid", placeItems: "center", padding: 24 }}>
      <div style={{ width: "100%", maxWidth: width, maxHeight: "86vh", display: "flex", flexDirection: "column", background: "var(--surface)", border: "1px solid var(--hairline-strong)", borderRadius: "var(--radius)", boxShadow: "var(--shadow-overlay)", overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "18px 22px", borderBottom: "1px solid var(--hairline)" }}>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 19, fontWeight: 500, color: "var(--paper)" }}>{title}</span>
          <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--muted)", fontSize: 18 }}>✕</button>
        </div>
        <div style={{ padding: 22, overflow: "auto" }}>{children}</div>
        {footer && <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, padding: "16px 22px", borderTop: "1px solid var(--hairline)" }}>{footer}</div>}
      </div>
    </div>
  );
};

window.Input = window.Input || function ({ label, value, onChange, type = "text", placeholder, prefix, icon, variant = "box", accent = "var(--brass)", style = {}, inputStyle = {}, ...rest }) {
  const [focus, setFocus] = React.useState(false);
  const wrap = variant === "box"
    ? { display: "flex", alignItems: "center", gap: 9, background: "var(--ink)", border: `1px solid ${focus ? accent : "var(--hairline-strong)"}`, borderRadius: "var(--radius-sm)", padding: "10px 13px" }
    : { display: "flex", alignItems: "baseline", gap: 4, borderBottom: `1px solid ${focus ? accent : "var(--hairline-strong)"}` };
  return (
    <label style={{ display: "block", ...style }}>
      {label && <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 7 }}>{label}</span>}
      <span style={wrap}>
        {icon && <i data-lucide={icon} style={{ width: 15, height: 15, strokeWidth: 1.6, color: "var(--muted-2)", flexShrink: 0 }}></i>}
        {prefix && <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--muted-2)" }}>{prefix}</span>}
        <input type={type} value={value} placeholder={placeholder} onChange={(e) => onChange && onChange(e.target.value)} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
          style={{ flex: 1, minWidth: 0, background: "transparent", border: "none", outline: "none", color: "var(--paper)", fontFamily: "var(--font-body)", fontSize: 14, padding: variant === "box" ? 0 : "2px 0", ...inputStyle }} {...rest} />
      </span>
    </label>
  );
};

const FallbackSelect = function ({ label, value, onChange, options = [], placeholder, accent = "var(--brass)", style = {} }) {
  const [focus, setFocus] = React.useState(false);
  const renderOpt = (o) => { const v = typeof o === "object" ? o.value : o; const l = typeof o === "object" ? o.label : o; return <option key={v} value={v} style={{ background: "var(--surface)" }}>{l}</option>; };
  return (
    <label style={{ display: "block", ...style }}>
      {label && <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 7 }}>{label}</span>}
      <select value={value} onChange={(e) => onChange && onChange(e.target.value)} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{ width: "100%", background: "var(--ink)", color: "var(--paper)", border: `1px solid ${focus ? accent : "var(--hairline-strong)"}`, borderRadius: "var(--radius-sm)", padding: "10px 13px", fontFamily: "var(--font-body)", fontSize: 14, outline: "none", cursor: "pointer" }}>
        {placeholder && <option value="" style={{ background: "var(--surface)" }}>{placeholder}</option>}
        {options.map((o, i) => (o && o.options)
          ? <optgroup key={o.label || i} label={o.label}>{o.options.map(renderOpt)}</optgroup>
          : renderOpt(o))}
      </select>
    </label>
  );
};
// Override a stale bundled Select that lacks <optgroup> support.
if (!window.Select || !String(window.Select).includes("optgroup")) window.Select = FallbackSelect;

window.DateRange = window.DateRange || function ({ from, to, onChange, accent = "var(--brass)", style = {} }) {
  const field = { background: "transparent", border: "none", outline: "none", color: "var(--paper)", fontFamily: "var(--font-mono)", fontSize: 12, colorScheme: "dark", cursor: "pointer", padding: 0 };
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 9, background: "var(--surface)", border: "1px solid var(--hairline)", borderRadius: "var(--radius-pill)", padding: "8px 14px", ...style }}>
      <i data-lucide="calendar-range" style={{ width: 14, height: 14, strokeWidth: 1.6, color: accent }}></i>
      <input type="date" value={from} max={to || undefined} onChange={(e) => onChange && onChange({ from: e.target.value, to })} style={field} />
      <span style={{ color: "var(--muted-2)", fontFamily: "var(--font-mono)", fontSize: 12 }}>–</span>
      <input type="date" value={to} min={from || undefined} onChange={(e) => onChange && onChange({ from, to: e.target.value })} style={field} />
    </div>
  );
};

/* Category-aware LedgerRow — overrides a stale bundle that lacks the `category` badge. */
const FallbackLedgerRow = function ({ name, value, paid = false, dueDate, paidDate, category, onToggle, onEdit, onDelete, wording, style = {} }) {
  const W = Object.assign({ toggle: "Pago", toggleDone: "✓ Pago", pending: "Pendente", done: "Pago", due: "vence", doneAt: "pago em" }, wording || {});
  const [hover, setHover] = React.useState(false);
  const BRLn = (n) => (Number(n) || 0).toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const Btn = window.Button;
  return (
    <li onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 16px", paddingLeft: paid ? 13 : 16, borderBottom: "1px solid var(--hairline)", background: paid ? "var(--fill-positive)" : (hover ? "var(--surface-2)" : "transparent"), borderLeft: paid ? "3px solid var(--jade)" : "3px solid transparent", transition: "background .18s ease", ...style }}>
      <Btn size="sm" accent="var(--jade)" active={paid} onClick={onToggle} style={{ minWidth: 64, justifyContent: "center" }}>{paid ? W.toggleDone : W.toggle}</Btn>
      <button type="button" onClick={onEdit} title={onEdit ? "Editar lançamento" : undefined}
        style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 3, background: "none", border: "none", padding: "2px 0", textAlign: "left", cursor: onEdit ? "pointer" : "default" }}>
        <span style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "var(--paper)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name || "—"}</span>
        <span style={{ display: "flex", alignItems: "center", gap: 9, flexWrap: "wrap" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.04em", textTransform: "uppercase", color: paid ? "var(--jade)" : "var(--clay)" }}>● {paid ? W.done : W.pending}</span>
          {dueDate && <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--muted-2)" }}>{W.due} {dueDate}</span>}
          {paid && paidDate && <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--jade)" }}>{W.doneAt} {paidDate}</span>}
          {category && <span title={category} style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.03em", color: "var(--sand)", background: "var(--surface-2)", border: "1px solid var(--hairline)", borderRadius: "var(--radius-pill)", padding: "1px 8px", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 220 }}>{category}</span>}
        </span>
      </button>
      <span style={{ width: 110, flexShrink: 0, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--paper)" }}>R$ {BRLn(value)}</span>
      {onEdit && <Btn variant="ghost" size="sm" onClick={onEdit} style={{ borderRadius: "var(--radius-sm)", padding: "6px 9px" }}>✎</Btn>}
      {onDelete && <Btn variant="danger" size="sm" onClick={onDelete} style={{ borderRadius: "var(--radius-sm)" }}>×</Btn>}
    </li>
  );
};
// Override a stale bundled LedgerRow that lacks the `category`/`paidDate`/`wording` support.
if (!window.LedgerRow || !String(window.LedgerRow).includes("wording")) window.LedgerRow = FallbackLedgerRow;
