@extends('layouts.dashboard')

@section('title', 'My Profile')

@section('content')
    @php
        $user = auth()->user();
        $level = max(1, (int) floor($user->total_points / 1000) + 1);
        $levelProgress = min(100, (int) (($user->total_points % 1000) / 10));
        $balanceMode = $user->balanceDisplayMode();
        $totalEarnings = $balanceMode === 'usd'
            ? format_coins_as_usd($user->total_points)
            : number_format($user->total_points, 2) . ' coins';
        $thirtyDayEarnings = $balanceMode === 'usd'
            ? format_coins_as_usd($stats['earnings_30_days'])
            : number_format($stats['earnings_30_days'], 2) . ' coins';
        $emailVerified = ! is_null($user->email_verified_at);
        $faceVerification = $user->latestFaceVerification;
        $faceStatus = $faceVerification?->status ?? 'not_submitted';
        $faceStatusClass = match ($faceStatus) {
            'approved' => 'success',
            'rejected' => 'danger',
            'duplicate_review' => 'warning',
            'pending' => 'warning',
            default => '',
        };
        $faceStatusLabel = match ($faceStatus) {
            'approved' => 'Face verified',
            'rejected' => 'Rejected',
            'duplicate_review' => 'Duplicate review',
            'pending' => 'Pending review',
            default => 'Not submitted',
        };
    @endphp

    @if(session('success'))
        <div class="alert alert-success"><div class="alert-body">{{ session('success') }}</div></div>
    @endif
    @if(isset($errors) && $errors->any())
        <div class="alert alert-danger">
            <div class="alert-body">
                @foreach($errors->all() as $error)
                    <p class="mb-0">{{ $error }}</p>
                @endforeach
            </div>
        </div>
    @endif

    <section class="loot-profile-hero user-page-card mb-2">
        <div class="loot-profile-title">
            <h1><i data-feather="user"></i> Account Information</h1>
            <button class="btn btn-loot loot-edit-button" type="button" data-bs-toggle="modal" data-bs-target="#profileSettingsModal">
                <i data-feather="settings" class="me-50"></i>Settings
            </button>
        </div>

        <div class="loot-profile-identity">
            <div class="loot-profile-avatar-block">
                <div class="loot-profile-avatar">
                    <img src="{{ $user->avatar() }}" alt="{{ $user->username }}">
                    <span class="loot-online-dot" aria-label="Online"></span>
                </div>
                <span class="loot-profile-level">Level {{ $level }}</span>
                <form action="{{ route('user.settings.update') }}" method="POST" class="loot-private-form">
                    @csrf
                    <input type="hidden" name="is_profile_private" value="{{ $user->is_profile_private ? 0 : 1 }}">
                    <button class="loot-private-toggle" type="submit" aria-pressed="{{ $user->is_profile_private ? 'true' : 'false' }}">
                        <i data-feather="eye-off"></i>
                        <span>Private</span>
                        <span class="loot-help-dot">?</span>
                        <span class="loot-mini-switch {{ $user->is_profile_private ? 'active' : '' }}"><span></span></span>
                    </button>
                </form>
            </div>

            <div class="loot-profile-main">
                <p class="loot-muted mb-50">Joined {{ $user->created_at->diffForHumans() }}</p>
                <h2>{{ $user->username }}</h2>
                <div class="loot-profile-badges">
                    <span class="loot-info-pill {{ $emailVerified ? 'success' : 'warning' }}">
                        <i data-feather="mail"></i>{{ $user->email }}
                        <i data-feather="{{ $emailVerified ? 'check-circle' : 'alert-circle' }}"></i>
                    </span>
                    <span class="loot-info-pill id-pill">
                        <i data-feather="hash"></i>User ID: <strong>#{{ $user->id }}</strong>
                    </span>
                </div>
                <div class="loot-level-meter">
                    <div class="d-flex justify-content-between">
                        <span>Level {{ $level }}</span>
                        <span>{{ 1000 - ((int) $user->total_points % 1000) }} coins to next level</span>
                    </div>
                    <div class="loot-progress mt-1" style="--value: {{ $levelProgress }}%"><span></span></div>
                </div>
            </div>
        </div>
    </section>

    <section class="user-page-card loot-face-verify mb-2">
        <div class="loot-shelf-head">
            <div>
                <h3 class="loot-section-title mb-0"><i data-feather="camera"></i> Face Verification</h3>
                <p class="loot-muted mb-0">Capture a clear selfie for account review. Exact repeated image submissions are flagged for admin review.</p>
            </div>
            <span class="loot-status {{ $faceStatusClass }}">{{ $faceStatusLabel }}</span>
        </div>

        @if($faceVerification)
            <div class="loot-face-status mb-1">
                <span>Last submitted {{ $faceVerification->created_at->diffForHumans() }}</span>
                @if($faceVerification->admin_note)
                    <span>{{ $faceVerification->admin_note }}</span>
                @endif
            </div>
        @endif

        <form method="POST" action="{{ route('user.face-verification.store') }}" id="faceVerificationForm">
            @csrf
            <input type="hidden" name="face_image" id="faceImageInput">
            <div class="loot-face-capture-grid">
                <div class="loot-face-camera">
                    <video id="faceVideo" autoplay playsinline muted></video>
                    <canvas id="faceCanvas" class="d-none" width="720" height="540"></canvas>
                    <div class="loot-face-placeholder" id="facePlaceholder">
                        <i data-feather="camera"></i>
                        <strong>Camera preview</strong>
                        <span>Use a well-lit face photo. Do not upload another person's image.</span>
                    </div>
                </div>
                <div class="loot-face-actions">
                    <button class="btn btn-outline-light" type="button" id="startFaceCamera">
                        <i data-feather="video"></i>Start camera
                    </button>
                    <button class="btn btn-outline-light" type="button" id="captureFace" disabled>
                        <i data-feather="camera"></i>Capture
                    </button>
                    <button class="btn btn-outline-light" type="button" id="retakeFace" disabled>
                        <i data-feather="refresh-cw"></i>Retake
                    </button>
                    <button class="btn btn-loot" type="submit" id="submitFace" disabled>
                        Submit verification
                    </button>
                    <p class="loot-muted mb-0">This capture is used for account verification review. It is not used for biometric face recognition matching in this build.</p>
                </div>
            </div>
        </form>
    </section>

    @if(site_bool('two_factor_site_enabled', false))
        @php
            $twoFaMethod = $user->two_factor_method;
            $twoFaActive = $user->two_factor_enabled && $user->two_factor_confirmed_at;
            $totpSetup = session('totp_setup');
        @endphp
        <section class="user-page-card mb-2">
            <div class="d-flex justify-content-between align-items-center gap-1 mb-1">
                <h3 class="loot-section-title mb-0"><i data-feather="shield" class="me-50"></i>Two-factor authentication</h3>
                <span class="loot-status {{ $twoFaActive ? 'success' : 'warning' }}">{{ $twoFaActive ? 'Enabled ('.$twoFaMethod.')' : 'Not enabled' }}</span>
            </div>
            <p class="loot-muted">Add a second step at login using an emailed code or an authenticator app (Google Authenticator, Authy).</p>

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

            @if($twoFaActive)
                <form method="POST" action="{{ route('user.2fa.disable') }}" onsubmit="return confirm('Turn off two-factor authentication?')">
                    @csrf
                    <button class="btn btn-outline-danger"><i data-feather="shield-off" class="me-50"></i>Disable two-factor</button>
                </form>
            @elseif($totpSetup)
                <div class="alert alert-info"><div class="alert-body">
                    <strong>Scan or enter this key in your authenticator app, then confirm a code below.</strong>
                    <div class="mt-1">Secret key: <code style="font-size:15px; letter-spacing:1px;">{{ $totpSetup['secret'] }}</code></div>
                    <div class="mt-1" style="word-break:break-all;"><small class="loot-muted">Setup link: {{ $totpSetup['uri'] }}</small></div>
                </div></div>
                <form method="POST" action="{{ route('user.2fa.totp.confirm') }}" class="d-flex gap-1 flex-wrap align-items-end">
                    @csrf
                    <div>
                        <label class="form-label">Enter the 6-digit code from your app</label>
                        <input type="text" name="code" class="form-control text-center" maxlength="6" placeholder="000000" style="letter-spacing:4px; max-width:180px;" required>
                    </div>
                    <button class="btn btn-loot">Confirm &amp; enable</button>
                </form>
            @else
                <div class="d-flex flex-wrap gap-1">
                    <form method="POST" action="{{ route('user.2fa.email') }}">
                        @csrf
                        <button class="btn btn-outline-light"><i data-feather="mail" class="me-50"></i>Enable email codes</button>
                    </form>
                    <form method="POST" action="{{ route('user.2fa.totp.setup') }}">
                        @csrf
                        <button class="btn btn-outline-light"><i data-feather="smartphone" class="me-50"></i>Set up authenticator app</button>
                    </form>
                </div>
            @endif
        </section>
    @endif

    <div class="modal fade" id="profileSettingsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl">
            <div class="modal-content loot-profile-settings-modal">
                <div class="modal-header">
                    <div class="d-flex align-items-center gap-1">
                        <div class="loot-profile-avatar small">
                            <img src="{{ $user->avatar() }}" alt="{{ $user->username }}">
                        </div>
                        <div>
                            <h4 class="modal-title loot-section-title mb-0">{{ $user->username }}</h4>
                            <p class="loot-muted mb-0">Account settings</p>
                        </div>
                    </div>
                    <button type="button" class="btn-close loot-modal-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" action="{{ route('user.settings.update') }}" enctype="multipart/form-data">
                    @csrf
                    <div class="modal-body">
                        <div class="loot-profile-settings-grid">
                            <section class="loot-profile-settings-card">
                                <h3>Information</h3>
                                <div class="loot-settings-row"><span>User ID</span><strong>#{{ $user->id }}</strong></div>
                                <div class="loot-settings-row"><span>Email</span><strong>{{ $user->email }}</strong></div>
                                <div class="loot-settings-row"><span>Referral earnings</span><strong>{{ number_format($stats['referral_earnings']) }} coins</strong></div>
                                <div class="loot-settings-row"><span>Date joined</span><strong>{{ $user->created_at->format('M d, Y') }}</strong></div>
                                <a class="btn btn-outline-light w-100 mt-1" href="{{ route('logout') }}"
                                   onclick="event.preventDefault(); document.getElementById('logout-form-profile').submit();">Logout</a>
                            </section>

                            <section class="loot-profile-settings-card">
                                <h3>Settings</h3>
                                <label class="form-label">Avatar</label>
                                <input type="file" class="form-control mb-1" accept="image/*" name="image">

                                <label class="form-label">New password</label>
                                <input type="password" class="form-control mb-1" name="password" placeholder="Leave blank to keep current password">

                                <label class="loot-switch-card" for="profile-private-switch">
                                    <div>
                                        <strong>Public profile</strong>
                                        <span>Show your username and avatar in activity popups.</span>
                                    </div>
                                    <input type="hidden" name="is_profile_private" value="1">
                                    <input class="form-check-input" type="checkbox" id="profile-private-switch"
                                           name="is_profile_private" value="0" {{ $user->is_profile_private ? '' : 'checked' }}>
                                </label>

                                <label class="loot-switch-card" for="balance-display-switch">
                                    <div>
                                        <strong>Show USD balance</strong>
                                        <span>1,000 coins equals $1.00 across your dashboard.</span>
                                    </div>
                                    <input type="hidden" name="balance_display" value="coins">
                                    <input class="form-check-input" type="checkbox" id="balance-display-switch"
                                           name="balance_display" value="usd" {{ $balanceMode === 'usd' ? 'checked' : '' }}>
                                </label>
                            </section>
                        </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">Save changes</button>
                    </div>
                </form>
                <form id="logout-form-profile" action="{{ route('logout') }}" method="POST" class="d-none">@csrf</form>
            </div>
        </div>
    </div>

    <section class="user-page-card loot-profile-stats mb-2">
        <h3 class="loot-section-title"><i data-feather="bar-chart-2"></i> Stats</h3>
        <div class="loot-profile-stat-grid">
            <div class="loot-profile-stat-card">
                <span class="loot-stat-icon"><i data-feather="check-circle"></i></span>
                <strong>{{ number_format($stats['completed_offers']) }}</strong>
                <p>Completed Offers</p>
            </div>
            <div class="loot-profile-stat-card">
                <span class="loot-stat-icon"><i data-feather="users"></i></span>
                <strong>{{ number_format($stats['users_referred']) }}</strong>
                <p>Users Referred</p>
            </div>
            <div class="loot-profile-stat-card">
                <span class="loot-stat-icon"><i data-feather="credit-card"></i></span>
                <strong>{{ $totalEarnings }}</strong>
                <p>Total Earning</p>
            </div>
            <div class="loot-profile-stat-card">
                <span class="loot-stat-icon"><i data-feather="clock"></i></span>
                <strong>{{ $thirtyDayEarnings }}</strong>
                <p>Earnings last 30 days</p>
            </div>
        </div>
    </section>

    <section class="user-page-card loot-profile-activity">
        <ul class="nav loot-profile-tabs" role="tablist">
            <li class="nav-item">
                <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#earnings" type="button">
                    <i data-feather="dollar-sign"></i>Earnings <span>{{ $stats['recent_leads']->count() }}</span>
                </button>
            </li>
            <li class="nav-item">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#withdrawals" type="button">
                    <i data-feather="corner-up-right"></i>Withdrawals
                </button>
            </li>
            <li class="nav-item">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#pending" type="button">
                    <i data-feather="hourglass"></i>Pending <span>{{ $stats['pending_withdrawals']->count() }}</span>
                </button>
            </li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane fade show active" id="earnings">
                <div class="table-responsive">
                    <table class="table loot-profile-table mb-0">
                        <thead><tr><th>Name</th><th>Time</th><th>Points</th></tr></thead>
                        <tbody>
                        @forelse($stats['recent_leads'] as $lead)
                            <tr>
                                <td>{{ $lead->offer_name ?? $lead->offer_id ?? 'Offer completed' }}</td>
                                <td>{{ $lead->created_at->diffForHumans() }}</td>
                                <td>{{ number_format((float) $lead->credited_points) }}</td>
                            </tr>
                        @empty
                            <tr><td colspan="3" class="text-center py-4">No activity found</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="tab-pane fade" id="withdrawals">
                <div class="table-responsive">
                    <table class="table loot-profile-table mb-0">
                        <thead><tr><th>Method</th><th>Amount</th><th>Status</th><th>Time</th></tr></thead>
                        <tbody>
                        @forelse($stats['withdrawals'] as $withdrawal)
                            <tr>
                                <td>{{ $withdrawal->method }}</td>
                                <td>{{ format_coins_as_usd($withdrawal->amount) }} <small class="loot-muted">· {{ number_format($withdrawal->amount) }} coins</small></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="4" class="text-center py-4">No withdrawals yet</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="tab-pane fade" id="pending">
                <div class="table-responsive">
                    <table class="table loot-profile-table mb-0">
                        <thead><tr><th>Method</th><th>Amount</th><th>Requested</th></tr></thead>
                        <tbody>
                        @forelse($stats['pending_withdrawals'] as $withdrawal)
                            <tr>
                                <td>{{ $withdrawal->method }}</td>
                                <td>{{ number_format((float) $withdrawal->amount, 2) }}</td>
                                <td>{{ $withdrawal->created_at->diffForHumans() }}</td>
                            </tr>
                        @empty
                            <tr><td colspan="3" class="text-center py-4">No pending requests</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>
@endsection

@push('scripts')
    <script>
        (function () {
            const video = document.getElementById('faceVideo');
            const canvas = document.getElementById('faceCanvas');
            const input = document.getElementById('faceImageInput');
            const placeholder = document.getElementById('facePlaceholder');
            const start = document.getElementById('startFaceCamera');
            const capture = document.getElementById('captureFace');
            const retake = document.getElementById('retakeFace');
            const submit = document.getElementById('submitFace');
            let stream = null;

            if (!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;
                submit.disabled = !captured;
            }

            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 for face verification.');
                }
            });

            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);
            });
        })();
    </script>
@endpush
