// DeployFacilityWizard.jsx — F2. Seven-step deploy-facility flow ending in a
// simulated transaction sequence and a success screen. Replaces the old
// onAction("deploy") info toast. All mock/in-memory; ONCHAINID all-caps.
//
// Steps: Facility, Modules, Identity registry, Access control, Collateral,
// Settlement, Review. Reuses Icon (deploy/check/copy/play), plain selects/inputs
// in the ComplianceForm style, and the success-checkmark pattern.

const WIZ_STEPS = ["Facility", "Modules", "Identity registry", "Access control", "Collateral", "Settlement", "Review"];
const DEPLOY_SEQ = [
  "Deploying facility contract...",
  "Configuring modules...",
  "Configuring registries...",
  "Setting access control...",
  "Whitelisting collateral...",
  "Configuring settlement tokens...",
  "Finalizing setup...",
];
const PREDICTED_ONCHAINID = "0x7F2c4aE9D1b3F5c8d0A6e7B4f2C9a1D3E5f7A8aB";

// ── inputs ───────────────────────────────────────────────────────────────
const wInput = { width: "100%", height: 40, padding: "0 var(--space-12)", boxSizing: "border-box", borderRadius: "var(--radius-md)", border: "1px solid var(--border-strong)", background: "var(--surface)", color: "var(--fg)", font: '400 14px "Inter", sans-serif' };
const WLabel = ({ children }) => <label style={{ display: "block", font: '500 13px/18px "Inter", sans-serif', color: "var(--fg)", marginBottom: "var(--space-8)" }}>{children}</label>;
const WSelect = ({ value, onChange, options }) => (
  <select value={value} onChange={(e) => onChange(e.target.value)} style={wInput}>
    {options.map((o) => <option key={o} value={o}>{o}</option>)}
  </select>
);
const ParamPanel = ({ desc, params }) => (
  <div style={{ marginTop: "var(--space-12)", padding: "var(--space-12) var(--space-16)", background: "var(--bg-alt)", borderRadius: "var(--radius-md)" }}>
    <div style={{ font: '400 12px/18px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: params.length ? 8 : 0 }}>{desc}</div>
    {params.length > 0 && (
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "4px 16px" }}>
        {params.map(([k, v], i) => (
          <div key={i} style={{ display: "flex", justifyContent: "space-between", gap: "var(--space-8)" }}>
            <span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{k}</span>
            <span className="tnum" style={{ font: '500 12px "Inter", sans-serif', color: "var(--fg)" }}>{v}</span>
          </div>
        ))}
      </div>
    )}
  </div>
);
const ModulePick = ({ label, options, value, onChange }) => {
  const sel = options.find((o) => o.name === value) || options[0];
  return (
    <div>
      <WLabel>{label}</WLabel>
      <WSelect value={value} onChange={onChange} options={options.map((o) => o.name)} />
      <ParamPanel desc={sel.desc} params={sel.params} />
    </div>
  );
};

const WizCard = ({ title, lede, children }) => (
  <section className="card" style={{ padding: 0 }}>
    <div style={{ padding: "var(--space-20) var(--space-24) var(--space-16)", borderBottom: "1px solid var(--border)" }}>
      <h3 style={{ margin: 0, font: '600 16px/22px "Figtree", sans-serif', color: "var(--fg)", letterSpacing: "-0.005em" }}>{title}</h3>
      {lede && <div style={{ marginTop: "var(--space-4)", font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{lede}</div>}
    </div>
    <div style={{ padding: "var(--space-24)" }}>{children}</div>
  </section>
);

const ReviewRow = ({ label, value }) => (
  <div style={{ display: "flex", justifyContent: "space-between", gap: "var(--space-16)", padding: "var(--space-12) 0", borderTop: "1px solid var(--border)" }}>
    <span style={{ font: '400 13px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{label}</span>
    <span style={{ font: '500 13px "Inter", sans-serif', color: "var(--fg)", textAlign: "right", maxWidth: "60%" }}>{value}</span>
  </div>
);

// ── the wizard ─────────────────────────────────────────────────────────--
const DeployFacilityWizard = ({ onCancel, onDeployed }) => {
  const O = window.DEPLOY_WIZARD_OPTIONS;
  const [step, setStep] = React.useState(0);
  const [deploying, setDeploying] = React.useState(false);
  const [seq, setSeq] = React.useState(0);
  const [done, setDone] = React.useState(false);

  const [name, setName] = React.useState("Orion Prime Credit Facility");
  const [mods, setMods] = React.useState({ risk: O.risk[0].name, auction: O.auction[0].name, valuation: O.valuation[0].name, liquidity: O.liquidity[0].name, fee: O.fee[0].name, compliance: O.compliance[0].name });
  const [regIdx, setRegIdx] = React.useState(0);
  const [owner, setOwner] = React.useState("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0");
  const [operators, setOperators] = React.useState([""]);
  const [ddfContracts, setDdf] = React.useState([""]);
  const [collateral, setCollateral] = React.useState([{ token: "BUIDL", haircut: "25", liq: "160", minHF: "1.1" }]);
  const [settlement, setSettlement] = React.useState([{ denom: "USD", token: "USDC", rate: "6.25" }]);

  // Deploy sequence (timer-driven, cleaned up on unmount)
  React.useEffect(() => {
    if (!deploying) return undefined;
    if (seq >= DEPLOY_SEQ.length) { const id = setTimeout(() => setDone(true), 300); return () => clearTimeout(id); }
    const id = setTimeout(() => setSeq((s) => s + 1), 480);
    return () => clearTimeout(id);
  }, [deploying, seq]);

  const setMod = (k) => (v) => setMods((m) => ({ ...m, [k]: v }));
  const reg = O.registries[regIdx];

  // ── success ──
  if (done) {
    const newFacility = (() => {
      const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "").slice(0, 16) || "new";
      return { id: "cf-" + slug, name, token: settlement[0] ? settlement[0].token : "USDC", status: "active", tvl: 0, utilization: 0, accounts: 0, rate: parseFloat(settlement[0] && settlement[0].rate) || 5, warn: 0, default: 0, tranche: "Senior tranche", lastActor: "admin@ascend.io", lastAction: "DEPLOY", lastAt: new Date().toISOString() };
    })();
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-20)" }}>
        <PageHeader eyebrow="Credit facilities" title="Set up credit facility" icon="deploy" lede="Complete the guided workflow to deploy and configure a new credit facility." />
        <section className="card" style={{ padding: "var(--space-36) var(--space-24)", display: "flex", flexDirection: "column", alignItems: "center", gap: "var(--space-16)", textAlign: "center" }}>
          <span style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--green-10)", color: "var(--success)", display: "grid", placeItems: "center" }}>
            <Icon name="check" size={32} stroke={2} />
          </span>
          <h2 style={{ margin: 0, font: '700 24px/30px "Figtree", sans-serif', color: "var(--fg)", letterSpacing: "-0.01em" }}>Credit facility setup complete</h2>
          <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)", maxWidth: 460 }}>
            Your new credit facility “{name}” has been fully configured and deployed.
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: "var(--space-8)", padding: "var(--space-12) var(--space-16)", background: "var(--bg-alt)", borderRadius: "var(--radius-md)" }}>
            <span style={{ font: '400 13px "Inter", sans-serif', color: "var(--fg-subtle)" }}>Tx hash</span>
            <MonoAddr full="0x8a3b7d1e4f5c6a7b8c9d0e1f2a3b4c5d6e7f0f1a2b3c" />
          </div>
          <button type="button" onClick={() => onDeployed(newFacility)} className="btn btn--primary" style={{ marginTop: "var(--space-4)" }}>
            <Icon name="arrow" size={14} stroke={1.6} /> View created facility
          </button>
        </section>
      </div>
    );
  }

  // ── deploying sequence ──
  if (deploying) {
    const cur = Math.min(seq, DEPLOY_SEQ.length - 1);
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-20)" }}>
        <PageHeader eyebrow="Credit facilities" title="Set up credit facility" icon="deploy" lede="Executing the setup sequence. Keep your wallet connected." />
        <section className="card" style={{ padding: "var(--space-36) var(--space-24)", display: "flex", flexDirection: "column", alignItems: "center", gap: "var(--space-20)" }}>
          <div style={{ width: 40, height: 40, border: "3px solid var(--border)", borderTopColor: "var(--accent)", borderRadius: "50%", animation: "wspin 0.8s linear infinite" }} />
          <div style={{ textAlign: "center" }}>
            <div style={{ font: '600 16px/22px "Figtree", sans-serif', color: "var(--fg)" }}>{DEPLOY_SEQ[cur]}</div>
            <div className="tnum" style={{ marginTop: "var(--space-4)", font: '400 13px "Inter", sans-serif', color: "var(--fg-subtle)" }}>Step {cur + 1} of {DEPLOY_SEQ.length}</div>
          </div>
          <style>{"@keyframes wspin{to{transform:rotate(360deg)}}"}</style>
        </section>
      </div>
    );
  }

  // ── stepper + step panels ──
  const canNext = step !== 0 || name.trim().length > 0;
  const last = step === WIZ_STEPS.length - 1;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-20)" }}>
      <PageHeader eyebrow="Credit facilities" title="Set up credit facility" icon="deploy" lede="Complete the guided workflow to deploy and configure a new credit facility." />

      {/* Stepper */}
      <div style={{ display: "flex", alignItems: "center", gap: 0, overflowX: "auto", padding: "var(--space-4) var(--space-2)" }}>
        {WIZ_STEPS.map((s, i) => (
          <React.Fragment key={s}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "var(--space-8)", minWidth: 84 }}>
              <span style={{
                width: 28, height: 28, borderRadius: "50%", display: "grid", placeItems: "center",
                font: '600 12px "Inter", sans-serif',
                background: i < step ? "var(--accent)" : i === step ? "var(--accent)" : "var(--bg-alt)",
                color: i <= step ? "var(--white-100)" : "var(--fg-subtle)",
                border: i <= step ? "none" : "1px solid var(--border-strong)",
              }}>{i < step ? <Icon name="check" size={14} stroke={2.2} /> : i + 1}</span>
              <span style={{ font: '500 11px/14px "Inter", sans-serif', color: i === step ? "var(--fg)" : "var(--fg-subtle)", whiteSpace: "nowrap" }}>{s}</span>
            </div>
            {i < WIZ_STEPS.length - 1 && <div style={{ flex: 1, height: 1, minWidth: 16, background: i < step ? "var(--accent)" : "var(--border)" }} />}
          </React.Fragment>
        ))}
      </div>

      {/* Step 0 — Facility */}
      {step === 0 && (
        <WizCard title="Facility details" lede="Initialize the basic parameters for your new credit facility.">
          <WLabel>Facility name *</WLabel>
          <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Facility name" style={wInput} />
        </WizCard>
      )}

      {/* Step 1 — Modules */}
      {step === 1 && (
        <WizCard title="Bootstrap configuration" lede="Select the core modules that will power this facility.">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-20)" }}>
            <ModulePick label="Risk module" options={O.risk} value={mods.risk} onChange={setMod("risk")} />
            <ModulePick label="Auction module" options={O.auction} value={mods.auction} onChange={setMod("auction")} />
            <ModulePick label="Valuation module" options={O.valuation} value={mods.valuation} onChange={setMod("valuation")} />
            <ModulePick label="Liquidity module" options={O.liquidity} value={mods.liquidity} onChange={setMod("liquidity")} />
            <ModulePick label="Fee module" options={O.fee} value={mods.fee} onChange={setMod("fee")} />
            <ModulePick label="Compliance module" options={O.compliance} value={mods.compliance} onChange={setMod("compliance")} />
          </div>
          <div style={{ marginTop: "var(--space-20)", padding: "var(--space-16) var(--space-16)", background: "var(--bg-alt)", borderRadius: "var(--radius-lg)" }}>
            <div style={{ font: '500 11px/16px "Inter", sans-serif', letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg-subtle)", marginBottom: "var(--space-8)" }}>Selected module stack</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: "var(--space-8)" }}>
              {["Chainlink (Oracle)", mods.risk, mods.fee, mods.auction, mods.compliance].map((m, i) => (
                <span key={i} className="chip chip--neutral" style={{ padding: "var(--space-4) var(--space-12)" }}>{m}</span>
              ))}
            </div>
          </div>
        </WizCard>
      )}

      {/* Step 2 — Identity registry */}
      {step === 2 && (
        <WizCard title="Identity registry" lede="Bind this credit facility to an Identity Registry, the gate that decides which wallets may use it based on their ONCHAINID claims.">
          <WLabel>Identity Registry</WLabel>
          <WSelect value={reg.label} onChange={(v) => setRegIdx(O.registries.findIndex((r) => r.label === v))} options={O.registries.map((r) => r.label)} />
          <ParamPanel desc={reg.policy} params={[["Jurisdiction", reg.jurisdiction], ["Trusted issuer", reg.issuer]]} />
          <div style={{ marginTop: "var(--space-16)" }}>
            <div style={{ font: '500 13px "Inter", sans-serif', color: "var(--fg)", marginBottom: "var(--space-8)" }}>Required claim topics</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: "var(--space-8)" }}>
              {O.claimTopics.map((t) => <span key={t} className="chip chip--neutral" style={{ padding: "var(--space-4) var(--space-12)" }}>{t}</span>)}
            </div>
          </div>
          <div style={{ marginTop: "var(--space-16)", padding: "var(--space-12) var(--space-16)", background: "var(--bg-alt)", borderRadius: "var(--radius-md)" }}>
            <div style={{ font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>Facility ONCHAINID</div>
            <div style={{ font: '400 12px/18px "Inter", sans-serif', color: "var(--fg-subtle)", margin: "var(--space-4) 0 var(--space-8)" }}>
              On deploy, the platform mints a new ONCHAINID for this facility via <span style={{ fontFamily: "var(--font-mono)" }}>IdFactory.createTokenIdentity</span> so it can hold and receive ERC-3643 collateral.
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: "var(--space-8)" }}>
              <span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>Predicted address</span>
              <MonoAddr full={PREDICTED_ONCHAINID} />
            </div>
          </div>
        </WizCard>
      )}

      {/* Step 3 — Access control */}
      {step === 3 && (
        <WizCard title="Access control" lede="Bootstrap admin role membership at deploy. Ongoing role management lives on the facility's Access control tab post-deploy.">
          <WLabel>OWNER role · owner address</WLabel>
          <input value={owner} onChange={(e) => setOwner(e.target.value)} style={{ ...wInput, fontFamily: "var(--font-mono)", fontSize: 13 }} />
          <div style={{ marginTop: "var(--space-20)" }}>
            <WLabel>OPERATOR role · additional addresses</WLabel>
            {operators.map((op, i) => (
              <input key={i} value={op} onChange={(e) => setOperators((a) => a.map((x, j) => j === i ? e.target.value : x))}
                placeholder="0x… operator address" style={{ ...wInput, fontFamily: "var(--font-mono)", fontSize: 13, marginBottom: "var(--space-8)" }} />
            ))}
            <button type="button" className="btn btn--secondary btn--sm" onClick={() => setOperators((a) => [...a, ""])}><Icon name="plus" size={12} stroke={1.8} /> Add operator address</button>
          </div>
          <div style={{ marginTop: "var(--space-20)" }}>
            <WLabel>LIQUIDATOR role · DDF contract addresses</WLabel>
            {ddfContracts.map((c, i) => (
              <input key={i} value={c} onChange={(e) => setDdf((a) => a.map((x, j) => j === i ? e.target.value : x))}
                placeholder="0x… DDF contract" style={{ ...wInput, fontFamily: "var(--font-mono)", fontSize: 13, marginBottom: "var(--space-8)" }} />
            ))}
            <button type="button" className="btn btn--secondary btn--sm" onClick={() => setDdf((a) => [...a, ""])}><Icon name="plus" size={12} stroke={1.8} /> Add DDF contract</button>
          </div>
        </WizCard>
      )}

      {/* Step 4 — Collateral */}
      {step === 4 && (
        <WizCard title="Whitelist collateral" lede="Add collateral tokens and configure risk parameters (informed by the risk module).">
          {collateral.map((c, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: "var(--space-16)", padding: "var(--space-16) 0", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
              <div><WLabel>Token</WLabel><WSelect value={c.token} onChange={(v) => setCollateral((a) => a.map((x, j) => j === i ? { ...x, token: v } : x))} options={O.collateralTokens} /></div>
              <div><WLabel>Haircut (%)</WLabel><input value={c.haircut} onChange={(e) => setCollateral((a) => a.map((x, j) => j === i ? { ...x, haircut: e.target.value } : x))} style={wInput} /></div>
              <div><WLabel>Liq. threshold (%)</WLabel><input value={c.liq} onChange={(e) => setCollateral((a) => a.map((x, j) => j === i ? { ...x, liq: e.target.value } : x))} style={wInput} /></div>
              <div><WLabel>Min HF</WLabel><input value={c.minHF} onChange={(e) => setCollateral((a) => a.map((x, j) => j === i ? { ...x, minHF: e.target.value } : x))} style={wInput} /></div>
            </div>
          ))}
          <button type="button" className="btn btn--secondary btn--sm" style={{ marginTop: "var(--space-12)" }} onClick={() => setCollateral((a) => [...a, { token: "OUSG", haircut: "20", liq: "150", minHF: "1.1" }])}><Icon name="plus" size={12} stroke={1.8} /> Add token</button>
        </WizCard>
      )}

      {/* Step 5 — Settlement */}
      {step === 5 && (
        <WizCard title="Settlement tokens" lede="Add stablecoin settlement tokens. Use the denomination filter to narrow available options.">
          {settlement.map((s, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "var(--space-16)", padding: "var(--space-16) 0", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
              <div><WLabel>Denomination</WLabel><WSelect value={s.denom} onChange={(v) => setSettlement((a) => a.map((x, j) => j === i ? { ...x, denom: v, token: O.settlement[v][0] } : x))} options={Object.keys(O.settlement)} /></div>
              <div><WLabel>Stablecoin</WLabel><WSelect value={s.token} onChange={(v) => setSettlement((a) => a.map((x, j) => j === i ? { ...x, token: v } : x))} options={O.settlement[s.denom]} /></div>
              <div><WLabel>Base interest rate (%)</WLabel><input value={s.rate} onChange={(e) => setSettlement((a) => a.map((x, j) => j === i ? { ...x, rate: e.target.value } : x))} style={wInput} /></div>
            </div>
          ))}
          <button type="button" className="btn btn--secondary btn--sm" style={{ marginTop: "var(--space-12)" }} onClick={() => setSettlement((a) => [...a, { denom: "USD", token: "USDT", rate: "6.0" }])}><Icon name="plus" size={12} stroke={1.8} /> Add token</button>
        </WizCard>
      )}

      {/* Step 6 — Review */}
      {step === 6 && (
        <WizCard title="Review configuration" lede="Review all settings before executing the setup sequence.">
          <ReviewRow label="Facility name" value={name} />
          <ReviewRow label="Modules" value={`${mods.risk} · ${mods.auction} · ${mods.fee} · ${mods.compliance}`} />
          <ReviewRow label="Identity registry" value={reg.label} />
          <ReviewRow label="Required claim topics" value={O.claimTopics.join(", ")} />
          <ReviewRow label="Facility ONCHAINID" value="Auto-generated at deploy" />
          <ReviewRow label="Owner" value={<span style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{owner.slice(0, 10)}…{owner.slice(-4)}</span>} />
          <ReviewRow label="Collateral" value={collateral.map((c) => `${c.token} (haircut ${c.haircut}%)`).join(", ")} />
          <ReviewRow label="Settlement" value={settlement.map((s) => `${s.token} @ ${s.rate}%`).join(", ")} />
          <div style={{ marginTop: "var(--space-16)", padding: "var(--space-12) var(--space-16)", background: "var(--gold-10)", borderRadius: "var(--radius-md)", font: '400 13px/20px "Inter", sans-serif', color: "var(--gold-80)" }}>
            <strong style={{ fontWeight: 600 }}>Setup sequence required.</strong> Clicking Deploy initiates a multi-step transaction sequence to fully provision the facility. Keep your wallet connected.
          </div>
        </WizCard>
      )}

      {/* Footer */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "var(--space-8)" }}>
        <button type="button" className="btn btn--text" onClick={onCancel}><Icon name="cross" size={14} stroke={1.6} /> Cancel</button>
        <div style={{ display: "flex", gap: "var(--space-8)" }}>
          {step > 0 && <button type="button" className="btn btn--secondary" onClick={() => setStep((s) => s - 1)}>Back</button>}
          {!last && <button type="button" className="btn btn--primary" disabled={!canNext} style={{ opacity: canNext ? 1 : 0.5 }} onClick={() => canNext && setStep((s) => s + 1)}>Next <Icon name="arrow" size={13} stroke={1.6} /></button>}
          {last && <button type="button" className="btn btn--primary" onClick={() => { setSeq(0); setDeploying(true); }}><Icon name="deploy" size={14} stroke={1.7} /> Deploy facility</button>}
        </div>
      </div>
    </div>
  );
};

window.DeployFacilityWizard = DeployFacilityWizard;
