// CreateMarginAccount.jsx — Create Margin Account wizard (F3).
//
// 4-step modal: Select facility → Select settlement token → Deposit collateral
// → Review & confirm → "Account created" success screen.
// Replaces the single-step ActionModal create toast.

const CMA_STEPS = [
  { key: "facility",    label: "Select facility" },
  { key: "token",       label: "Settlement token" },
  { key: "collateral",  label: "Deposit collateral" },
  { key: "review",      label: "Review & confirm" },
];

const StepIndicator = ({ steps, current }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 0, marginBottom: "var(--space-24)" }}>
    {steps.map((s, i) => {
      const done = i < current;
      const active = i === current;
      return (
        <React.Fragment key={s.key}>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flex: 1, minWidth: 0 }}>
            <div style={{
              width: 28, height: 28, borderRadius: "50%",
              background: done ? "var(--accent)" : active ? "var(--accent)" : "var(--bg-alt)",
              border: done ? "none" : active ? "none" : "1.5px solid var(--border-strong)",
              display: "grid", placeItems: "center",
              font: '600 11px/1 "Inter", sans-serif',
              color: (done || active) ? "#fff" : "var(--fg-faint)",
              transition: "background var(--motion-fast)",
            }}>
              {done ? <Icon name="shieldCheck" size={13} stroke={2} /> : i + 1}
            </div>
            <div style={{
              font: '400 10px/14px "Inter", sans-serif',
              color: active ? "var(--fg)" : done ? "var(--fg-subtle)" : "var(--fg-faint)",
              textAlign: "center", marginTop: "var(--space-4)", maxWidth: 60,
              overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
            }}>{s.label}</div>
          </div>
          {i < steps.length - 1 && (
            <div style={{
              height: 1, flex: "0 0 16px",
              background: i < current ? "var(--accent)" : "var(--border)",
              marginBottom: "var(--space-16)",
              transition: "background var(--motion-fast)",
            }} />
          )}
        </React.Fragment>
      );
    })}
  </div>
);

const CreateMarginAccount = ({ facilities = [], onClose, onSuccess }) => {
  const [step, setStep] = React.useState(0);
  const [selectedFacility, setSelectedFacility] = React.useState(null);
  const [selectedToken, setSelectedToken] = React.useState("");
  const [collateralAmt, setCollateralAmt] = React.useState("");
  const [collateralToken, setCollateralToken] = React.useState("");

  // Escape closes the wizard, matching the backdrop-click and Cancel affordances.
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const activeFacilities = facilities.filter(f => f.statusVariant === "active");
  const facility = selectedFacility
    ? activeFacilities.find(f => f.id === selectedFacility)
    : null;
  const settlementTokens = facility ? facility.settlement : [];
  const collateralTokens = facility ? facility.collateral.map(c => c.ticker || c) : [];

  const mockAccountId = "ma-" + (1200 + Math.floor(activeFacilities.length * 17));

  const canNext = () => {
    if (step === 0) return !!selectedFacility;
    if (step === 1) return !!selectedToken;
    if (step === 2) return true;
    return false;
  };

  const handleNext = () => {
    if (step < 3) {
      if (step === 1 && !collateralToken && collateralTokens.length > 0) {
        setCollateralToken(collateralTokens[0]);
      }
      setStep(s => s + 1);
    }
  };

  return (
    <div role="dialog" aria-modal="true" aria-labelledby="cma-title" style={{
      position: "fixed", inset: 0, zIndex: 100,
      display: "grid", placeItems: "center",
      background: "var(--scrim)",
      animation: "fade 150ms ease-out",
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: "var(--surface)",
        width: 540, maxWidth: "calc(100vw - 32px)",
        borderRadius: "var(--radius-xl)", padding: "var(--space-24)",
        boxShadow: "var(--shadow-1)",
        animation: "rise 150ms ease-out",
        maxHeight: "calc(100vh - 48px)",
        overflowY: "auto",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "var(--space-8)" }}>
          <div>
            <Eyebrow>Margin accounts</Eyebrow>
            <h2 id="cma-title" style={{ margin: "var(--space-4) 0 0", font: '700 20px/26px "Figtree", sans-serif', color: "var(--fg)" }}>
              Create margin account
            </h2>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ all: "unset", cursor: "pointer", padding: "var(--space-8)", color: "var(--fg-subtle)" }}>
            <Icon name="cross" size={16} stroke={1.6} />
          </button>
        </div>

        <div style={{ marginTop: "var(--space-20)" }}>
          <StepIndicator steps={CMA_STEPS} current={step} />
        </div>

        {/* Step 0: Select facility */}
        {step === 0 && (
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-8)" }}>
            <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-8)" }}>
              Each margin account is scoped to one credit facility and its collateral / settlement rules.
            </div>
            {activeFacilities.slice(0, 6).map((f) => (
              <button key={f.id} type="button" onClick={() => setSelectedFacility(f.id)} style={{
                all: "unset", cursor: "pointer",
                display: "flex", alignItems: "center", justifyContent: "space-between",
                padding: "var(--space-16) var(--space-16)", borderRadius: "var(--radius-lg)",
                border: selectedFacility === f.id ? "1.5px solid var(--accent)" : "1px solid var(--border)",
                background: selectedFacility === f.id ? "var(--blue-10)" : "var(--bg-alt)",
                transition: "border-color var(--motion-fast), background var(--motion-fast)",
              }}>
                <div>
                  <div style={{ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)" }}>{f.name}</div>
                  <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: "var(--space-2)" }}>
                    {f.tranche} · {f.rate} · LTV {f.maxLtv}
                  </div>
                </div>
                <div style={{ width: 18, height: 18, borderRadius: "50%", border: "2px solid", borderColor: selectedFacility === f.id ? "var(--accent)" : "var(--border)", background: selectedFacility === f.id ? "var(--accent)" : "transparent", flexShrink: 0, transition: "all var(--motion-fast)" }} />
              </button>
            ))}
          </div>
        )}

        {/* Step 1: Settlement token */}
        {step === 1 && (
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-12)" }}>
            <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-4)" }}>
              Borrowed funds will settle in this token. You can change it per borrow later.
            </div>
            {settlementTokens.map((tok) => {
              const ticker = tok.ticker || tok;
              return (
                <button key={ticker} type="button" onClick={() => setSelectedToken(ticker)} style={{
                  all: "unset", cursor: "pointer",
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                  padding: "var(--space-16) var(--space-16)", borderRadius: "var(--radius-lg)",
                  border: selectedToken === ticker ? "1.5px solid var(--accent)" : "1px solid var(--border)",
                  background: selectedToken === ticker ? "var(--blue-10)" : "var(--bg-alt)",
                  transition: "border-color var(--motion-fast), background var(--motion-fast)",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: "var(--space-12)" }}>
                    <span className="chip chip--neutral" style={{ padding: "var(--space-4) var(--space-12)" }}>{ticker}</span>
                    <span style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
                      {ticker === "USDC" ? "USD Coin" : ticker === "USDT" ? "Tether USD" : ticker === "EURC" ? "Euro Coin" : ticker === "USD1" ? "USD1 Stablecoin" : ticker}
                    </span>
                  </div>
                  <div style={{ width: 18, height: 18, borderRadius: "50%", border: "2px solid", borderColor: selectedToken === ticker ? "var(--accent)" : "var(--border)", background: selectedToken === ticker ? "var(--accent)" : "transparent", flexShrink: 0 }} />
                </button>
              );
            })}
          </div>
        )}

        {/* Step 2: Deposit collateral */}
        {step === 2 && (
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
            <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
              Initial collateral deposit is optional — you can add it after the account is created. Choose a collateral token accepted by {facility?.name}.
            </div>
            {collateralTokens.length > 0 && (
              <>
                <div>
                  <label style={{ display: "block", font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-8)" }}>
                    Collateral token
                  </label>
                  <div style={{ display: "flex", gap: "var(--space-8)", flexWrap: "wrap" }}>
                    {collateralTokens.map((t) => (
                      <button key={t} type="button" onClick={() => setCollateralToken(t)} style={{
                        all: "unset", cursor: "pointer", padding: "var(--space-8) var(--space-16)", borderRadius: "var(--radius-md)",
                        border: collateralToken === t ? "1.5px solid var(--accent)" : "1px solid var(--border)",
                        background: collateralToken === t ? "var(--blue-10)" : "var(--bg-alt)",
                        font: '500 13px/18px "Inter", sans-serif',
                        color: collateralToken === t ? "var(--accent)" : "var(--fg)",
                        transition: "all var(--motion-fast)",
                      }}>{t}</button>
                    ))}
                  </div>
                </div>
                <div>
                  <label style={{ display: "block", font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-8)" }}>
                    Amount {collateralToken ? "(" + collateralToken + ")" : ""}
                  </label>
                  <div style={{ display: "flex", alignItems: "center", gap: "var(--space-8)", border: "1px solid var(--border-strong)", borderRadius: "var(--radius-md)", padding: "0 var(--space-12)" }}>
                    <input
                      value={collateralAmt}
                      onChange={(e) => setCollateralAmt(e.target.value)}
                      inputMode="decimal"
                      placeholder="0.00"
                      style={{ flex: 1, border: 0, outline: 0, font: '500 20px/28px "Figtree", sans-serif', color: "var(--fg)", background: "transparent", padding: "var(--space-12) 0", fontVariantNumeric: "tabular-nums" }}
                    />
                    {collateralToken && <span className="chip chip--neutral" style={{ padding: "var(--space-4) var(--space-8)" }}>{collateralToken}</span>}
                    <button className="btn btn--ghost btn--sm" type="button" onClick={() => setCollateralAmt("MAX")}>MAX</button>
                  </div>
                </div>
              </>
            )}
            <div style={{ padding: "var(--space-12) var(--space-16)", borderRadius: "var(--radius-md)", background: "var(--bg-alt)", font: '400 12px/18px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
              Skip this step to create the account first, then deposit collateral from the margin account view.
            </div>
          </div>
        )}

        {/* Step 3: Review */}
        {step === 3 && (
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
            <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
              Review the details before confirming. The account is created on-chain; this cannot be undone.
            </div>
            <div style={{ padding: "var(--space-16) var(--space-20)", background: "var(--bg-alt)", borderRadius: "var(--radius-lg)", display: "grid", gridTemplateColumns: "1fr 1fr", rowGap: "var(--space-12)", columnGap: "var(--space-16)" }}>
              {[
                { label: "Facility", value: facility?.name || "—" },
                { label: "Settlement", value: selectedToken || "—" },
                { label: "Initial collateral", value: collateralAmt ? collateralAmt + " " + collateralToken : "None — add after creation" },
                { label: "Account ID", value: mockAccountId },
              ].map(({ label, value }) => (
                <div key={label}>
                  <div style={{ font: '400 11px/14px "Inter", sans-serif', letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-faint)", marginBottom: "var(--space-4)" }}>{label}</div>
                  <div style={{ font: '500 13px/18px "Inter", sans-serif', color: "var(--fg)" }}>{value}</div>
                </div>
              ))}
            </div>
            <div style={{ font: 'italic 300 11px/16px "Literata", serif', color: "var(--fg-subtle)", textAlign: "center" }}>
              Compliance gates evaluated at transaction time.
            </div>
          </div>
        )}

        {/* Nav buttons */}
        <div style={{ display: "flex", gap: "var(--space-8)", justifyContent: "space-between", marginTop: "var(--space-24)" }}>
          <div>
            {step > 0 && (
              <button className="btn btn--secondary" type="button" onClick={() => setStep(s => s - 1)}>
                Back
              </button>
            )}
          </div>
          <div style={{ display: "flex", gap: "var(--space-8)" }}>
            <button className="btn btn--secondary" type="button" onClick={onClose}>Cancel</button>
            {step < 3 ? (
              <button className="btn btn--primary" type="button" disabled={!canNext()} onClick={handleNext}>
                Next <Icon name="arrow" size={13} stroke={1.6} />
              </button>
            ) : (
              <button className="btn btn--primary" type="button" onClick={() => onSuccess && onSuccess(mockAccountId)}>
                Create account
                <Icon name="arrow" size={13} stroke={1.6} />
              </button>
            )}
          </div>
        </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.CreateMarginAccount = CreateMarginAccount;
