@extends('site.layouts.site-layout')
@section('title', 'گردونه شانس')

@php
    $prizeCount = max(1, count($prizes));
    $spanPct = 100 / $prizeCount;
    $gradientStops = [];
    foreach ($prizes as $i => $prize) {
        $startPct = $i * $spanPct;
        $endPct = ($i + 1) * $spanPct;
        $gradientStops[] = $prize['color'] . ' ' . $startPct . '% ' . $endPct . '%';
    }
@endphp

@section('content')

<div class="bread-crumb pt-3">
    <div class="container-fluid">
        <div class="content-box">
            <div class="container-fluid">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item"><a href="{{ route('home') }}" class="font-14 text-muted">خانه</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('panel.index') }}" class="font-14 text-muted">پنل کاربری</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('panel.club.index') }}" class="font-14 text-muted">باشگاه مشتریان</a></li>
                        <li class="breadcrumb-item active main-color-one-color font-14" aria-current="page">گردونه شانس</li>
                    </ol>
                </nav>
            </div>
        </div>
    </div>
</div>

<div class="content">
    <div class="container-fluid">

        <div class="custom-filter d-lg-none d-block">
            <button class="btn btn-filter-float border-0 main-color-two-bg shadow-box px-4 rounded-3 position-fixed"
                style="z-index:999;bottom:80px;" type="button"
                data-bs-toggle="offcanvas" data-bs-target="#panelSideCanvas" aria-controls="panelSideCanvas">
                <i class="bi bi-list font-20 fw-bold text-white"></i>
                <span class="d-block font-14 text-white">منو</span>
            </button>
            <div class="offcanvas offcanvas-start" tabindex="-1" id="panelSideCanvas">
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title">منو پنل</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                <div class="offcanvas-body">
                    <div class="panel-side">
                        <div class="content-box pb-0">
                            <div class="container-fluid">
                                @include('panel._sidebar')
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="dashboard-panel">
            <div class="row gy-3">

                <div class="col-lg-3 d-lg-block d-none">
                    <div class="panel-side">
                        <div class="content-box pb-0">
                            <div class="container-fluid">
                                @include('panel._sidebar')
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-9">
                    <div class="content-box">
                        <div class="container-fluid">
                            <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-4">
                                <div>
                                    <h5 class="font-18 mb-1">گردونه شانس</h5>
                                    <p class="text-muted font-13 mb-0">شانس‌های باقی‌مانده: <strong id="clubSpinsLeft" class="main-color-one-color">{{ $account->available_spins }}</strong></p>
                                </div>
                                <a href="{{ route('panel.club.index') }}" class="btn btn-sm btn-outline-secondary rounded-3 font-12">
                                    <i class="bi bi-arrow-right me-1"></i>بازگشت به باشگاه
                                </a>
                            </div>

                            <div class="club-wheel-wrap">
                                <div class="club-wheel-pointer"></div>
                                <div class="club-wheel" id="clubWheel"
                                     style="--club-wheel-bg: {{ implode(', ', $gradientStops) }};">
                                    @foreach($prizes as $prize)
                                        <span class="club-wheel-label" style="--center: {{ $prize['angle_center'] }};">
                                            {{ $prize['label'] }}
                                        </span>
                                    @endforeach
                                </div>
                                <button type="button" class="club-wheel-btn" id="clubSpinBtn"
                                        {{ $account->available_spins < 1 ? 'disabled' : '' }}>
                                    بچرخان
                                </button>
                            </div>

                            <p class="text-muted font-12 text-center mt-4 mb-0">
                                جوایز نقدی مستقیماً به کیف پول واریز می‌شوند.
                            </p>
                        </div>
                    </div>
                </div>

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

<div class="modal fade" id="clubResultModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4 border-0">
            <div class="modal-body text-center p-4">
                <div class="club-result-icon mb-3" id="clubResultIcon">
                    <i class="bi bi-gift-fill"></i>
                </div>
                <h5 class="mb-2" id="clubResultTitle">تبریک!</h5>
                <p class="text-muted font-14 mb-3" id="clubResultMessage"></p>
                <button type="button" class="btn main-color-one-bg text-white rounded-3 px-4" data-bs-dismiss="modal">باشه</button>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
(function () {
    var wheel = document.getElementById('clubWheel');
    var btn = document.getElementById('clubSpinBtn');
    var spinsEl = document.getElementById('clubSpinsLeft');
    var spinning = false;
    var currentRotation = 0;
    var prizes = @json($prizesForJs);
    var spinUrl = @json(route('panel.club.spin'));
    var csrf = @json(csrf_token());

    if (!wheel || !btn) return;

    btn.addEventListener('click', function () {
        if (spinning || btn.disabled) return;
        spinning = true;
        btn.disabled = true;

        fetch(spinUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': csrf
            },
            body: JSON.stringify({})
        })
        .then(function (r) { return r.json().then(function (data) { return { ok: r.ok, data: data }; }); })
        .then(function (res) {
            if (!res.ok || !res.data.success) {
                spinning = false;
                btn.disabled = parseInt(spinsEl.textContent, 10) < 1;
                alert((res.data && res.data.message) || 'خطا در چرخاندن گردونه');
                return;
            }

            var index = parseInt(res.data.result.index, 10);
            var prize = prizes[index];
            if (!prize) {
                spinning = false;
                btn.disabled = parseInt(spinsEl.textContent, 10) < 1;
                alert('نتیجه گردونه نامعتبر بود.');
                return;
            }

            // Pointer is fixed at top (0deg). Rotate wheel so prize center lands under pointer.
            var targetCenter = Number(prize.angle_center) || 0;
            var extraTurns = 5 * 360;
            var base = Math.ceil(currentRotation / 360) * 360;
            var finalRotation = base + extraTurns + (360 - targetCenter);

            currentRotation = finalRotation;
            wheel.style.transition = 'transform 4.5s cubic-bezier(0.15, 0.85, 0.25, 1)';
            wheel.style.transform = 'rotate(' + finalRotation + 'deg)';

            setTimeout(function () {
                spinning = false;
                spinsEl.textContent = res.data.result.spins_left;
                btn.disabled = res.data.result.spins_left < 1;

                document.getElementById('clubResultTitle').textContent =
                    res.data.result.amount > 0 ? 'تبریک!' : 'اوه!';
                document.getElementById('clubResultMessage').textContent = res.data.message;
                document.getElementById('clubResultIcon').innerHTML =
                    res.data.result.amount > 0
                        ? '<i class="bi bi-gift-fill"></i>'
                        : '<i class="bi bi-emoji-neutral"></i>';

                var modal = new bootstrap.Modal(document.getElementById('clubResultModal'));
                modal.show();
            }, 4700);
        })
        .catch(function () {
            spinning = false;
            btn.disabled = parseInt(spinsEl.textContent, 10) < 1;
            alert('خطا در ارتباط با سرور');
        });
    });
})();
</script>
@endsection
