// ActionModal — handles Borrow / Deposit / Withdraw / Repay flows scoped
// to a margin account, or "create new account" when invoked from the header.

const ActionModal = ({ open, action, account, facility, onClose }) => {
  const [amount, setAmount] = React.useState("");
  React.useEffect(() => {
    if (open) {
      const focusable = document.getElementById("modal-amount-input");
      if (focusable) setTimeout(() => focusable.focus(), 60);
    } else {
      setAmount("");
    }
  }, [open]);

  if (!open) return null;

  const titles = {
    borrow:   { label: "Borrow against margin account", verb: "Borrow", token: facility?.settlement?.[0]?.ticker || "USDC" },
    deposit:  { label: "Deposit collateral", verb: "Deposit", token: facility?.collateral?.[0]?.ticker || "ABN" },
    withdraw: { label: "Withdraw collateral", verb: "Withdraw", token: facility?.collateral?.[0]?.ticker || "ABN" },
    repay:    { label: "Repay borrowed amount", verb: "Repay", token: facility?.settlement?.[0]?.ticker || "USDC" },
    create:   { label: "Create new margin account", verb: "Create account", token: "" },
  }[action] || { label: "Action", verb: "Confirm", token: "" };

  return (
    <div role="dialog" aria-modal="true" aria-labelledby="modal-title" style={{
      position: "fixed", inset: 0, zIndex: 100,
      display: "grid", placeItems: "center",
      background: "rgba(17,17,17,0.45)",
      animation: "fade 150ms ease-out",
    }} onClick={() => onClose({ confirm: false })}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: "var(--surface)",
        width: 480, maxWidth: "calc(100vw - 32px)",
        borderRadius: 16, padding: 28,
        boxShadow: "var(--shadow-1)",
        animation: "rise 150ms ease-out",
      }}>
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "flex-start",
          marginBottom: 18,
        }}>
          <div>
            <Eyebrow>{facility?.name}</Eyebrow>
            <h2 id="modal-title" style={{
              margin: "4px 0 0",
              font: '700 20px/26px "Figtree", sans-serif',
              color: "var(--fg)",
            }}>{titles.label}</h2>
            {account && (
              <div style={{
                marginTop: 6, font: '500 13px/18px "JetBrains Mono", monospace',
                color: "var(--fg-subtle)",
              }}>{account.id}</div>
            )}
          </div>
          <button onClick={() => onClose({ confirm: false })} aria-label="Close" style={{
            all: "unset", cursor: "pointer", padding: 6,
            color: "var(--fg-subtle)",
          }}>
            <Icon name="cross" size={16} stroke={1.6}/>
          </button>
        </div>

        {action !== "create" && (
          <>
            <label style={{
              display: "block",
              font: '400 12px/16px "Inter", sans-serif',
              color: "var(--fg-subtle)", marginBottom: 6,
            }}>Amount ({titles.token})</label>
            <div style={{
              display: "flex", alignItems: "center", gap: 8,
              border: "1px solid var(--border-strong)", borderRadius: 8,
              padding: "0 12px",
              transition: "border-color var(--motion-fast)",
            }}>
              <input
                id="modal-amount-input"
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                inputMode="decimal"
                placeholder="0.00"
                style={{
                  flex: 1, border: 0, outline: 0,
                  font: '500 22px/30px "Figtree", sans-serif',
                  color: "var(--fg)",
                  background: "transparent",
                  padding: "12px 0",
                  fontVariantNumeric: "tabular-nums",
                }}
              />
              <span className="chip chip--neutral" style={{ padding: "4px 8px" }}>
                {titles.token}
              </span>
              <button className="btn btn--ghost btn--sm" type="button" onClick={() => setAmount("MAX")}>MAX</button>
            </div>

            {account && (
              <div style={{
                marginTop: 16, padding: 14, background: "var(--bg-alt)", borderRadius: 8,
                display: "grid", gridTemplateColumns: "1fr 1fr", rowGap: 8, columnGap: 16,
                font: '400 12px/16px "Inter", sans-serif',
              }}>
                <span style={{ color: "var(--fg-subtle)" }}>Current health factor</span>
                <span className="tnum" style={{ color: "var(--fg)", textAlign: "right", fontWeight: 500 }}>{account.hf}</span>
                <span style={{ color: "var(--fg-subtle)" }}>Health factor after</span>
                <span className="tnum" style={{ color: "var(--success)", textAlign: "right", fontWeight: 500 }}>
                  {action === "borrow" ? "1.28" : action === "repay" ? "1.71" : action === "deposit" ? "1.86" : "1.24"} →
                </span>
                <span style={{ color: "var(--fg-subtle)" }}>Rate</span>
                <span className="tnum" style={{ color: "var(--fg)", textAlign: "right", fontWeight: 500 }}>5.5% APR</span>
              </div>
            )}
          </>
        )}

        {action === "create" && (
          <div style={{
            padding: 14, background: "var(--bg-alt)", borderRadius: 8,
            font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-muted)",
          }}>
            A new margin account isolates collateral and borrow positions. You can
            open multiple accounts to manage different risk profiles inside the
            same facility.
          </div>
        )}

        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 20 }}>
          <button className="btn btn--secondary" type="button" onClick={() => onClose({ confirm: false })}>Cancel</button>
          <button className="btn btn--primary" type="button" onClick={() => onClose({ confirm: true })}>
            {titles.verb}
            <Icon name="arrow" size={13} stroke={1.6}/>
          </button>
        </div>

        <div style={{
          marginTop: 14,
          font: 'italic 300 11px/16px "Literata", serif',
          color: "var(--fg-subtle)", textAlign: "center",
        }}>
          Compliance gates evaluated at transaction time.
        </div>
      </div>

      <style>{`
        @keyframes fade { from { opacity: 0 } to { opacity: 1 } }
        @keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: translateY(0) } }
      `}</style>
    </div>
  );
};

window.ActionModal = ActionModal;
