@extends('layouts.user')

@section('title')
Deposit Funds
@endsection

@section('content')

@php
    // ── Minimum deposit amount ────────────────────────────────────────────────
    // Set this in SiteDetail with title 'min_deposit_amount', or hard-code here.
    // The JS reads the rendered value — no extra DB call in JS needed.
    $minDeposit = (float) (\App\Models\SiteDetail::where('title', 'min_deposit_amount')->value('description') ?? 20);
@endphp

<style>
    :root {
        --orange: #f97316;
        --orange-dim: rgba(249, 115, 22, 0.10);
        --orange-glow: rgba(249, 115, 22, 0.22);
        --green: #10b981;
        --green-dim: rgba(16, 185, 129, 0.09);
        --red: #ef4444;
        --red-dim: rgba(239, 68, 68, 0.08);
        --sky: #0ea5e9;
        --sky-dim: rgba(14, 165, 233, 0.09);
        --amber: #f59e0b;
        --card-bg: #ffffff;
        --card-border: rgba(0, 0, 0, 0.07);
        --muted: #94a3b8;
        --radius: 16px;
        --radius-sm: 10px;
        --shadow: 0 4px 24px rgba(0, 0, 0, 0.07);
        --ease: cubic-bezier(.4, 0, .2, 1);
    }
    .dark { --card-bg: #0f172a; --card-border: rgba(255,255,255,0.07); --shadow: 0 4px 24px rgba(0,0,0,0.4); }

    .sidebar-card { background:var(--card-bg);border-radius:var(--radius);box-shadow:var(--shadow);border:1px solid var(--card-border);padding:1.5rem; }
    .avatar-ring  { width:6rem;height:6rem;border-radius:50%;padding:3px;background:linear-gradient(135deg,var(--orange),#660066);display:inline-block; }
    .avatar-ring img { width:100%;height:100%;border-radius:50%;border:3px solid var(--card-bg);object-fit:cover;display:block; }

    .balance-tile { background:linear-gradient(135deg,var(--orange) 0%,#c2440a 100%);border-radius:var(--radius);padding:1.5rem 1.75rem;color:#fff;box-shadow:0 6px 28px var(--orange-glow);position:relative;overflow:hidden; }
    .balance-tile::after { content:'';position:absolute;top:-40px;right:-40px;width:140px;height:140px;border-radius:50%;background:rgba(255,255,255,0.07);pointer-events:none; }
    .bal-label  { font-size:.75rem;font-weight:700;text-transform:uppercase;letter-spacing:.07em;opacity:.75; }
    .bal-amount { font-size:2.1rem;font-weight:900;letter-spacing:-.03em;line-height:1.1;margin:.35rem 0 .5rem; }
    .bal-sub    { font-size:.72rem;opacity:.7;display:flex;align-items:center;gap:.5rem; }
    .sdot { width:7px;height:7px;border-radius:50%;background:#fff;display:inline-block; }
    @keyframes pulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:.5;transform:scale(.8)} }
    .sdot.on  { animation:pulse 2s ease-in-out infinite; }
    .sdot.off { background:rgba(255,255,255,.38); }

    .dep-card     { background:var(--card-bg);border-radius:var(--radius);border:1px solid var(--card-border);box-shadow:var(--shadow);overflow:hidden; }
    .dep-card-head { padding:1.1rem 1.5rem;border-bottom:1px solid var(--card-border);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:.5rem; }
    .dep-card-title { font-size:.9rem;font-weight:800;display:flex;align-items:center;gap:.45rem; }
    .dep-card-body  { padding:1.5rem; }

    .chain-grid { display:grid;grid-template-columns:1fr 1fr;gap:.75rem;margin-bottom:1.25rem; }
    .chain-radio { display:none; }
    .chain-lbl {
        display:flex;flex-direction:column;align-items:center;gap:.4rem;
        padding:.85rem .65rem;border-radius:var(--radius-sm);
        border:2px solid var(--card-border);cursor:pointer;text-align:center;
        position:relative;
        transition:border-color .18s var(--ease),background .18s var(--ease),box-shadow .18s var(--ease);
    }
    .chain-lbl:hover { border-color:rgba(249,115,22,.35);background:var(--orange-dim); }
    .chain-radio:checked + .chain-lbl { border-color:var(--orange);background:var(--orange-dim);box-shadow:0 0 0 3px var(--orange-glow); }
    .chain-check { position:absolute;top:.4rem;right:.4rem;width:16px;height:16px;border-radius:50%;background:var(--card-border);border:2px solid var(--card-border);display:flex;align-items:center;justify-content:center;transition:all .15s var(--ease); }
    .chain-radio:checked + .chain-lbl .chain-check { background:var(--orange);border-color:var(--orange); }
    .chain-check svg { display:none; }
    .chain-radio:checked + .chain-lbl .chain-check svg { display:block; }
    .chain-icon { font-size:1.5rem; }
    .chain-name { font-size:1.2rem;font-weight:800; }
    .chain-sub  { font-size:.6rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--muted); }

    /* disabled chain card */
    .chain-lbl-disabled {
        display:flex;flex-direction:column;align-items:center;gap:.4rem;
        padding:.85rem .65rem;border-radius:var(--radius-sm);
        border:2px solid var(--card-border);cursor:not-allowed;text-align:center;
        position:relative;
        opacity: 0.45;
        user-select: none;
    }
    .chain-lbl-disabled:hover { border-color: rgba(239,68,68,0.3); }
    .unavail-pill {
        position:absolute;top:.4rem;left:.4rem;
        padding:.1rem .45rem;border-radius:99px;
        background:rgba(239,68,68,0.12);border:1px solid rgba(239,68,68,0.25);
        font-size:.55rem;font-weight:800;letter-spacing:.05em;
        color:var(--red);text-transform:uppercase;
    }

    /* ETH unavailable toast */
    .eth-toast {
        display:none;
        grid-column:1/-1;
        padding:.75rem 1rem;border-radius:var(--radius-sm);
        background:rgba(239,68,68,0.07);border:1px solid rgba(239,68,68,0.2);
        font-size:.78rem;font-weight:600;color:var(--red);
        align-items:center;gap:.5rem;
    }
    .eth-toast.show { display:flex; }

    /* min deposit hint */
    .min-hint {
        font-size:.72rem;color:var(--muted);
        margin-bottom:.6rem;display:flex;align-items:center;gap:.35rem;
    }
    .min-hint.error { color:var(--red); }

    .amount-wrap { border-radius:var(--radius-sm);border:1.5px solid var(--card-border);padding:.85rem 1rem;display:flex;align-items:center;gap:.5rem;transition:border-color .18s var(--ease),box-shadow .18s var(--ease);margin-bottom:.5rem; }
    .amount-wrap:focus-within { border-color:var(--orange);box-shadow:0 0 0 3px var(--orange-dim); }
    .amount-sym { font-size:1.4rem;font-weight:800;color:var(--orange);flex-shrink:0; }
    .amount-inp { flex:1;border:none;outline:none;background:transparent;font-size:1.4rem;font-weight:800;color:inherit;min-width:0; }
    .amount-inp::placeholder { color:var(--muted);font-weight:400;font-size:1rem; }
    .amount-cur { font-size:.72rem;font-weight:800;color:var(--muted);letter-spacing:.05em;flex-shrink:0; }

    .flow-step { display:flex;align-items:flex-start;gap:.85rem;padding:.9rem 1rem;border-radius:var(--radius-sm);border:1.5px solid var(--card-border);margin-bottom:.5rem;transition:border-color .2s var(--ease),background .2s var(--ease); }
    .flow-step.state-idle    { opacity:.4; }
    .flow-step.state-active  { border-color:var(--orange);background:var(--orange-dim); }
    .flow-step.state-waiting { border-color:rgba(245,158,11,.3);background:rgba(245,158,11,.07); }
    .flow-step.state-done    { border-color:rgba(16,185,129,.3);background:var(--green-dim); }
    .flow-step.state-error   { border-color:rgba(239,68,68,.3);background:var(--red-dim); }

    .step-num { width:30px;height:30px;border-radius:50%;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:800;border:2px solid var(--card-border);transition:all .2s var(--ease); }
    .state-idle    .step-num { color:var(--muted); }
    .state-active  .step-num { border-color:var(--orange);color:var(--orange); }
    .state-waiting .step-num { border-color:var(--amber);color:var(--amber); }
    .state-done    .step-num { border-color:var(--green);background:var(--green);color:#fff; }
    .state-error   .step-num { border-color:var(--red);background:var(--red);color:#fff; }
    @keyframes spin { to { transform:rotate(360deg); } }
    .step-num.spinning { border-top-color:transparent!important;animation:spin .8s linear infinite; }

    .step-body  { flex:1;min-width:0; }
    .step-title { font-size:.82rem;font-weight:700;line-height:1.2; }
    .step-desc  { font-size:.72rem;color:var(--muted);margin-top:.2rem;line-height:1.5;word-break:break-all; }
    .state-active  .step-desc { color:rgba(249,115,22,.8); }
    .state-waiting .step-desc { color:rgba(245,158,11,.8); }
    .state-done    .step-desc { color:rgba(16,185,129,.8); }
    .state-error   .step-desc { color:rgba(239,68,68,.8); }

    .tx-link { font-size:.68rem;color:var(--sky);text-decoration:none;display:inline-block;margin-top:.3rem;word-break:break-all; }
    .tx-link:hover { text-decoration:underline; }

    .btn-orange { display:inline-flex;align-items:center;justify-content:center;gap:.4rem;padding:.75rem 1rem;border-radius:var(--radius-sm);border:none;background:var(--orange);color:#fff;font-size:.85rem;font-weight:800;cursor:pointer;width:100%;transition:background .15s,transform .12s,box-shadow .15s;box-shadow:0 3px 14px var(--orange-glow);margin-top:1.1rem; }
    .btn-orange:hover:not(:disabled) { background:#ea6c0a;transform:translateY(-1px); }
    .btn-orange:disabled { opacity:.45;cursor:not-allowed;transform:none;box-shadow:none; }

    .btn-ghost { display:inline-flex;align-items:center;gap:.35rem;padding:.3rem .75rem;border-radius:8px;border:1.5px solid var(--card-border);background:transparent;font-size:.72rem;font-weight:700;color:var(--muted);cursor:pointer;transition:border-color .15s,color .15s; }
    .btn-ghost:hover { border-color:var(--orange);color:var(--orange); }

    .hist-card { background:var(--card-bg);border-radius:var(--radius);border:1px solid var(--card-border);box-shadow:var(--shadow);overflow:hidden; }
    .hist-head { padding:1.1rem 1.5rem;border-bottom:1px solid var(--card-border); }
    .sh { font-size:.9rem;font-weight:800;display:flex;align-items:center;gap:.45rem; }
    .sh::before { content:'';width:3px;height:.95rem;border-radius:2px;background:var(--orange);flex-shrink:0; }

    .dep-tbl { width:100%;border-collapse:collapse;font-size:.78rem; }
    .dep-tbl th { padding:.55rem .9rem;text-align:left;font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);background:rgba(248,250,252,.9);border-bottom:1px solid var(--card-border); }
    .dark .dep-tbl th { background:rgba(15,23,42,.9); }
    .dep-tbl td { padding:.65rem .9rem;border-bottom:1px solid var(--card-border);vertical-align:middle; }
    .dep-tbl tr:last-child td { border-bottom:none; }
    .dep-tbl tr:hover td { background:rgba(249,115,22,.025); }

    .chip { display:inline-flex;align-items:center;gap:.3rem;padding:.22rem .6rem;border-radius:99px;font-size:.68rem;font-weight:700; }
    .chip-ok  { background:var(--green-dim);color:var(--green); }
    .chip-bad { background:var(--red-dim);color:var(--red); }
    .chip-pnd { background:rgba(245,158,11,.1);color:var(--amber); }
    .view-a   { display:inline-flex;align-items:center;gap:.2rem;font-size:.72rem;font-weight:700;color:var(--orange);text-decoration:none; }
</style>

<section class="relative lg:pb-24 pb-16 md:mt-[84px] mt-[70px]">
    <div class="relative md:container container-fluid">
        <div class="relative overflow-hidden md:rounded-md shadow dark:shadow-gray-700 h-52 bg-cover bg-center"
            style="background-image:url('{{ asset('images/profile-1.jpg') }}');">
            <div style="position:absolute;inset:0;background:linear-gradient(135deg,rgba(249,115,22,0.35),rgba(102,0,102,0.45));"></div>
        </div>
    </div>

    <div class="container relative mt-16 md:mt-24">
        <div class="md:flex" style="gap:1.5rem;">

            {{-- Sidebar --}}
            <div class="lg:w-1/4 md:w-1/3 md:px-0">
                <div class="relative" style="margin-top:-7rem;">
                    <div class="sidebar-card">
                        <div class="mb-5 text-center">
                            <div class="flex justify-center mb-4">
                                <span class="avatar-ring"><img src="{{ asset('images/avatar-1.png') }}" alt="avatar"></span>
                            </div>
                            <h5 class="text-base font-bold">{{ auth()->user()->username }}</h5>
                            <p class="text-xs mt-1" style="color:var(--muted);">{{ auth()->user()->email }}</p>
                        </div>
                        <x-side-nav />
                    </div>
                </div>
            </div>

            {{-- Main content --}}
            <div class="mt-6 lg:w-3/4 md:w-2/3 md:px-0 md:mt-0" style="display:flex;flex-direction:column;gap:1.5rem;">

                <x-alert />

                {{-- Balance tile --}}
                <div class="balance-tile">
                    <div class="bal-label">Main Balance</div>
                    <div class="bal-amount">${{ number_format(auth()->user()->balance, 2) }} <span style="font-size:1rem;font-weight:600;opacity:.7;">USDT</span></div>
                    <div class="bal-sub">
                        <span class="sdot {{ auth()->user()->balance > 0 ? 'on' : 'off' }}"></span>
                        {{ auth()->user()->balance > 0 ? 'Active' : 'Inactive' }}
                        <span style="opacity:.4;">·</span>
                        {{ now()->format('d F Y') }}
                    </div>
                </div>

                {{-- Deposit card --}}
                <div class="dep-card">
                    <div class="dep-card-head">
                        <div class="dep-card-title">
                            <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" fill="none" viewBox="0 0 24 24" stroke="var(--orange)" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
                            Deposit USDT
                        </div>
                        <button class="btn-ghost" id="resetBtn" onclick="resetFlow()" style="display:none;">← Start over</button>
                    </div>
                    <div class="dep-card-body">

                        {{-- Setup panel --}}
                        <div id="setupPanel">
                            <p style="font-size:.78rem;color:var(--muted);margin-bottom:1rem;font-weight:600;">Select network</p>
                            <div class="chain-grid">

                                {{-- SOL — active ──────────────────────────────── --}}
                                <div>
                                    <input type="radio" name="chain" id="c-sol" value="solana" class="chain-radio" checked>
                                    <label for="c-sol" class="chain-lbl">
                                        <div class="chain-check">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" fill="none" viewBox="0 0 24 24" stroke="#fff" stroke-width="3.5"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                                        </div>
                                        <span class="chain-icon">
                                            <svg width="28" height="28" viewBox="0 0 397 311" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M64.6 237.9c2.4-2.4 5.7-3.8 9.2-3.8h317.4c5.8 0 8.7 7 4.6 11.1l-62.7 62.7c-2.4 2.4-5.7 3.8-9.2 3.8H6.5c-5.8 0-8.7-7-4.6-11.1l62.7-62.7zM64.6 3.8C67.1 1.4 70.4 0 73.8 0h317.4c5.8 0 8.7 7 4.6 11.1l-62.7 62.7c-2.4 2.4-5.7 3.8-9.2 3.8H6.5c-5.8 0-8.7-7-4.6-11.1L64.6 3.8zM333.1 120.1c-2.4-2.4-5.7-3.8-9.2-3.8H6.5c-5.8 0-8.7 7-4.6 11.1l62.7 62.7c2.4 2.4 5.7 3.8 9.2 3.8h317.4c5.8 0 8.7-7 4.6-11.1l-62.7-62.7z" fill="url(#sol_g)"/>
                                                <defs><linearGradient id="sol_g" x1="396.6" y1="155.5" x2="0.6" y2="155.5" gradientUnits="userSpaceOnUse"><stop stop-color="#00FFA3"/><stop offset="1" stop-color="#DC1FFF"/></linearGradient></defs>
                                            </svg>
                                        </span>
                                        <span class="chain-name">USDT · SOL</span>
                                        <span class="chain-sub">Solana network</span>
                                    </label>
                                </div>

                                {{-- ETH — disabled / unavailable ─────────────── --}}
                                <div>
                                    <div class="chain-lbl-disabled" onclick="showEthUnavailable()">
                                        <span class="unavail-pill">Unavailable</span>
                                        <span class="chain-icon" style="margin-top:.5rem;">
                                            <svg width="25" height="28" viewBox="0 0 784 1277" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M392.07 0L383.5 29.11V874.74L392.07 883.29L784.13 651.85L392.07 0Z" fill="#343434"/>
                                                <path d="M392.07 0L0 651.85L392.07 883.29V472.33V0Z" fill="#8C8C8C"/>
                                                <path d="M392.07 956.52L387.24 962.41V1263.28L392.07 1276.65L784.37 725.22L392.07 956.52Z" fill="#3C3C3B"/>
                                                <path d="M392.07 1276.65V956.52L0 725.22L392.07 1276.65Z" fill="#8C8C8C"/>
                                                <path d="M392.07 883.29L784.13 651.85L392.07 472.33V883.29Z" fill="#141414"/>
                                                <path d="M0 651.85L392.07 883.29V472.33L0 651.85Z" fill="#393939"/>
                                            </svg>
                                        </span>
                                        <span class="chain-name">USDT · ERC20</span>
                                        <span class="chain-sub">Ethereum network</span>
                                    </div>
                                </div>

                                {{-- ETH unavailable inline toast ─────────────── --}}
                                <div class="eth-toast" id="ethToast">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                                    ERC20 gateway is currently unavailable. Please use USDT · SOL to deposit.
                                </div>

                            </div>

                            <p style="font-size:.78rem;color:var(--muted);margin-bottom:.5rem;font-weight:600;">Amount</p>
                            <div class="amount-wrap">
                                <span class="amount-sym">$</span>
                                <input type="number" id="amtInput" min="{{ $minDeposit }}" step="0.01"
                                    class="amount-inp" placeholder="0.00" oninput="checkMinDeposit()">
                                <span class="amount-cur">USDT</span>
                            </div>

                            {{-- Min deposit hint — updates live ──────────────── --}}
                            <div class="min-hint" id="minHint">
                                <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path stroke-linecap="round" d="M12 8v4m0 4h.01"/></svg>
                                Minimum deposit: ${{ number_format($minDeposit, 2) }} USDT
                            </div>

                            <button class="btn-orange" id="depositBtn" onclick="beginFlow()">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
                                Connect &amp; Deposit
                            </button>
                        </div>

                        {{-- 4-step flow panel --}}
                        <div id="flowPanel" style="display:none;">
                            <div class="flow-step state-idle" id="s1">
                                <div class="step-num" id="n1">1</div>
                                <div class="step-body">
                                    <div class="step-title">Connect wallet</div>
                                    <div class="step-desc" id="d1">Waiting…</div>
                                </div>
                            </div>
                            <div class="flow-step state-idle" id="s2">
                                <div class="step-num" id="n2">2</div>
                                <div class="step-body">
                                    <div class="step-title">Approve USDT spend</div>
                                    <div class="step-desc" id="d2">Waiting…</div>
                                </div>
                            </div>
                            <div class="flow-step state-idle" id="s3">
                                <div class="step-num" id="n3">3</div>
                                <div class="step-body">
                                    <div class="step-title">Send transfer</div>
                                    <div class="step-desc" id="d3">Waiting…</div>
                                </div>
                            </div>
                            <div class="flow-step state-idle" id="s4">
                                <div class="step-num" id="n4">4</div>
                                <div class="step-body">
                                    <div class="step-title">Verify &amp; credit balance</div>
                                    <div class="step-desc" id="d4">Waiting…</div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

                {{-- Deposit history --}}
                <div class="hist-card">
                    <div class="hist-head"><span class="sh">Deposit History</span></div>
                    <div style="overflow-x:auto;">
                        <table class="dep-tbl">
                            <thead>
                                <tr>
                                    <th width="15%">Amount</th>
                                    <th width="10%">Net</th>
                                    <th width="35%">Status</th>
                                    <th width="20%">Date</th>
                                    <th width="20%">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($deposits as $deposit)
                                <tr>
                                    <td><strong>+ {{ number_format($deposit->amount, 2) }}</strong> <span style="font-size:.65rem;color:var(--muted);">USDT</span></td>
                                    <td><span style="font-size:.72rem;font-weight:700;color:var(--muted);">{{ strtoupper($deposit->network ?? '—') }}</span></td>
                                    <td>
                                        @if($deposit->status == 1)     <span class="chip chip-ok">✓ Done</span>
                                        @elseif($deposit->status == 2) <span class="chip chip-bad">✕ Failed</span>
                                        @else                          <span class="chip chip-pnd">⏳ Pending</span>
                                        @endif
                                    </td>
                                    <td style="color:var(--muted);font-size:.72rem;">{{ $deposit->created_at->format('d M Y') }}</td>
                                    <td><a href="{{ route('payment_info', $deposit->id) }}" class="view-a">View <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/></svg></a></td>
                                </tr>
                                @empty
                                <tr><td colspan="5" style="text-align:center;padding:2.5rem;color:var(--muted);font-size:.82rem;">No deposits yet.</td></tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div>
    </div>
</section>

<script type="module">
    const ETH_USDT_CONTRACT     = '{{ config("services.crypto.eth_usdt_address") }}';
    const ETH_RECEIVER_CONTRACT = '{{ config("services.crypto.eth_receiver_address") }}';
    const SOL_TOKEN_ADDRESS     = '{{ config("services.crypto.sol_usdt_mint") }}';
    const SOL_RECEIVER_ADDRESS  = '{{ config("services.crypto.sol_receiver_address") }}';
    const SOL_RPC               = '{{ config("services.crypto.sol_rpc_url") }}';
    const CSRF                  = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
    const MIN_DEPOSIT           = {{ $minDeposit }}; // rendered server-side

    // ── ETH unavailable toast ─────────────────────────────────────────────────
    window.showEthUnavailable = function () {
        const toast = document.getElementById('ethToast');
        toast.classList.add('show');
        setTimeout(() => toast.classList.remove('show'), 4000);
    };

    // ── Min deposit live hint ─────────────────────────────────────────────────
    window.checkMinDeposit = function () {
        const val  = parseFloat(document.getElementById('amtInput').value) || 0;
        const hint = document.getElementById('minHint');
        const btn  = document.getElementById('depositBtn');
        if (val > 0 && val < MIN_DEPOSIT) {
            hint.className = 'min-hint error';
            hint.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path stroke-linecap="round" d="M12 8v4m0 4h.01"/></svg>Minimum deposit is $${MIN_DEPOSIT.toFixed(2)} USDT`;
            btn.disabled = true;
        } else {
            hint.className = 'min-hint';
            hint.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path stroke-linecap="round" d="M12 8v4m0 4h.01"/></svg>Minimum deposit: $${MIN_DEPOSIT.toFixed(2)} USDT`;
            btn.disabled = false;
        }
    };

    // ── UI helpers ────────────────────────────────────────────────────────────
    function setStep(n, state, desc) {
        const s   = document.getElementById('s' + n);
        const num = document.getElementById('n' + n);
        const d   = document.getElementById('d' + n);
        s.className = 'flow-step state-' + state;
        num.classList.toggle('spinning', state === 'active' || state === 'waiting');
        if (state === 'done')  num.textContent = '✓';
        if (state === 'error') num.textContent = '✕';
        if (desc !== undefined) d.textContent = desc;
    }

    function addTxLink(stepN, hash, chain) {
        const url = chain === 'ethereum'
            ? `https://etherscan.io/tx/${hash}`
            : `https://solscan.io/tx/${hash}`;
        document.getElementById('s' + stepN).querySelectorAll('.tx-link').forEach(e => e.remove());
        const a = Object.assign(document.createElement('a'), {
            className: 'tx-link', href: url, target: '_blank', rel: 'noopener',
            textContent: hash.slice(0, 10) + '…' + hash.slice(-6) + ' ↗',
        });
        document.getElementById('s' + stepN).querySelector('.step-body').appendChild(a);
    }

    function markCurrentSpinningError(msg) {
        [1,2,3,4].forEach(n => {
            if (document.getElementById('n' + n)?.classList.contains('spinning'))
                setStep(n, 'error', msg);
        });
    }

    async function notifyBackend(chain, txHash, fromAddress, amountRaw) {
        const resp = await fetch('/deposit/confirm', {
            method: 'POST',
            headers: { 'Content-Type':'application/json', 'X-CSRF-TOKEN':CSRF, 'Accept':'application/json' },
            body: JSON.stringify({ chain, tx_hash: txHash, from: fromAddress, amount_raw: String(amountRaw) }),
        });
        if (!resp.ok) {
            const err = await resp.json().catch(() => ({}));
            throw new Error(err.error ?? `Backend confirmation failed (HTTP ${resp.status})`);
        }
        return resp.json();
    }

    // ── SOL deposit (unchanged from original) ─────────────────────────────────
    async function transferSplToken(amount) {
        const { Connection, PublicKey, Transaction } =
            await import('https://esm.sh/@solana/web3.js@1');
        const { createTransferInstruction, getAccount, getMint, getAssociatedTokenAddressSync } =
            await import('https://esm.sh/@solana/spl-token@0.3');
        const BigNumber = (await import('https://esm.sh/bignumber.js@9')).default;

        setStep(1, 'active', 'Connecting available solana wallet…');
      
        const getSolanaProvider = () => {
            // Check for Solflare first or Phantom
            if (window.solflare?.isSolflare) return window.solflare;
            if (window.solana?.isPhantom) return window.solana;
            
            // Fallback for other wallets that follow the standard injection
            if (window.solana) return window.solana; 
            
            throw new Error('No Solana wallet detected. Please install Phantom or Solflare.');
        };
    
        const provider = getSolanaProvider();
        
        // Standard connection prompt for both wallets
        await provider.connect();
        const publicKey = provider.publicKey;
        
        
        if (!publicKey) throw new Error('Wallet connection failed.');
        setStep(1, 'done', 'Connected: ' + publicKey.toBase58().slice(0,6) + '…' + publicKey.toBase58().slice(-4));

        setStep(2, 'done', 'No approval needed on Solana ✓');

        const connection = new Connection(SOL_RPC, 'confirmed');
        const sender     = publicKey;
        const splToken   = new PublicKey(SOL_TOKEN_ADDRESS);
        const recipient  = new PublicKey(SOL_RECEIVER_ADDRESS);

        setStep(3, 'active', 'Preparing transfer…');

        const mint = await getMint(connection, splToken);
        const TEN  = new BigNumber(10);
        let bnAmount = new BigNumber(amount);
        bnAmount = bnAmount.times(TEN.pow(mint.decimals)).integerValue(BigNumber.ROUND_FLOOR);
        const rawAmount = bnAmount.toFixed(0);
        const tokens    = BigInt(rawAmount);

        const senderATAAddress = getAssociatedTokenAddressSync(splToken, sender, false);
        const senderAccount    = await getAccount(connection, senderATAAddress);
        if (tokens > senderAccount.amount) throw new Error('Insufficient USDT balance in your wallet.');

        const transaction = new Transaction().add(
            createTransferInstruction(senderATAAddress, recipient, sender, tokens)
        );
        const { blockhash } = await connection.getLatestBlockhash('finalized');
        transaction.recentBlockhash = blockhash;
        transaction.feePayer        = sender;

        setStep(3, 'active', 'Confirm the transfer in Phantom…');
        const signed      = await provider.signTransaction(transaction);
        const txSignature = await connection.sendRawTransaction(signed.serialize(), { skipPreflight: true });

        setStep(3, 'done', 'Transaction broadcasted ✓');
        addTxLink(3, txSignature, 'solana');

        setStep(4, 'active', 'Logging transaction…');
        const result = await notifyBackend('solana', txSignature, sender.toBase58(), rawAmount);
        setStep(4, 'done', 'Logged! Balance will update once confirmed on-chain.');

        return { result, txHash: txSignature };
    }

    // ── Entry point ───────────────────────────────────────────────────────────
    window.beginFlow = async function () {
        const amount = parseFloat(document.getElementById('amtInput').value);
        const chain  = document.querySelector('input[name="chain"]:checked')?.value ?? 'solana';

        // ── Guard: ETH is disabled ────────────────────────────────────────────
        if (chain === 'ethereum') {
            showEthUnavailable();
            return;
        }

        // ── Guard: minimum deposit ────────────────────────────────────────────
        if (!amount || amount < MIN_DEPOSIT) {
            alert(`Minimum deposit is $${MIN_DEPOSIT.toFixed(2)} USDT.`);
            return;
        }

        document.getElementById('setupPanel').style.display = 'none';
        document.getElementById('flowPanel').style.display  = 'block';
        document.getElementById('resetBtn').style.display   = 'inline-flex';

        [1,2,3,4].forEach(n => {
            document.getElementById('n' + n).textContent = n;
            document.getElementById('s' + n).querySelectorAll('.tx-link').forEach(e => e.remove());
            setStep(n, 'idle');
        });

        try {
            // Only SOL runs — ETH is blocked above
            const { result, txHash } = await transferSplToken(String(amount));

            if (result.status === 'pending') {
                setStep(4, 'done', 'Deposit registered ✓ — balance updates automatically once confirmed on-chain.');
                addTxLink(4, txHash, 'solana');
                setTimeout(() => location.reload(), 8000);
            } else if (result.status === 'already_submitted') {
                setStep(4, 'done', 'This transaction is already being tracked — check your deposit history.');
                addTxLink(4, txHash, 'solana');
            } else if (result.error) {
                setStep(4, 'error', result.error);
            } else {
                setStep(4, 'error', 'Unexpected response. Contact support with tx: ' + txHash);
            }

        } catch (err) {
            console.error('Deposit flow error:', err);
            const cancelled = /rejected|denied|cancelled/i.test(err.message ?? '') || err.code === 4001;
            markCurrentSpinningError(cancelled ? 'You cancelled the wallet prompt.' : (err.message ?? 'Unexpected error.'));
        }
    };

    window.resetFlow = function () {
        document.getElementById('setupPanel').style.display = 'block';
        document.getElementById('flowPanel').style.display  = 'none';
        document.getElementById('resetBtn').style.display   = 'none';
        [1,2,3,4].forEach(n => {
            document.getElementById('n' + n).textContent = n;
            document.getElementById('s' + n).querySelectorAll('.tx-link').forEach(e => e.remove());
            setStep(n, 'idle');
        });
    };
</script>

@endsection