@extends('layouts.dashboard')

@section('title', 'Support')

@section('content')
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-1 mb-2">
        <div><h1 class="loot-section-title mb-25">Support</h1><p class="loot-muted mb-0">Create a ticket for offer tracking, cashout, account, or bug issues.</p></div>
    </div>

    @if(site_bool('ai_support_bot_enabled', false))
        <section class="user-page-card mb-2" id="support-bot">
            <div class="d-flex justify-content-between align-items-center mb-1">
                <div>
                    <h3 class="loot-section-title mb-25"><i data-feather="message-square" class="me-50"></i>Ask our assistant first</h3>
                    <p class="loot-muted mb-0">Instant answers to common questions. If it can't help, it will point you to a ticket.</p>
                </div>
            </div>
            <div id="botMessages" class="mb-1" style="max-height: 260px; overflow-y: auto; display: none;" aria-live="polite" aria-label="Assistant conversation"></div>
            <form id="botForm" class="d-flex gap-1">
                <label for="botInput" class="visually-hidden">Ask the support assistant</label>
                <input id="botInput" class="form-control" placeholder="e.g. How long do withdrawals take?" maxlength="2000" autocomplete="off" required>
                <button class="btn btn-loot" type="submit" id="botSend">Ask</button>
            </form>
        </section>

        <style>
            .bot-msg { padding: .5rem .85rem; border-radius: .75rem; margin-bottom: .5rem; max-width: 85%; font-size: .9rem; }
            .bot-msg.user { background: rgba(40,199,111,.15); margin-left: auto; }
            .bot-msg.assistant { background: rgba(255,255,255,.06); }
            .bot-msg.assistant.error { background: rgba(234,84,85,.12); }
        </style>

        <script>
            (function () {
                var form = document.getElementById('botForm');
                var input = document.getElementById('botInput');
                var send = document.getElementById('botSend');
                var box = document.getElementById('botMessages');
                var history = [];

                function esc(s) { var d = document.createElement('div'); d.textContent = s; return d.innerHTML; }

                function add(role, text, opts) {
                    opts = opts || {};
                    box.style.display = 'block';
                    var div = document.createElement('div');
                    div.className = 'bot-msg ' + role + (opts.error ? ' error' : '');
                    div.innerHTML = esc(text) + (opts.ticket
                        ? '<div class="mt-50"><a class="btn btn-sm btn-loot" href="#support-ticket-form" onclick="document.querySelector(\'[name=subject]\').focus()">Open a ticket</a></div>'
                        : '');
                    box.appendChild(div);
                    box.scrollTop = box.scrollHeight;
                }

                form.addEventListener('submit', function (e) {
                    e.preventDefault();
                    var q = input.value.trim();
                    if (!q) return;
                    add('user', q);
                    history.push({ role: 'user', content: q });
                    input.value = '';
                    send.disabled = true;

                    fetch('{{ route('user.support.bot') }}', {
                        method: 'POST',
                        credentials: 'same-origin',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                        },
                        body: JSON.stringify({ messages: history.slice(-10) })
                    })
                        .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, j: j }; }); })
                        .then(function (res) {
                            if (res.ok && res.j.reply) {
                                history.push({ role: 'assistant', content: res.j.reply });
                                add('assistant', res.j.reply, { ticket: res.j.suggest_ticket });
                            } else {
                                add('assistant', (res.j && res.j.error) || 'Something went wrong.', { error: true, ticket: true });
                            }
                        })
                        .catch(function () {
                            add('assistant', 'Network error — please try again or open a ticket.', { error: true, ticket: true });
                        })
                        .finally(function () { send.disabled = false; input.focus(); });
                });
            })();
        </script>
    @endif

    <div class="loot-command-grid">
        <section class="user-page-card">
            <h3 class="loot-section-title mb-2">My tickets</h3>
            <div class="loot-leader-list">
                @forelse($tickets as $ticket)
                    <a class="loot-leader-row ticket-row" href="{{ route('user.tickets.show', $ticket) }}">
                        <span class="loot-leader-rank">#{{ $ticket->id }}</span>
                        <span class="loot-brand-mark"><i data-feather="message-circle"></i></span>
                        <span class="loot-leader-name"><strong>{{ $ticket->subject }}</strong><small>{{ ucfirst($ticket->category) }} / {{ $ticket->last_reply_at?->diffForHumans() }}</small></span>
                        <span class="loot-status {{ $ticket->status === 'closed' ? '' : 'success' }}">{{ ucfirst($ticket->status) }}</span>
                    </a>
                @empty
                    <p class="loot-muted mb-0">No support tickets yet.</p>
                @endforelse
            </div>
            <div class="mt-2">{{ $tickets->links() }}</div>
        </section>

        <section class="user-page-card" id="support-ticket-form">
            <h3 class="loot-section-title mb-2">New ticket</h3>
            <form method="POST" action="{{ route('user.tickets.store') }}">
                @csrf
                @if($errors->any())
                    <div class="alert alert-danger" role="alert">
                        <div class="alert-body">Please review the highlighted ticket fields.</div>
                    </div>
                @endif
                <div class="mb-1"><label class="form-label" for="ticketSubject">Subject</label><input id="ticketSubject" name="subject" value="{{ old('subject') }}" @class(['form-control', 'is-invalid' => $errors->has('subject')]) required maxlength="140" aria-describedby="ticketSubjectError">@error('subject')<div id="ticketSubjectError" class="invalid-feedback">{{ $message }}</div>@enderror</div>
                <div class="row">
                    <div class="col-md-6 mb-1"><label class="form-label" for="ticketCategory">Category</label><select id="ticketCategory" name="category" class="form-select"><option value="offerwall" @selected(old('category') === 'offerwall')>Offerwall</option><option value="cashout" @selected(old('category') === 'cashout')>Cashout</option><option value="account" @selected(old('category') === 'account')>Account</option><option value="bug" @selected(old('category') === 'bug')>Bug</option><option value="general" @selected(old('category') === 'general')>General</option></select></div>
                    <div class="col-md-6 mb-1"><label class="form-label" for="ticketPriority">Priority</label><select id="ticketPriority" name="priority" class="form-select"><option value="normal" @selected(old('priority', 'normal') === 'normal')>Normal</option><option value="low" @selected(old('priority') === 'low')>Low</option><option value="high" @selected(old('priority') === 'high')>High</option></select></div>
                </div>
                <div class="mb-1"><label class="form-label" for="ticketMessage">Message</label><textarea id="ticketMessage" name="message" @class(['form-control', 'is-invalid' => $errors->has('message')]) rows="5" required maxlength="3000" aria-describedby="ticketMessageHelp ticketMessageError">{{ old('message') }}</textarea><small id="ticketMessageHelp" class="loot-muted">Include the offer or cashout name and when the issue happened.</small>@error('message')<div id="ticketMessageError" class="invalid-feedback">{{ $message }}</div>@enderror</div>
                <button class="btn btn-loot w-100" type="submit">Submit ticket</button>
            </form>
        </section>
    </div>
@endsection
