@extends('layouts.dashboard')

@section('title', 'Cashout')

@push('css')
    <style>
        .wallet-v2-heading { display:flex; align-items:flex-end; justify-content:space-between; gap:18px; margin-bottom:18px; }
        .wallet-v2-heading h1 { margin:0; color:var(--user-text, #f7f8fc); font-size:clamp(1.7rem, 3vw, 2.35rem); font-weight:800; }
        .wallet-v2-heading p { max-width:620px; margin:7px 0 0; color:var(--user-muted, #aab2c5); }
        .wallet-v2-overview { display:grid; grid-template-columns:minmax(0, 1.1fr) minmax(280px, .9fr); gap:14px; margin-bottom:14px; }
        .wallet-v2-balance { position:relative; min-height:190px; overflow:hidden; padding:30px; background:radial-gradient(circle at 88% 10%, rgba(72,189,244,.3), transparent 30%), linear-gradient(130deg, #102b48, #11172b 65%, #171233); border:1px solid rgba(72,189,244,.3); border-radius:8px; }
        .wallet-v2-balance span, .wallet-v2-balance strong, .wallet-v2-balance small { display:block; }
        .wallet-v2-balance > span { color:#c9d2e2; font-weight:700; }
        .wallet-v2-balance strong { margin:12px 0 4px; color:#fff; font-size:clamp(2rem, 5vw, 3.4rem); line-height:1; }
        .wallet-v2-balance small { color:var(--user-cyan, #48bdf4); font-size:1rem; }
        .wallet-v2-balance a { margin-top:22px; }
        .wallet-v2-guide { display:grid; gap:9px; padding:18px; background:var(--user-surface, #11192a); border:1px solid var(--user-border, #263149); border-radius:8px; }
        .wallet-v2-step { display:flex; min-height:46px; align-items:center; gap:11px; color:var(--user-body, #d7dce7); }
        .wallet-v2-step b { display:grid; width:30px; height:30px; flex:0 0 30px; place-items:center; color:#07101d; background:var(--user-cyan, #48bdf4); border-radius:50%; }
        .wallet-v2-toolbar { display:flex; flex-wrap:wrap; gap:9px; align-items:center; }
        .wallet-v2-tabs { display:flex; gap:5px; padding:4px; background:#0d1425; border:1px solid var(--user-border, #263149); border-radius:8px; }
        .wallet-v2-tabs button { min-height:38px; padding:0 14px; color:var(--user-muted, #aab2c5); background:transparent; border:0; border-radius:6px; font-weight:700; }
        .wallet-v2-tabs button.active { color:#07101d; background:var(--user-cyan, #48bdf4); }
        .wallet-v2-search { position:relative; min-width:min(290px, 100%); margin-left:auto; }
        .wallet-v2-search input { width:100%; min-height:46px; padding:0 42px 0 13px; color:var(--user-text, #f7f8fc); background:#0d1425; border:1px solid var(--user-border, #263149); border-radius:8px; }
        .wallet-v2-search svg { position:absolute; top:50%; right:13px; color:var(--user-muted, #aab2c5); transform:translateY(-50%); }
        .cashout-v2-preview { display:flex; justify-content:space-between; gap:12px; padding:12px; margin-top:10px; background:rgba(72,189,244,.08); border:1px solid rgba(72,189,244,.2); border-radius:7px; }
        .cashout-v2-preview strong { color:var(--user-cyan, #48bdf4); }
        .cashout-unit-switch { display:grid; grid-template-columns:1fr 1fr; gap:4px; padding:4px; margin-bottom:12px; background:var(--user-page, #0b1120); border:1px solid var(--user-border, #263149); border-radius:8px; }
        .cashout-unit-switch button { min-height:44px; color:var(--user-muted, #aab2c5); background:transparent; border:0; border-radius:6px; font-weight:800; }
        .cashout-unit-switch button.active { color:#07101d; background:var(--user-cyan, #48bdf4); }
        @media (max-width:767px) {
            .wallet-v2-heading { align-items:flex-start; flex-direction:column; }
            .wallet-v2-overview { grid-template-columns:1fr; }
            .wallet-v2-balance { min-height:210px; padding:24px 20px; }
            .wallet-v2-toolbar { align-items:stretch; flex-direction:column; }
            .wallet-v2-tabs { overflow-x:auto; }
            .wallet-v2-tabs button { flex:1 0 auto; }
            .wallet-v2-search { width:100%; margin-left:0; }
        }
    </style>
@endpush

@section('content')
    @php
        $user = auth()->user();
        $cryptoNames = ['binance', 'bitcoin', 'btc', 'litecoin', 'ltc', 'tron', 'trx', 'dogecoin', 'doge', 'ethereum', 'eth', 'usdt', 'crypto'];
        $cryptoPayments = $payments->filter(function ($payment) use ($cryptoNames) {
            $name = strtolower($payment->name . ' ' . $payment->currency);
            return collect($cryptoNames)->contains(fn ($needle) => str_contains($name, $needle));
        })->values();
        $walletPayments = $payments->reject(fn ($payment) => $cryptoPayments->contains('id', $payment->id))->values();
        $cardTone = function ($payment) {
            $name = strtolower($payment->name . ' ' . $payment->currency);
            if (str_contains($name, 'binance')) return '#020202';
            if (str_contains($name, 'litecoin') || str_contains($name, 'ltc')) return '#626262';
            if (str_contains($name, 'tron') || str_contains($name, 'trx')) return '#050505';
            if (str_contains($name, 'bitcoin') || str_contains($name, 'btc')) return '#f4a20b';
            if (str_contains($name, 'doge')) return '#f7d28c';
            if (str_contains($name, 'paypal')) return '#13bfe6';
            if (str_contains($name, 'google')) return '#06191d';
            return '#15171d';
        };
    @endphp

    @if(session('success'))
        <div class="alert alert-success"><div class="alert-body">{{ session('success') }}</div></div>
    @endif
    @if(session('error'))
        <div class="alert alert-danger"><div class="alert-body">{{ session('error') }}</div></div>
    @endif

    <header class="wallet-v2-heading">
        <div><span class="user-home-eyebrow"><i data-feather="credit-card" aria-hidden="true"></i> Rewards wallet</span><h1>Cashout center</h1><p>Choose an active payout method, review your destination carefully, and track every request.</p></div>
        <a class="btn btn-outline-light" href="#cashoutHistory"><i data-feather="clock" class="me-50" aria-hidden="true"></i>History</a>
    </header>

    <section class="wallet-v2-overview" aria-label="Wallet overview">
        <div class="wallet-v2-balance"><span>Available balance</span><strong>{{ format_coins_as_usd($user->current_points) }}</strong><small>{{ number_format($user->current_points, 0) }} {{ strtolower(site_setting('points_name', 'coins')) }} at {{ number_format(coins_per_usd()) }} = $1</small><a class="btn btn-loot" href="#paymentMethods">Choose a reward</a></div>
        <div class="wallet-v2-guide" aria-label="Cashout steps"><div class="wallet-v2-step"><b>1</b><span>Select an available payment method.</span></div><div class="wallet-v2-step"><b>2</b><span>Enter an amount and payout destination.</span></div><div class="wallet-v2-step"><b>3</b><span>Complete verification when required.</span></div><div class="wallet-v2-step"><b>4</b><span>Track review status in your history.</span></div></div>
    </section>

    <section class="user-page-card loot-shop-panel mb-2" id="paymentMethods">
        <div class="loot-shop-head">
            <div><h2><i data-feather="shopping-cart"></i>Payment methods</h2><p class="loot-muted mb-0">Select a method to begin your cashout</p></div>
        </div>

        <div class="wallet-v2-toolbar mb-2">
            <div class="wallet-v2-tabs" role="group" aria-label="Payment method categories"><button class="active" type="button" data-wallet-filter="all">All</button><button type="button" data-wallet-filter="crypto">Crypto</button><button type="button" data-wallet-filter="wallet">Gift cards & wallets</button></div>
            <label class="wallet-v2-search"><span class="visually-hidden">Search payment methods</span><input id="walletMethodSearch" type="search" placeholder="Search payment methods" aria-label="Search payment methods"><i data-feather="search" aria-hidden="true"></i></label>
        </div>

        <div class="loot-shop-section" data-wallet-group="crypto">
            <h3>Crypto</h3>
            @if($cryptoPayments->count())
                <div class="loot-shop-grid">
                    @foreach($cryptoPayments as $payment)
                        @include('user.partials.payment-card', ['payment' => $payment, 'tone' => $cardTone($payment), 'category' => 'crypto'])
                    @endforeach
                </div>
            @else
                <p class="loot-muted mb-0">No crypto payout methods are active yet.</p>
            @endif
        </div>

        <div class="loot-shop-section" data-wallet-group="wallet">
            <h3>Gift cards & wallets</h3>
            @if($walletPayments->count())
                <div class="loot-shop-grid">
                    @foreach($walletPayments as $payment)
                        @include('user.partials.payment-card', ['payment' => $payment, 'tone' => $cardTone($payment), 'category' => 'wallet'])
                    @endforeach
                </div>
            @else
                <p class="loot-muted mb-0">No gift card or wallet payout methods are active yet.</p>
            @endif
        </div>
    </section>

    <section class="user-page-card loot-shop-history" id="cashoutHistory">
        <div class="loot-shop-head">
            <h2><i data-feather="clock"></i>Cashout history</h2>
            <a href="{{ route('user.transactions') }}" class="btn btn-sm btn-outline-light">Full history</a>
        </div>
        <div class="table-responsive">
            <table class="table loot-profile-table mb-0">
                <thead><tr><th>Method</th><th>Amount</th><th>Account</th><th>Status</th><th>Requested</th></tr></thead>
                <tbody>
                @forelse($withdrawals as $withdrawal)
                    <tr>
                        <td><strong>{{ $withdrawal->method }}</strong></td>
                        <td><strong>{{ format_coins_as_usd($withdrawal->amount) }}</strong></td>
                        <td>{{ $withdrawal->account }}</td>
                        <td><span class="loot-status {{ $withdrawal->status === 'approved' ? 'success' : ($withdrawal->status === 'rejected' ? 'danger' : 'warning') }}">{{ $withdrawal->status === 'pending' && $withdrawal->verification_status !== 'approved' ? 'Face review' : ucfirst($withdrawal->status) }}</span></td>
                        <td>{{ $withdrawal->created_at->diffForHumans() }}</td>
                    </tr>
                @empty
                    <tr><td colspan="5" class="text-center loot-muted py-3">No cashout requests yet.</td></tr>
                @endforelse
                </tbody>
            </table>
        </div>
    </section>

    <div class="modal fade" id="cashoutModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <div class="d-flex align-items-center gap-1 min-w-0">
                        <span class="loot-payment-logo small" id="cashoutLogo"></span>
                        <div class="min-w-0">
                            <h4 class="modal-title loot-section-title text-truncate" id="cashoutTitle">Cashout</h4>
                            <p class="loot-muted mb-0" id="cashoutCurrency">Payment method</p>
                        </div>
                    </div>
                    <button type="button" class="btn-close loot-modal-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                @php $faceRequired = site_bool('protection_require_face_verification', true); @endphp
                <form method="POST" id="cashoutForm" action="#" data-face-required="{{ $faceRequired ? '1' : '0' }}">
                    @csrf
                    <input type="hidden" name="face_image" id="cashoutFaceImage">
                    <div class="modal-body">
                        <p class="loot-muted">Choose the payout amount and destination.{{ $faceRequired ? ' You will verify your face after clicking submit.' : '' }}</p>
                        <fieldset class="mb-1">
                            <legend class="form-label">Withdrawal amount</legend>
                            <div class="cashout-unit-switch" role="group" aria-label="Choose amount unit">
                                <button class="active" type="button" data-cashout-unit="usd" aria-pressed="true">Enter USD</button>
                                <button type="button" data-cashout-unit="coins" aria-pressed="false">Enter coins</button>
                            </div>
                            <input type="hidden" name="amount" id="cashoutAmount">
                            <div data-cashout-panel="usd">
                                <label class="form-label" for="cashoutAmountUsd">Amount in USD</label>
                                <div class="input-group"><span class="input-group-text">$</span><input class="form-control" type="number" min="0.001" step="0.001" max="{{ coins_to_usd($user->current_points) }}" id="cashoutAmountUsd" inputmode="decimal" placeholder="5.00" required></div>
                            </div>
                            <div data-cashout-panel="coins" hidden>
                                <label class="form-label" for="cashoutAmountCoins">Amount in coins</label>
                                <input class="form-control" type="number" min="1" step="1" max="{{ floor($user->current_points) }}" id="cashoutAmountCoins" inputmode="numeric" placeholder="5000">
                            </div>
                            <small class="loot-muted">Available: {{ format_coins_as_usd($user->current_points) }} · {{ number_format($user->current_points, 0) }} coins</small>
                            <div class="cashout-v2-preview" aria-live="polite"><span>Withdrawal value</span><strong id="cashoutValuePreview">$0.00 · 0 coins</strong></div>
                        </fieldset>
                        <div class="mb-1">
                            <label class="form-label" for="cashoutAddress">Account, wallet, email, or number</label>
                            <input class="form-control" type="text" id="cashoutAddress" name="address"
                                   placeholder="Enter payout destination" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-loot" id="cashoutSubmit">{{ $faceRequired ? 'Continue to face verify' : 'Submit cashout' }}</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="cashoutFaceModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <div>
                        <h4 class="modal-title loot-section-title">Face verification</h4>
                        <p class="loot-muted mb-0">Capture a clear selfie to finish this cashout request.</p>
                    </div>
                    <button type="button" class="btn-close loot-modal-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <div class="alert-body">Face verification is required for every cashout. First-time captures must be approved by admin before cashout can continue.</div>
                    </div>
                    <div class="loot-face-capture-grid">
                        <div class="loot-face-camera">
                            <video id="cashoutFaceVideo" autoplay playsinline muted></video>
                            <canvas id="cashoutFaceCanvas" class="d-none" width="720" height="540"></canvas>
                            <div class="loot-face-placeholder" id="cashoutFacePlaceholder">
                                <i data-feather="camera"></i>
                                <strong>Cashout face check</strong>
                                <span>Start camera, capture a clear selfie, then submit.</span>
                            </div>
                        </div>
                        <div class="loot-face-actions">
                            <button class="btn btn-outline-light" type="button" id="cashoutStartCamera">
                                <i data-feather="video"></i>Start camera
                            </button>
                            <button class="btn btn-outline-light" type="button" id="cashoutCaptureFace" disabled>
                                <i data-feather="camera"></i>Capture
                            </button>
                            <button class="btn btn-outline-light" type="button" id="cashoutRetakeFace" disabled>
                                <i data-feather="refresh-cw"></i>Retake
                            </button>
                            <button class="btn btn-loot" type="button" id="cashoutFinalSubmit" disabled>
                                Submit cashout
                            </button>
                            <p class="loot-muted mb-0">This capture is attached to your cashout request for admin review.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        (function () {
            const search = document.getElementById('walletMethodSearch');
            const filters = Array.from(document.querySelectorAll('[data-wallet-filter]'));
            const cards = Array.from(document.querySelectorAll('[data-wallet-category]'));
            const groups = Array.from(document.querySelectorAll('[data-wallet-group]'));
            let category = 'all';

            function applyWalletFilters() {
                const query = (search?.value || '').trim().toLowerCase();
                cards.forEach(function (card) {
                    const categoryMatch = category === 'all' || card.dataset.walletCategory === category;
                    const searchMatch = !query || (card.dataset.walletSearch || '').includes(query);
                    card.hidden = !(categoryMatch && searchMatch);
                });
                groups.forEach(function (group) {
                    group.hidden = !Array.from(group.querySelectorAll('[data-wallet-category]')).some(function (card) { return !card.hidden; });
                });
            }

            filters.forEach(function (button) {
                button.addEventListener('click', function () {
                    category = button.dataset.walletFilter;
                    filters.forEach(function (item) { item.classList.toggle('active', item === button); });
                    applyWalletFilters();
                });
            });
            search?.addEventListener('input', applyWalletFilters);

            const amount = document.getElementById('cashoutAmount');
            const usdAmount = document.getElementById('cashoutAmountUsd');
            const coinAmount = document.getElementById('cashoutAmountCoins');
            const value = document.getElementById('cashoutValuePreview');
            const unitButtons = Array.from(document.querySelectorAll('[data-cashout-unit]'));
            const unitPanels = Array.from(document.querySelectorAll('[data-cashout-panel]'));
            const rate = {{ coins_per_usd() }};

            function syncAmount(source) {
                let coins = source === 'usd'
                    ? Math.round(Math.max(0, Number.parseFloat(usdAmount?.value) || 0) * rate)
                    : Math.round(Math.max(0, Number.parseFloat(coinAmount?.value) || 0));
                const usd = coins / rate;
                if (amount) amount.value = coins || '';
                if (source !== 'usd' && usdAmount) usdAmount.value = coins ? usd.toFixed(3).replace(/0+$/, '').replace(/\.$/, '') : '';
                if (source !== 'coins' && coinAmount) coinAmount.value = coins || '';
                if (value) value.textContent = '$' + usd.toFixed(2) + ' · ' + coins.toLocaleString() + ' coins';
            }

            usdAmount?.addEventListener('input', function () { syncAmount('usd'); });
            coinAmount?.addEventListener('input', function () { syncAmount('coins'); });
            unitButtons.forEach(function (button) {
                button.addEventListener('click', function () {
                    const unit = button.dataset.cashoutUnit;
                    unitButtons.forEach(function (item) { const selected = item === button; item.classList.toggle('active', selected); item.setAttribute('aria-pressed', selected ? 'true' : 'false'); });
                    unitPanels.forEach(function (panel) { panel.hidden = panel.dataset.cashoutPanel !== unit; });
                    if (usdAmount) usdAmount.required = unit === 'usd';
                    if (coinAmount) coinAmount.required = unit === 'coins';
                    document.getElementById(unit === 'usd' ? 'cashoutAmountUsd' : 'cashoutAmountCoins')?.focus();
                });
            });
        })();

        document.getElementById('cashoutModal')?.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const id = button.getAttribute('data-payment-id');
            const name = button.getAttribute('data-payment-name');
            const currency = button.getAttribute('data-payment-currency');
            const logo = button.getAttribute('data-payment-logo');

            document.getElementById('cashoutForm').action = '{{ url('/shop') }}/' + id;
            document.getElementById('cashoutTitle').textContent = name;
            document.getElementById('cashoutCurrency').textContent = currency;
            document.getElementById('cashoutLogo').innerHTML = logo
                ? '<img src="' + logo + '" alt="' + name + '">'
                : name.substring(0, 1);
            document.getElementById('cashoutFaceImage').value = '';
            document.getElementById('cashoutAmount').value = '';
            document.getElementById('cashoutAmountUsd').value = '';
            document.getElementById('cashoutAmountCoins').value = '';
            document.getElementById('cashoutAddress').value = '';
            document.getElementById('cashoutValuePreview').textContent = '$0.00 · 0 coins';
        });

        (function () {
            const modal = document.getElementById('cashoutModal');
            const faceModal = document.getElementById('cashoutFaceModal');
            const faceModalInstance = faceModal ? new bootstrap.Modal(faceModal) : null;
            const video = document.getElementById('cashoutFaceVideo');
            const canvas = document.getElementById('cashoutFaceCanvas');
            const input = document.getElementById('cashoutFaceImage');
            const placeholder = document.getElementById('cashoutFacePlaceholder');
            const start = document.getElementById('cashoutStartCamera');
            const capture = document.getElementById('cashoutCaptureFace');
            const retake = document.getElementById('cashoutRetakeFace');
            const finalSubmit = document.getElementById('cashoutFinalSubmit');
            const form = document.getElementById('cashoutForm');
            let stream = null;
            let verifiedSubmit = false;

            if (!modal || !video || !canvas) {
                return;
            }

            function setCaptured(captured) {
                video.classList.toggle('d-none', captured);
                canvas.classList.toggle('d-none', !captured);
                capture.disabled = captured || !stream;
                retake.disabled = !captured;
                finalSubmit.disabled = !captured;
            }

            function stopCamera() {
                if (stream) {
                    stream.getTracks().forEach((track) => track.stop());
                    stream = null;
                }
            }

            start?.addEventListener('click', async function () {
                try {
                    stream = await navigator.mediaDevices.getUserMedia({video: {facingMode: 'user'}, audio: false});
                    video.srcObject = stream;
                    placeholder?.classList.add('d-none');
                    capture.disabled = false;
                    setCaptured(false);
                } catch (error) {
                    alert('Camera permission is required before requesting cashout.');
                }
            });

            capture?.addEventListener('click', function () {
                const context = canvas.getContext('2d');
                context.drawImage(video, 0, 0, canvas.width, canvas.height);
                input.value = canvas.toDataURL('image/png', 0.92);
                setCaptured(true);
            });

            retake?.addEventListener('click', function () {
                input.value = '';
                setCaptured(false);
            });

            const faceRequired = form?.dataset.faceRequired !== '0';

            form?.addEventListener('submit', function (event) {
                // When the admin has turned face verification off, submit directly.
                if (!faceRequired || verifiedSubmit) {
                    return;
                }

                event.preventDefault();
                faceModalInstance?.show();
            });

            finalSubmit?.addEventListener('click', function () {
                if (!input.value) {
                    alert('Please capture your face before submitting cashout.');
                    return;
                }

                verifiedSubmit = true;
                stopCamera();
                form?.submit();
            });

            modal.addEventListener('hidden.bs.modal', function () {
                if (document.body.classList.contains('modal-open')) {
                    return;
                }
                stopCamera();
                input.value = '';
                verifiedSubmit = false;
                placeholder?.classList.remove('d-none');
                video.classList.remove('d-none');
                canvas.classList.add('d-none');
                capture.disabled = true;
                retake.disabled = true;
                finalSubmit.disabled = true;
            });

            faceModal?.addEventListener('hidden.bs.modal', function () {
                if (verifiedSubmit) {
                    return;
                }

                stopCamera();
                input.value = '';
                placeholder?.classList.remove('d-none');
                video.classList.remove('d-none');
                canvas.classList.add('d-none');
                capture.disabled = true;
                retake.disabled = true;
                finalSubmit.disabled = true;
            });
        })();
    </script>
@endpush
