/* ============================================================
   ChadCoin — wallet connect + swap + burn + confirm + success
   ============================================================ */

/* ─── Helpers Solana / Jupiter ──────────────────────────── */
async function helius(method, params) {
  const r = await fetch(HELIUS_RPC, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ jsonrpc:"2.0", id:1, method, params })
  });
  const d = await r.json();
  if (d.error) throw new Error(d.error.message);
  return d.result;
}

async function fetchSolBalance(addr) {
  const r = await helius("getBalance", [addr, { commitment:"confirmed" }]);
  return r.value / 1e9;
}

async function fetchChdBalance(addr) {
  const r = await helius("getTokenAccountsByOwner", [
    addr, { mint: CHD_MINT }, { encoding:"jsonParsed", commitment:"confirmed" }
  ]);
  if (!r.value?.length) return 0;
  return r.value[0].account.data.parsed.info.tokenAmount.uiAmount ?? 0;
}

async function fetchTbtcBalance(addr) {
  const r = await helius("getTokenAccountsByOwner", [
    addr, { mint: TBTC_MINT }, { encoding:"jsonParsed", commitment:"confirmed" }
  ]);
  if (!r.value?.length) return 0;
  return r.value[0].account.data.parsed.info.tokenAmount.uiAmount ?? 0;
}

async function jupiterQuote(solAmount) {
  const lamports = Math.round(solAmount * 1e9);
  const url = `https://api.jup.ag/swap/v1/quote?inputMint=${SOL_MINT}&outputMint=${CHD_MINT}&amount=${lamports}&slippageBps=${SLIPPAGE_BPS}`;
  const r = await fetch(url);
  if (!r.ok) throw new Error("Jupiter indisponible");
  const d = await r.json();
  if (!d.outAmount) throw new Error("Aucune route trouvée — liquidité insuffisante pour ce montant");
  return d;
}

async function jupiterSwap(quote, userPublicKey, signTransaction) {
  const r = await fetch("https://api.jup.ag/swap/v1/swap", {
    method: "POST",
    headers: { "Content-Type":"application/json" },
    body: JSON.stringify({
      quoteResponse: quote,
      userPublicKey,
      dynamicComputeUnitLimit: true,
      prioritizationFeeLamports: "auto"
    })
  });
  if (!r.ok) throw new Error("Erreur lors de la construction du swap");
  const { swapTransaction } = await r.json();
  const bytes = Uint8Array.from(atob(swapTransaction), c => c.charCodeAt(0));
  const tx = solanaWeb3.VersionedTransaction.deserialize(bytes);
  const signed = await signTransaction(tx);
  const conn = new solanaWeb3.Connection(HELIUS_RPC, "confirmed");
  const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight:false, maxRetries:3 });
  const latest = await conn.getLatestBlockhash();
  await conn.confirmTransaction({ signature:sig, ...latest }, "confirmed");
  return sig;
}

/* ─── ATA + burn CHD → tBTC ─────────────────────────────── */
function findATA(ownerStr, mintStr) {
  const [ata] = solanaWeb3.PublicKey.findProgramAddressSync(
    [
      new solanaWeb3.PublicKey(ownerStr).toBytes(),
      new solanaWeb3.PublicKey(TOKEN_PROGRAM_ID).toBytes(),
      new solanaWeb3.PublicKey(mintStr).toBytes(),
    ],
    new solanaWeb3.PublicKey(ASSOC_TOKEN_PROGRAM_ID)
  );
  return ata;
}

function u64LE(n) {
  const buf = new Uint8Array(8);
  let v = BigInt(Math.round(n));
  for (let i = 0; i < 8; i++) { buf[i] = Number(v & 0xFFn); v >>= 8n; }
  return buf;
}

async function burnChd(chdAmount, userPublicKey, signTransaction) {
  const conn        = new solanaWeb3.Connection(HELIUS_RPC, "confirmed");
  const userPK      = new solanaWeb3.PublicKey(userPublicKey);
  const userTbtcAta = findATA(userPublicKey, TBTC_MINT);
  const userChdAta  = findATA(userPublicKey, CHD_MINT);

  const BURN_DISC = new Uint8Array([216, 117, 35, 35, 239, 192, 140, 79]);
  const data = new Uint8Array([...BURN_DISC, ...u64LE(chdAmount)]);

  // Créer l'ATA tBTC si absente (instruction idempotente)
  const createAtaIx = new solanaWeb3.TransactionInstruction({
    programId: new solanaWeb3.PublicKey(ASSOC_TOKEN_PROGRAM_ID),
    keys: [
      { pubkey: userPK,                                      isSigner:true,  isWritable:true  },
      { pubkey: userTbtcAta,                                 isSigner:false, isWritable:true  },
      { pubkey: userPK,                                      isSigner:false, isWritable:false },
      { pubkey: new solanaWeb3.PublicKey(TBTC_MINT),         isSigner:false, isWritable:false },
      { pubkey: new solanaWeb3.PublicKey(SYSTEM_PROGRAM_ID), isSigner:false, isWritable:false },
      { pubkey: new solanaWeb3.PublicKey(TOKEN_PROGRAM_ID),  isSigner:false, isWritable:false },
    ],
    data: new Uint8Array([1]),
  });

  const burnIx = new solanaWeb3.TransactionInstruction({
    programId: new solanaWeb3.PublicKey(PROGRAM_ID),
    keys: [
      { pubkey: new solanaWeb3.PublicKey(STATE_PDA),  isSigner:false, isWritable:true  },
      { pubkey: new solanaWeb3.PublicKey(CHD_MINT),   isSigner:false, isWritable:true  },
      { pubkey: new solanaWeb3.PublicKey(VAULT_TBTC), isSigner:false, isWritable:true  },
      { pubkey: userTbtcAta,                          isSigner:false, isWritable:true  },
      { pubkey: userChdAta,                           isSigner:false, isWritable:true  },
      { pubkey: userPK,                               isSigner:true,  isWritable:true  },
      { pubkey: new solanaWeb3.PublicKey(TOKEN_PROGRAM_ID), isSigner:false, isWritable:false },
    ],
    data,
  });

  const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash();
  const tx = new solanaWeb3.Transaction({ recentBlockhash:blockhash, feePayer:userPK });
  tx.add(createAtaIx, burnIx);

  const signed = await signTransaction(tx);
  const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight:false, maxRetries:3 });
  await conn.confirmTransaction({ signature:sig, blockhash, lastValidBlockHeight }, "confirmed");
  return sig;
}

/* ─── Détection et connexion des wallets ────────────────── */
function detectWallets() {
  return {
    phantom:  !!(window.phantom?.solana?.isPhantom || window.solana?.isPhantom),
    solflare: !!(window.solflare?.isSolflare),
    backpack: !!(window.backpack?.isBackpack),
    coinbase: !!(window.coinbaseSolana),
    magiceden:!!(window.magicEden?.solana),
  };
}

const WALLET_INSTALL = {
  phantom:      "https://phantom.app",
  solflare:     "https://solflare.com",
  backpack:     "https://backpack.app",
  coinbase:     "https://www.coinbase.com/wallet",
  magiceden:    "https://wallet.magiceden.io",
  trust:        "https://trustwallet.com",
  ledger:       "https://www.ledger.com/ledger-live",
  coin98:       "https://coin98.com/wallet",
  bitget:       "https://web3.bitget.com/wallet",
  walletconnect:"https://walletconnect.com",
};

async function walletConnect(id) {
  switch(id) {
    case "phantom": {
      const p = window.phantom?.solana || (window.solana?.isPhantom ? window.solana : null);
      if (!p) throw new Error("not_installed");
      const r = await p.connect();
      return { publicKey: r.publicKey.toString(), signTransaction: tx => p.signTransaction(tx) };
    }
    case "solflare": {
      const p = window.solflare;
      if (!p?.isSolflare) throw new Error("not_installed");
      await p.connect();
      return { publicKey: p.publicKey.toString(), signTransaction: tx => p.signTransaction(tx) };
    }
    case "backpack": {
      const p = window.backpack;
      if (!p) throw new Error("not_installed");
      const r = await p.connect();
      return { publicKey: r.publicKey.toString(), signTransaction: tx => p.signTransaction(tx) };
    }
    case "coinbase": {
      const p = window.coinbaseSolana;
      if (!p) throw new Error("not_installed");
      const r = await p.connect();
      return { publicKey: r.publicKey.toString(), signTransaction: tx => p.signTransaction(tx) };
    }
    case "magiceden": {
      const p = window.magicEden?.solana;
      if (!p) throw new Error("not_installed");
      const r = await p.connect();
      return { publicKey: r.publicKey.toString(), signTransaction: tx => p.signTransaction(tx) };
    }
    default:
      throw new Error("not_installed");
  }
}

/* ─── SWAP CARD (onglets Acheter / Brûler) ───────────────── */
function SwapCard({ connected, solBalance, chdBalance, solPrice, btcPrice,
                    onConnect, onSwap, onBurn, swapLoading, compact }) {
  const [mode, setMode]     = useState("buy");
  const [sol, setSol]       = useState("");
  const [chd, setChd]       = useState("");
  const [showSet, setShowSet] = useState(false);
  const [slip, setSlip]       = useState("0.5");

  const chdPerSol = (btcPrice > 0 && solPrice > 0) ? (solPrice / btcPrice) * 1e8 : CHD_PER_SOL;
  const chdUsd    = btcPrice > 0 ? btcPrice / 1e8 : CHD_USD;

  const estChd    = sol && !isNaN(sol) ? parseFloat(sol) * chdPerSol : 0;
  const solFiat   = sol && !isNaN(sol) ? parseFloat(sol) * solPrice : 0;
  const chdAmt    = chd && !isNaN(chd) ? parseFloat(chd) : 0;
  const tbtcOut   = chdAmt / 1e8;
  const burnFiat  = chdAmt * chdUsd;

  const onMaxSol  = () => connected && setSol(String(Math.max(0, solBalance - 0.01).toFixed(4)));
  const onMaxChd  = () => connected && setChd(String(Math.floor(chdBalance)));

  const buyValid   = sol && parseFloat(sol) > 0 && (!connected || parseFloat(sol) <= solBalance);
  const burnValid  = chd && chdAmt > 0 && (!connected || chdAmt <= chdBalance);
  const solTooMuch = connected && sol && parseFloat(sol) > solBalance;
  const chdTooMuch = connected && chd && chdAmt > chdBalance;

  const TAB_STYLE = (active) => ({
    flex:1, padding:"9px 0", borderRadius:9, border:"none", fontWeight:600,
    fontSize:14, cursor:"pointer",
    background: active ? "var(--bg)" : "transparent",
    color: active ? "var(--btc)" : "var(--muted)",
    boxShadow: active ? "0 1px 4px rgba(0,0,0,0.18)" : "none",
    transition:"all .15s",
  });

  return (
    <div className="swap" style={compact ? { boxShadow:"none", border:"none", padding:0, background:"none" } : {}}>

      {/* Onglets */}
      <div style={{ display:"flex", gap:0, marginBottom:18, background:"var(--bg-2)",
                    borderRadius:12, padding:4, border:"1px solid var(--line)" }}>
        <button style={TAB_STYLE(mode==="buy")} onClick={() => setMode("buy")}>
          <Ic.bolt style={{width:14,height:14,verticalAlign:"middle",marginRight:5}}/>
          Acheter CHD
        </button>
        <button style={TAB_STYLE(mode==="burn")} onClick={() => setMode("burn")}>
          <Ic.fire style={{width:14,height:14,verticalAlign:"middle",marginRight:5}}/>
          Brûler CHD
        </button>
      </div>

      {mode === "buy" ? (
        /* ───── MODE ACHAT ───── */
        <>
          <div className="swap-head">
            <div className="swap-title"><Ic.swap style={{color:"var(--btc)"}}/> Échanger</div>
            <div style={{ position:"relative" }}>
              <button className="swap-gear" onClick={() => setShowSet(s => !s)} aria-label="Réglages"><Ic.gear/></button>
              {showSet && (
                <div className="settings-pop" onMouseLeave={() => setShowSet(false)}>
                  <div style={{ fontSize:13, fontWeight:600 }}>Tolérance de slippage</div>
                  <div className="slip-opts">
                    {["0.1","0.5","1.0"].map(s => (
                      <button key={s} className={"slip-opt"+(slip===s?" active":"")} onClick={() => setSlip(s)}>{s}%</button>
                    ))}
                  </div>
                  <div style={{ fontSize:12, color:"var(--faint)", marginTop:12, lineHeight:1.5 }}>
                    Routé via Jupiter pour le meilleur prix.
                  </div>
                </div>
              )}
            </div>
          </div>

          <div className="swap-field">
            <div className="swap-field-top">
              <span>Tu paies</span>
              <span style={{ display:"flex", gap:8, alignItems:"center" }}>
                {connected
                  ? <>Solde {fmt(solBalance,3)} SOL <button className="maxbtn" onClick={onMaxSol}>MAX</button></>
                  : "Wallet non connecté"}
              </span>
            </div>
            <div className="swap-field-row">
              <input className="swap-amount" inputMode="decimal" placeholder="0.0" value={sol}
                onChange={e => { const v = e.target.value.replace(",","."); if(/^\d*\.?\d*$/.test(v)) setSol(v); }}/>
              <div className="token-pill"><SolMark size={24}/> SOL</div>
            </div>
            <div className="swap-fiat">≈ {fmt(solFiat)} $</div>
          </div>

          <div className="swap-mid"><div className="swap-switch"><Ic.arrowDown/></div></div>

          <div className="swap-field">
            <div className="swap-field-top"><span>Tu reçois (estimé)</span><span>1 CHD = 1 satoshi</span></div>
            <div className="swap-field-row">
              <input className="swap-amount" readOnly placeholder="0.0" value={estChd ? fmt(estChd,0) : ""}/>
              <div className="token-pill"><ChdCoin size={24}/> CHD</div>
            </div>
            <div className="swap-fiat">≈ {fmt(estChd*chdUsd)} $ · {fmt(estChd,0)} sats</div>
          </div>

          <div className="swap-meta">
            <div className="swap-meta-row"><span>Taux</span><b className="swap-rate">1 SOL ≈ {fmt(chdPerSol,0)} CHD</b></div>
            <div className="swap-meta-row"><span>Slippage max.</span><b>{slip}%</b></div>
            <div className="swap-meta-row"><span>Frais réseau</span><b>~ 0,0007 $</b></div>
            <div className="swap-meta-row"><span>Route</span><b style={{display:"flex",alignItems:"center",gap:6}}>Jupiter <Ic.bolt style={{width:13,height:13,color:"var(--btc)"}}/></b></div>
          </div>

          {!connected ? (
            <button className="btn btn-primary btn-lg btn-block" onClick={onConnect}>
              <Ic.wallet/> Connecter le wallet
            </button>
          ) : (
            <button className="btn btn-primary btn-lg btn-block"
              disabled={!buyValid || swapLoading}
              onClick={() => onSwap({ sol:parseFloat(sol), estChd })}>
              {swapLoading ? "Récupération du devis…"
                : solTooMuch ? "Solde SOL insuffisant"
                : buyValid ? <>Échanger maintenant <Ic.arrow/></>
                : "Saisis un montant"}
            </button>
          )}
        </>
      ) : (
        /* ───── MODE BURN ───── */
        <>
          <div className="swap-head">
            <div className="swap-title"><Ic.fire style={{color:"var(--btc)"}}/> Récupérer du tBTC</div>
          </div>

          <div className="swap-field">
            <div className="swap-field-top">
              <span>Tu brûles</span>
              <span style={{ display:"flex", gap:8, alignItems:"center" }}>
                {connected
                  ? <>Solde {fmt(chdBalance,0)} CHD <button className="maxbtn" onClick={onMaxChd}>MAX</button></>
                  : "Wallet non connecté"}
              </span>
            </div>
            <div className="swap-field-row">
              <input className="swap-amount" inputMode="decimal" placeholder="0" value={chd}
                onChange={e => { const v = e.target.value.replace(",","."); if(/^\d*\.?\d*$/.test(v)) setChd(v); }}/>
              <div className="token-pill"><ChdCoin size={24}/> CHD</div>
            </div>
            <div className="swap-fiat">≈ {fmt(burnFiat)} $</div>
          </div>

          <div className="swap-mid"><div className="swap-switch"><Ic.arrowDown/></div></div>

          <div className="swap-field">
            <div className="swap-field-top"><span>Tu reçois (garanti)</span><span>1:1 par le contrat</span></div>
            <div className="swap-field-row">
              <input className="swap-amount" readOnly placeholder="0.00000000"
                value={tbtcOut ? tbtcOut.toFixed(8) : ""}/>
              <div className="token-pill"><BtcCoin size={24}/> tBTC</div>
            </div>
            <div className="swap-fiat">{fmt(chdAmt,0)} satoshis · ≈ {fmt(burnFiat)} $</div>
          </div>

          <div className="swap-meta">
            <div className="swap-meta-row"><span>Taux</span><b>1 CHD = 1 satoshi tBTC</b></div>
            <div className="swap-meta-row"><span>Garantie</span><b style={{color:"var(--success)"}}>Protocole 1:1</b></div>
            <div className="swap-meta-row"><span>Frais réseau</span><b>~ 0,0007 $</b></div>
            <div className="swap-meta-row"><span>Contrat</span><b style={{display:"flex",alignItems:"center",gap:5}}><Ic.shield style={{width:12,height:12}}/> On-chain</b></div>
          </div>

          {!connected ? (
            <button className="btn btn-primary btn-lg btn-block" onClick={onConnect}>
              <Ic.wallet/> Connecter le wallet
            </button>
          ) : (
            <button className="btn btn-lg btn-block"
              disabled={!burnValid || swapLoading}
              style={ burnValid && !swapLoading
                ? { background:"linear-gradient(135deg,#F7931A,#E8820C)", color:"#fff", border:"none", borderRadius:14, fontWeight:700, cursor:"pointer" }
                : { background:"var(--bg-2)", color:"var(--muted)", border:"1px solid var(--line)", borderRadius:14, fontWeight:700, cursor:"not-allowed" }}
              onClick={() => onBurn({ chd: chdAmt })}>
              {swapLoading ? "Transaction en cours…"
                : chdTooMuch ? "Solde CHD insuffisant"
                : burnValid ? <><Ic.fire style={{width:16,height:16}}/> Brûler les CHD</>
                : "Saisis un montant"}
            </button>
          )}
        </>
      )}
    </div>
  );
}

/* ─── CONNECT MODAL ──────────────────────────────────────── */
function ConnectModal({ onClose, onConnected }) {
  const [connecting, setConnecting] = useState(null);
  const [error, setError]           = useState(null);
  const detected = detectWallets();

  /* Détection mobile + contexte in-app */
  const isMobile   = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
  const inPhantom  = !!(window.phantom?.solana?.isPhantom || window.solana?.isPhantom);
  const inSolflare = !!(window.solflare?.isSolflare);
  const inApp      = inPhantom || inSolflare;
  const showMobileGuide = isMobile && !inApp;

  const siteUrl         = encodeURIComponent(window.location.href);
  const phantomDeepLink = `https://phantom.app/ul/browse/${siteUrl}?ref=${siteUrl}`;
  const solflareDeepLink= `https://solflare.com/ul/v1/browse/${siteUrl}?ref=${siteUrl}`;

  const enriched = WALLETS.map(w => ({
    ...w,
    isDetected: !!detected[w.id],
    installUrl: WALLET_INSTALL[w.id] || null
  }));

  const choose = async (w) => {
    if (w.id === "google") return;
    if (!w.isDetected) { if (w.installUrl) window.open(w.installUrl, "_blank"); return; }
    setConnecting(w.id);
    setError(null);
    try {
      const { publicKey, signTransaction } = await walletConnect(w.id);
      onConnected({ ...w, signTransaction }, publicKey);
    } catch(e) {
      if (e.message === "not_installed") {
        if (w.installUrl) window.open(w.installUrl, "_blank");
      } else if (e.code === 4001 || e.message?.toLowerCase().includes("rejected")) {
        setError("Connexion refusée dans le wallet.");
      } else {
        setError("Erreur : " + (e.message || "inconnue"));
      }
    } finally {
      setConnecting(null);
    }
  };

  const active = connecting ? enriched.find(w => w.id === connecting) : null;

  /* ── Vue mobile : guide pour ouvrir dans l'app ── */
  if (showMobileGuide) {
    return (
      <div className="overlay" onMouseDown={e => e.target === e.currentTarget && onClose()}>
        <div className="modal">
          <div className="modal-head">
            <div className="modal-title"><Ic.wallet style={{color:"var(--btc)"}}/> Connecter un wallet</div>
            <button className="modal-x" onClick={onClose}><Ic.x/></button>
          </div>
          <div className="modal-body">
            <div style={{ background:"rgba(247,147,26,0.08)", border:"1px solid rgba(247,147,26,0.25)",
                          borderRadius:12, padding:"12px 14px", marginBottom:18, fontSize:13.5, lineHeight:1.6,
                          color:"var(--muted)", display:"flex", gap:10, alignItems:"flex-start" }}>
              <Ic.info style={{width:16,height:16,flexShrink:0,marginTop:2,color:"var(--btc)"}}/>
              <span>Sur mobile, ouvre ce site <b style={{color:"var(--ink)"}}>depuis le navigateur intégré</b> de ton app wallet pour te connecter.</span>
            </div>

            <a href={phantomDeepLink} style={{ textDecoration:"none" }}>
              <div className="wallet-row" style={{cursor:"pointer"}}>
                <WalletLogo id="phantom" size={40}/>
                <span className="wallet-name">Ouvrir dans Phantom</span>
                <span className="wallet-tag">Recommandé</span>
              </div>
            </a>

            <a href={solflareDeepLink} style={{ textDecoration:"none" }}>
              <div className="wallet-row" style={{cursor:"pointer"}}>
                <WalletLogo id="solflare" size={40}/>
                <span className="wallet-name">Ouvrir dans Solflare</span>
                <span className="wallet-tag">Recommandé</span>
              </div>
            </a>

            <div className="modal-foot-note" style={{marginTop:16}}>
              <Ic.shield style={{width:15,height:15,flexShrink:0,marginTop:1,color:"var(--faint)"}}/>
              Le site s'ouvrira dans l'app. Tu pourras connecter ton wallet en un tap.
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="overlay" onMouseDown={e => e.target === e.currentTarget && !connecting && onClose()}>
      <div className="modal">
        <div className="modal-head">
          <div className="modal-title">
            <Ic.wallet style={{color:"var(--btc)"}}/>
            {connecting ? "Connexion…" : "Connecter un wallet"}
          </div>
          {!connecting && <button className="modal-x" onClick={onClose}><Ic.x/></button>}
        </div>
        <div className="modal-body">
          {connecting ? (
            <div className="connecting">
              <div style={{ position:"relative", width:54, margin:"0 auto 22px" }}>
                <div className="spinner"/>
                <div style={{ position:"absolute", inset:0, display:"grid", placeItems:"center" }}>
                  <WalletTile w={active} size={28}/>
                </div>
              </div>
              <div style={{ fontWeight:600, fontSize:16 }}>Ouverture de {active.name}…</div>
              <div style={{ color:"var(--muted)", fontSize:13.5, marginTop:8, lineHeight:1.5 }}>
                Approuve la connexion dans {active.name}. ChadCoin ne pourra jamais déplacer tes fonds sans ta signature.
              </div>
            </div>
          ) : (
            <>
              {error && (
                <div style={{ background:"rgba(229,72,77,0.1)", border:"1px solid rgba(229,72,77,0.3)",
                              borderRadius:10, padding:"10px 14px", marginBottom:12, fontSize:13.5, color:"#E5484D" }}>
                  {error}
                </div>
              )}
              {enriched.map(w => (
                <button key={w.id} className="wallet-row" onClick={() => choose(w)}>
                  <WalletTile w={w}/>
                  <span className="wallet-name">{w.name}</span>
                  {w.type === "social"
                    ? <span className="wallet-tag">Bientôt</span>
                    : w.isDetected
                      ? <span className="wallet-tag">Détecté</span>
                      : <span className="wallet-tag muted">Installer</span>}
                </button>
              ))}
              <div className="modal-foot-note">
                <Ic.shield style={{ width:15, height:15, flexShrink:0, marginTop:1, color:"var(--faint)" }}/>
                En connectant ton wallet, tu acceptes les conditions. ChadCoin est non-custodial : tes clés et tes fonds restent toujours sous ton contrôle.
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

/* ─── CONFIRM MODAL ──────────────────────────────────────── */
function ConfirmModal({ tx, wallet, loading, onClose, onConfirm }) {
  const isBurn = tx.type === "burn";
  return (
    <div className="overlay" onMouseDown={e => e.target === e.currentTarget && !loading && onClose()}>
      <div className="modal">
        <div className="modal-head">
          <div className="modal-title">
            {loading ? "Transaction en cours…" : isBurn ? "Confirmer le burn" : "Vérifier l'échange"}
          </div>
          {!loading && <button className="modal-x" onClick={onClose}><Ic.x/></button>}
        </div>
        <div className="modal-body">
          {loading ? (
            <div className="connecting">
              <div className="spinner"/>
              <div style={{ fontWeight:600, fontSize:16 }}>En attente de ta signature</div>
              <div style={{ color:"var(--muted)", fontSize:13.5, marginTop:8, lineHeight:1.5 }}>
                Confirme dans {wallet?.name || "ton wallet"}. La transaction est ensuite envoyée sur Solana.
              </div>
            </div>
          ) : isBurn ? (
            <>
              <div className="review-big">
                <div style={{ display:"flex", alignItems:"center", justifyContent:"center", gap:12, marginBottom:10 }}>
                  <span style={{ display:"flex", alignItems:"center", gap:8 }}><ChdCoin size={26}/> <b className="mono" style={{fontSize:18}}>{fmt(tx.chd,0)}</b></span>
                  <Ic.arrow style={{ color:"var(--faint)" }}/>
                  <span style={{ display:"flex", alignItems:"center", gap:8 }}><BtcCoin size={26}/> <b className="mono" style={{fontSize:18}}>{(tx.chd/1e8).toFixed(8)}</b></span>
                </div>
                <div className="rb-amt text-btc">{fmt(tx.chd,0)} satoshis récupérés</div>
                <div className="rb-sub">≈ {fmt(tx.chd*(tx.btcPrice/1e8))} $ · tBTC garanti par le protocole</div>
              </div>
              <div style={{ background:"var(--bg-2)", border:"1px solid var(--line)", borderRadius:14, padding:"4px 16px", margin:"4px 0 18px" }}>
                <div className="review-line"><span className="rl-label">Tu brûles</span><span className="rl-val mono">{fmt(tx.chd,0)} CHD</span></div>
                <div className="review-line"><span className="rl-label">Tu reçois</span><span className="rl-val mono">{(tx.chd/1e8).toFixed(8)} tBTC</span></div>
                <div className="review-line"><span className="rl-label">Garantie</span><span className="rl-val" style={{color:"var(--success)"}}>Protocole 1:1</span></div>
                <div className="review-line"><span className="rl-label">Frais réseau</span><span className="rl-val">~ 0,0007 $</span></div>
              </div>
              <button className="btn btn-lg btn-block" onClick={onConfirm}
                style={{ background:"linear-gradient(135deg,#F7931A,#E8820C)", color:"#fff", border:"none", borderRadius:14, fontWeight:700, cursor:"pointer" }}>
                <Ic.fire/> Confirmer le burn dans {wallet?.name || "le wallet"}
              </button>
            </>
          ) : (
            <>
              <div className="review-big">
                <div style={{ display:"flex", alignItems:"center", justifyContent:"center", gap:12, marginBottom:10 }}>
                  <span style={{ display:"flex", alignItems:"center", gap:8 }}><SolMark size={26}/> <b className="mono" style={{fontSize:18}}>{fmt(tx.sol,3)}</b></span>
                  <Ic.arrow style={{ color:"var(--faint)" }}/>
                  <span style={{ display:"flex", alignItems:"center", gap:8 }}><ChdCoin size={26}/> <b className="mono" style={{fontSize:18}}>{fmt(tx.chd,0)}</b></span>
                </div>
                <div className="rb-amt text-btc">{fmt(tx.chd,0)} CHD</div>
                <div className="rb-sub">≈ {fmt(tx.chd*(tx.btcPrice/1e8))} $ · tu accumules {fmt(tx.chd,0)} satoshis</div>
              </div>
              <div style={{ background:"var(--bg-2)", border:"1px solid var(--line)", borderRadius:14, padding:"4px 16px", margin:"4px 0 18px" }}>
                <div className="review-line"><span className="rl-label">Tu paies</span><span className="rl-val mono">{fmt(tx.sol,3)} SOL</span></div>
                <div className="review-line"><span className="rl-label">Taux Jupiter</span><span className="rl-val">1 SOL ≈ {fmt(tx.chd/tx.sol,0)} CHD</span></div>
                <div className="review-line"><span className="rl-label">Slippage max.</span><span className="rl-val">{SLIPPAGE_BPS/100}%</span></div>
                <div className="review-line"><span className="rl-label">Frais réseau</span><span className="rl-val">~ 0,0007 $</span></div>
                <div className="review-line"><span className="rl-label">Route</span><span className="rl-val">Jupiter (meilleur prix)</span></div>
              </div>
              <button className="btn btn-primary btn-lg btn-block" onClick={onConfirm}>
                <Ic.lock/> Confirmer dans {wallet?.name || "le wallet"}
              </button>
              <div className="modal-foot-note" style={{ justifyContent:"center", marginTop:14 }}>
                <Ic.info style={{ width:14, height:14, color:"var(--faint)" }}/> Montant garanti par Jupiter (±{SLIPPAGE_BPS/100}% slippage).
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

/* ─── SUCCESS MODAL ──────────────────────────────────────── */
function SuccessModal({ tx, onClose }) {
  const isBurn     = tx.type === "burn";
  const shortSig   = tx.sig ? tx.sig.slice(0,8)+"…"+tx.sig.slice(-4) : "—";
  const solscanUrl = tx.sig ? `https://solscan.io/tx/${tx.sig}` : "https://solscan.io";
  return (
    <div className="overlay" onMouseDown={e => e.target === e.currentTarget && onClose()}>
      <div className="modal">
        <div className="modal-head">
          <div className="modal-title">Transaction confirmée</div>
          <button className="modal-x" onClick={onClose}><Ic.x/></button>
        </div>
        <div className="modal-body">
          <div className="success-wrap">
            <div className="success-ring"><Ic.checkBig/></div>
            {isBurn ? (
              <>
                <div style={{ color:"var(--muted)", fontSize:14 }}>Tu as récupéré</div>
                <div className="success-amt text-btc">+{(tx.chd/1e8).toFixed(8)} tBTC</div>
                <div style={{ color:"var(--muted)", fontSize:14 }}>≈ {fmt(tx.chd*(tx.btcPrice/1e8))} $</div>
                <div className="sats-badge"><BtcCoin size={18}/> {fmt(tx.chd,0)} satoshis du vault</div>
              </>
            ) : (
              <>
                <div style={{ color:"var(--muted)", fontSize:14 }}>Tu as reçu</div>
                <div className="success-amt text-btc">+{fmt(tx.chd,0)} CHD</div>
                <div style={{ color:"var(--muted)", fontSize:14 }}>≈ {fmt(tx.chd*(tx.btcPrice/1e8))} $</div>
                <div className="sats-badge"><BtcCoin size={18}/> +{fmt(tx.chd,0)} satoshis de Bitcoin accumulés</div>
              </>
            )}
          </div>
          <div style={{ background:"var(--bg-2)", border:"1px solid var(--line)", borderRadius:14, padding:"4px 16px", margin:"22px 0 18px" }}>
            <div className="review-line">
              <span className="rl-label">{isBurn ? "Brûlé" : "Payé"}</span>
              <span className="rl-val mono">{isBurn ? fmt(tx.chd,0)+" CHD" : fmt(tx.sol,3)+" SOL"}</span>
            </div>
            <div className="review-line">
              <span className="rl-label">Statut</span>
              <span className="rl-val" style={{ color:"var(--success)", display:"flex", alignItems:"center", gap:6 }}>
                <Ic.check/> Finalisé
              </span>
            </div>
            <div className="review-line">
              <span className="rl-label">Signature</span>
              <span className="rl-val mono" style={{ fontSize:13 }}>{shortSig}</span>
            </div>
          </div>
          <a className="btn btn-ghost btn-block" href={solscanUrl} target="_blank" rel="noopener" style={{ marginBottom:9 }}>
            Voir sur Solscan <Ic.ext/>
          </a>
          <button className="btn btn-primary btn-block" onClick={onClose}>Terminé</button>
        </div>
      </div>
    </div>
  );
}

/* ─── Stats on-chain live ────────────────────────────────── */
async function fetchChainStats() {
  const [supplyR, vaultR] = await Promise.all([
    helius("getTokenSupply",         [CHD_MINT]),
    helius("getTokenAccountBalance", [VAULT_TBTC])
  ]);
  return {
    supply:    supplyR.value.uiAmount  || 0,   // CHD en circulation
    vault:     vaultR.value.uiAmount   || 0,   // tBTC dans le vault (en BTC)
    vaultSats: parseInt(vaultR.value.amount) || 0, // satoshis bruts
  };
}

Object.assign(window, {
  SwapCard, ConnectModal, ConfirmModal, SuccessModal,
  jupiterQuote, jupiterSwap, burnChd,
  fetchSolBalance, fetchChdBalance, fetchTbtcBalance, fetchChainStats,
});
