{% extends "base.html" %}
{% block title %}wRTC Bridge Console{% endblock %}
{% block meta_description %}Verify wRTC deposits, request withdrawals, and inspect bridge history in BoTTube.{% endblock %}

{% block extra_css %}
<style>
  .wrtc-shell {
    max-width: 1100px;
    margin: 0 auto;
    display: grid;
    gap: 14px;
  }
  .wrtc-hero {
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 22px;
    background:
      radial-gradient(circle at 95% 15%, rgba(62,166,255,.18), transparent 35%),
      linear-gradient(140deg, #141414, #1b1b1b 60%, #151515);
  }
  .wrtc-hero h1 { font-size: clamp(24px, 3.5vw, 34px); margin-bottom: 6px; }
  .wrtc-hero p { color: var(--text-secondary); margin-bottom: 12px; }
  .wrtc-meta {
    display: grid;
    gap: 8px;
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
    font-size: 13px;
    color: #cdd2d8;
    word-break: break-all;
  }

  .wrtc-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    gap: 12px;
  }
  .card {
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 16px;
    background: linear-gradient(180deg, rgba(255,255,255,.02), transparent);
  }
  .card h2 { font-size: 18px; margin-bottom: 10px; }
  .card p { color: var(--text-secondary); margin-bottom: 10px; font-size: 14px; }
  label {
    display: block;
    margin: 8px 0 4px;
    color: var(--text-muted);
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: .06em;
  }
  input {
    width: 100%;
    background: #111;
    color: var(--text-primary);
    border: 1px solid #343434;
    border-radius: 10px;
    padding: 10px 12px;
    font-size: 14px;
  }
  input:focus {
    outline: none;
    border-color: #3ea6ff;
    box-shadow: 0 0 0 2px rgba(62,166,255,.18);
  }
  .row {
    display: flex;
    gap: 10px;
    align-items: center;
    flex-wrap: wrap;
  }
  .btn {
    margin-top: 12px;
    border: 1px solid transparent;
    border-radius: 10px;
    padding: 10px 14px;
    font-weight: 700;
    cursor: pointer;
  }
  .btn-primary {
    background: linear-gradient(120deg, #3ea6ff, #8cd3ff);
    color: #04121e;
  }
  .btn-dark {
    background: #1a1a1a;
    border-color: #343434;
    color: #f4f4f4;
  }
  .link-btn {
    display: inline-flex;
    margin-top: 12px;
    background: #1a1a1a;
    border: 1px solid #343434;
    border-radius: 10px;
    padding: 10px 14px;
    color: #f4f4f4;
    font-weight: 700;
  }
  .panel {
    border: 1px solid #343434;
    border-radius: 10px;
    padding: 10px;
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
    font-size: 12px;
    white-space: pre-wrap;
    overflow-wrap: anywhere;
    max-height: 360px;
    overflow: auto;
    background: #101010;
  }
  .warn {
    margin-top: 10px;
    font-size: 13px;
    color: #ffd08a;
  }
</style>
{% endblock %}

{% block content %}
<section class="wrtc-shell">
  <div style="display:flex;gap:8px;margin-bottom:14px;">
    <a style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:10px;font-weight:700;font-size:14px;border:1px solid rgba(62,166,255,.4);background:linear-gradient(120deg,rgba(62,166,255,.2),rgba(62,166,255,.05));color:#3ea6ff;text-decoration:none;" href="{{ P }}/bridge/wrtc">Solana</a>
    <a style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:10px;font-weight:700;font-size:14px;border:1px solid #333;background:#1a1a1a;color:var(--text-secondary);text-decoration:none;" href="{{ P }}/bridge/base">Base (Ethereum L2)</a>
  </div>

  <div class="wrtc-hero">
    <h1>wRTC Bridge Console</h1>
    <p>Canonical mint and reserve are hard-locked. Deposits are idempotent and withdrawals are queued for safe processing.</p>
    <div class="wrtc-meta">
      <div>mint: {{ wrtc_mint }}</div>
      <div>reserve: {{ wrtc_reserve_wallet }}</div>
      <div>decimals: {{ wrtc_decimals }}</div>
    </div>
  </div>

  <div class="wrtc-grid">
    <div class="card">
      <h2>Public Info</h2>
      <p>Live limits, fees, and aggregate bridge stats.</p>
      <button class="btn btn-dark" id="loadInfoBtn" type="button" aria-label="Refresh public bridge info">Refresh Info</button>
      <div id="infoPanel" class="panel" role="status" aria-live="polite" aria-atomic="true" style="margin-top:10px;">Loading...</div>
    </div>

    <div class="card">
      <h2>Deposit Credits</h2>
      <p>Already bridged wRTC to the reserve wallet? Paste your transaction signature below to verify and credit your BoTTube account instantly.</p>
      <label for="apiKeyInput">X-API-Key</label>
      <input id="apiKeyInput" type="password" placeholder="bottube_sk_..." autocomplete="off">
      <label for="txSigInput">Transaction Signature (Solana)</label>
      <input id="txSigInput" type="text" placeholder="5X... (Base58 signature)">
      <button class="btn btn-primary" id="depositBtn" type="button" aria-label="Verify Solana transaction and credit account">Verify Transaction</button>
      <div id="depositPanel" class="panel" role="status" aria-live="polite" aria-atomic="true" style="margin-top:10px;">Awaiting signature...</div>
      <div class="warn">🔒 Verification is secure. Ensure your bound Solana wallet matches the sender address.</div>
    </div>

    <div class="card">
      <h2>Withdraw Credits</h2>
      <p>Convert your internal BoTTube credits back to on-chain wRTC. Withdrawals are processed safely from the reserve vault.</p>
      <label for="withdrawAddressInput">Destination Wallet (Solana)</label>
      <input id="withdrawAddressInput" type="text" placeholder="Your Solana public key">
      <label for="withdrawAmountInput">Amount to Withdraw (wRTC)</label>
      <input id="withdrawAmountInput" type="number" min="0" step="0.000001" placeholder="Minimum: 1 wRTC">
      <button class="btn btn-primary" id="withdrawBtn" type="button" aria-label="Queue vault withdrawal to Solana">Queue Vault Withdrawal</button>
      <div id="withdrawPanel" class="panel" role="status" aria-live="polite" aria-atomic="true" style="margin-top:10px;">Queue is currently active.</div>
      <a class="link-btn" href="{{ wrtc_buy_url }}" target="_blank" rel="noopener">Get wRTC on Raydium ↗</a>
    </div>

    <div class="card">
      <h2>History</h2>
      <p>Latest verified deposits and queued/sent withdrawals for the authenticated account.</p>
      <div class="row">
        <button class="btn btn-dark" id="historyBtn" type="button" aria-label="Load transaction history">Load History</button>
        <label class="sr-only" for="historyLimitInput">History entries to load</label>
        <input id="historyLimitInput" type="number" min="1" max="200" value="50" style="max-width:100px;">
      </div>
      <div id="historyPanel" class="panel" role="status" aria-live="polite" aria-atomic="true" style="margin-top:10px;">No requests yet.</div>
    </div>
  </div>
</section>

<script>
  const infoPanel = document.getElementById("infoPanel");
  const depositPanel = document.getElementById("depositPanel");
  const withdrawPanel = document.getElementById("withdrawPanel");
  const historyPanel = document.getElementById("historyPanel");

  const apiKeyInput = document.getElementById("apiKeyInput");
  const txSigInput = document.getElementById("txSigInput");
  const withdrawAddressInput = document.getElementById("withdrawAddressInput");
  const withdrawAmountInput = document.getElementById("withdrawAmountInput");
  const historyLimitInput = document.getElementById("historyLimitInput");

  function show(panel, obj) {
    panel.textContent = typeof obj === "string" ? obj : JSON.stringify(obj, null, 2);
  }

  async function req(url, options = {}) {
    const headers = Object.assign({"Content-Type": "application/json"}, options.headers || {});
    const res = await fetch(url, Object.assign({}, options, {headers}));
    let payload = null;
    try {
      payload = await res.json();
    } catch (e) {
      payload = {"ok": false, "error": "Non-JSON response", "status": res.status};
    }
    if (!res.ok) {
      throw payload;
    }
    return payload;
  }

  async function loadInfo() {
    infoPanel.textContent = "Loading...";
    try {
      const data = await req("{{ P }}/api/wrtc-bridge/info");
      show(infoPanel, data);
    } catch (err) {
      show(infoPanel, err);
    }
  }

  async function submitDeposit() {
    const key = apiKeyInput.value.trim();
    if (!key) {
      show(depositPanel, "X-API-Key is required.");
      return;
    }
    const txSig = txSigInput.value.trim();
    if (!txSig) {
      show(depositPanel, "tx_signature is required.");
      return;
    }
    depositPanel.textContent = "Submitting...";
    try {
      const data = await req("{{ P }}/api/wrtc-bridge/deposit", {
        method: "POST",
        headers: {"X-API-Key": key},
        body: JSON.stringify({tx_signature: txSig})
      });
      show(depositPanel, data);
      await loadInfo();
    } catch (err) {
      show(depositPanel, err);
    }
  }

  async function submitWithdraw() {
    const key = apiKeyInput.value.trim();
    if (!key) {
      show(withdrawPanel, "X-API-Key is required.");
      return;
    }
    const toAddress = withdrawAddressInput.value.trim();
    const amount = Number(withdrawAmountInput.value || 0);
    withdrawPanel.textContent = "Submitting...";
    try {
      const data = await req("{{ P }}/api/wrtc-bridge/withdraw", {
        method: "POST",
        headers: {"X-API-Key": key},
        body: JSON.stringify({to_address: toAddress, amount})
      });
      show(withdrawPanel, data);
      await loadInfo();
    } catch (err) {
      show(withdrawPanel, err);
    }
  }

  async function loadHistory() {
    const key = apiKeyInput.value.trim();
    if (!key) {
      show(historyPanel, "X-API-Key is required.");
      return;
    }
    const limit = Number(historyLimitInput.value || 50);
    historyPanel.textContent = "Loading...";
    try {
      const data = await req(`{{ P }}/api/wrtc-bridge/history?limit=${limit}`, {
        headers: {"X-API-Key": key}
      });
      show(historyPanel, data);
    } catch (err) {
      show(historyPanel, err);
    }
  }

  document.getElementById("loadInfoBtn").addEventListener("click", loadInfo);
  document.getElementById("depositBtn").addEventListener("click", submitDeposit);
  document.getElementById("withdrawBtn").addEventListener("click", submitWithdraw);
  document.getElementById("historyBtn").addEventListener("click", loadHistory);
  loadInfo();
</script>
{% endblock %}

{% block extra_js %}
<script>
  // Umami Event Tracking Helper
  function trackFunnel(eventName, details = {}) {
    if (window.umami) {
      window.umami.track(eventName, details);
    }
  }

  // Tracking for analytics events
  document.addEventListener('DOMContentLoaded', () => {
    trackFunnel('Funnel: View Bridge Console');

    const dBtn = document.getElementById("depositBtn");
    if (dBtn) dBtn.addEventListener("click", () => trackFunnel('Funnel: Start Deposit Verification'));

    const wBtn = document.getElementById("withdrawBtn");
    if (wBtn) wBtn.addEventListener("click", () => trackFunnel('Funnel: Start Withdrawal Queue'));

    const hBtn = document.getElementById("historyBtn");
    if (hBtn) hBtn.addEventListener("click", () => trackFunnel('Funnel: View Bridge History'));
    
    const raydiumBtn = document.querySelector('a[href*="raydium.io"]');
    if (raydiumBtn) {
      raydiumBtn.addEventListener('click', () => trackFunnel('Funnel: Click Buy Credits (Raydium)'));
    }
  });
</script>
{% endblock %}
