@extends('admin.layouts.layout')
@section('title', 'گفتگوی بیاتو بات #' . $conversation->id)

@section('customhead')
<link rel="stylesheet" href="{{ url('theme/admin') }}/vendor/css/pages/app-chat.css" />
<style>
    .biata-admin-app-chat.app-chat {
        height: calc(100vh - 13.5rem);
    }
    .biata-admin-app-chat .app-chat-history {
        height: 100%;
    }
    .biata-admin-app-chat .chat-history-body {
        height: calc(100% - 4.25rem);
        overflow-y: auto !important;
    }
    .biata-admin-app-chat .app-chat-sidebar-right {
        position: static;
        opacity: 1;
        width: 22rem;
        flex: 0 0 22rem;
        height: 100%;
        box-shadow: none !important;
        border-inline-start: 1px solid rgba(75, 70, 92, .08);
    }
    .biata-admin-app-chat .app-chat-sidebar-right .sidebar-body {
        height: calc(100% - 3.75rem);
        overflow-y: auto;
        padding: 1.25rem;
    }
    .biata-admin-app-chat .chat-message {
        scroll-margin-top: 1.5rem;
    }
    .biata-admin-app-chat .chat-message.is-highlighted .chat-message-text {
        box-shadow: 0 0 0 3px rgba(245, 158, 11, .55) !important;
        outline: 2px solid #f59e0b;
        background-color: #fef3c7 !important;
        color: #1e293b !important;
    }
    .biata-analysis-list li,
    .biata-analysis-products li {
        display: flex;
        align-items: flex-start;
        gap: 10px;
        padding: .65rem .5rem;
        margin: 0 -.5rem;
        border-radius: .375rem;
        font-size: .875rem;
        line-height: 1.6;
        cursor: pointer;
        transition: background .15s ease;
    }
    .biata-analysis-list li:hover,
    .biata-analysis-products li:hover {
        background: rgba(105, 108, 255, .08);
    }
    .biata-analysis-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #696cff;
        margin-top: 7px;
        flex-shrink: 0;
    }
    .biata-analysis-product-row {
        display: flex;
        align-items: flex-start;
        gap: 8px;
        width: 100%;
        color: #4338ca;
    }
    .biata-analysis-product-row i { margin-top: 3px; flex-shrink: 0; }
    .biata-analysis-open-tab {
        margin-right: auto;
        color: #a8aaae;
        padding: 2px 4px;
    }
    .biata-analysis-open-tab:hover { color: #696cff; }
    .chat-message-text p { white-space: pre-wrap; word-break: break-word; }
    @media (max-width: 991.98px) {
        .biata-admin-app-chat.app-chat { height: auto; min-height: 70vh; }
        .biata-admin-app-chat .app-chat-sidebar-right {
            width: 100%;
            flex-basis: 100%;
            border-inline-start: 0;
            border-top: 1px solid rgba(75, 70, 92, .08);
        }
        .biata-admin-app-chat .chat-history-body {
            height: 55vh;
        }
        .biata-admin-app-chat .app-chat-sidebar-right .sidebar-body {
            height: auto;
            max-height: 50vh;
        }
    }
</style>
@endsection

@section('content')
@php
    $displayTitle = $conversation->displayTitle();
    $displaySub = $conversation->displaySubtitle();
    $userInitial = $conversation->user
        ? mb_substr($conversation->user->first_name ?: 'ک', 0, 1)
        : 'م';
@endphp

<div class="container-xxl flex-grow-1 container-p-y">

    <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
        <div>
            <a href="{{ route('admin.biata-bot.chats.index') }}" class="text-muted small">
                <i class="ti ti-arrow-right ti-xs"></i> بازگشت به گزارشات
            </a>
        </div>
        <form method="POST" action="{{ route('admin.biata-bot.chats.destroy', $conversation) }}"
              onsubmit="return confirm('این گفتگو برای همیشه حذف شود؟');">
            @csrf
            @method('DELETE')
            <button type="submit" class="btn btn-sm btn-outline-danger">
                <i class="ti ti-trash ti-xs me-1"></i>حذف گفتگو
            </button>
        </form>
    </div>

    <div class="app-chat biata-admin-app-chat card overflow-hidden">
        <div class="row g-0 h-100">

            {{-- Chat history --}}
            <div class="col app-chat-history bg-body">
                <div class="chat-history-wrapper h-100 d-flex flex-column">
                    <div class="chat-history-header border-bottom">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex overflow-hidden align-items-center">
                                <div class="flex-shrink-0 avatar avatar-online">
                                    <span class="avatar-initial rounded-circle bg-label-primary">{{ $userInitial }}</span>
                                </div>
                                <div class="chat-contact-info flex-grow-1 ms-2">
                                    <h6 class="m-0">{{ $displayTitle }}</h6>
                                    <small class="user-status text-muted">
                                        @if($displaySub)
                                            <span dir="ltr">{{ $displaySub }}</span>
                                        @else
                                            session#{{ $conversation->id }}
                                        @endif
                                        · {{ number_format($conversation->messages_count) }} پیام
                                        · {{ $conversation->shamsiLastMessage() }}
                                    </small>
                                </div>
                            </div>
                            <div class="d-flex align-items-center">
                                <span class="badge {{ $conversation->user_id ? 'bg-label-primary' : 'bg-label-secondary' }}">
                                    {{ $conversation->user_id ? 'کاربر' : 'مهمان' }}
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="chat-history-body bg-body flex-grow-1" id="biataAdminThread">
                        @if($conversation->messages->isEmpty())
                        <div class="text-center text-muted py-5">پیامی ثبت نشده است.</div>
                        @else
                        <ul class="list-unstyled chat-history mb-0">
                            @foreach($conversation->messages as $msg)
                            @php $isBot = $msg->role === 'assistant'; @endphp
                            <li class="chat-message {{ $isBot ? 'chat-message-right' : '' }}"
                                id="msg-{{ $msg->id }}"
                                data-msg-id="{{ $msg->id }}">
                                <div class="d-flex overflow-hidden">
                                    @if(!$isBot)
                                    <div class="user-avatar flex-shrink-0 me-3">
                                        <div class="avatar avatar-sm">
                                            <span class="avatar-initial rounded-circle bg-label-secondary">{{ $userInitial }}</span>
                                        </div>
                                    </div>
                                    @endif

                                    <div class="chat-message-wrapper flex-grow-1">
                                        <div class="chat-message-text">
                                            <p class="mb-0">{!! nl2br(e($msg->content)) !!}</p>
                                        </div>
                                        <div class="{{ $isBot ? 'text-end' : '' }} text-muted mt-1">
                                            @if($isBot)
                                            <i class="ti ti-checks ti-xs me-1 text-success"></i>
                                            @endif
                                            <small>{{ $msg->created_at->format('H:i') }} · {{ $isBot ? 'بیاتو بات' : 'کاربر' }}</small>
                                        </div>
                                    </div>

                                    @if($isBot)
                                    <div class="user-avatar flex-shrink-0 ms-3">
                                        <div class="avatar avatar-sm">
                                            <span class="avatar-initial rounded-circle bg-label-primary">
                                                <i class="ti ti-robot ti-xs"></i>
                                            </span>
                                        </div>
                                    </div>
                                    @endif
                                </div>
                            </li>
                            @endforeach
                        </ul>
                        @endif
                    </div>
                </div>
            </div>

            {{-- Analysis sidebar --}}
            <div class="col app-chat-sidebar-right app-sidebar overflow-hidden bg-white">
                <div class="sidebar-header d-flex flex-column justify-content-center px-4 pt-3 pb-2 border-bottom">
                    <div class="d-flex align-items-center gap-2">
                        <i class="ti ti-chart-dots text-primary"></i>
                        <h5 class="mb-0">تجزیه و تحلیل مکالمه</h5>
                    </div>
                </div>
                <div class="sidebar-body"
                     id="biataAnalysisCard"
                     data-url="{{ route('admin.biata-bot.chats.analyze', $conversation) }}">
                    <div id="biataAnalysisBody">
                        <div class="text-center text-muted py-4">
                            <div class="spinner-border spinner-border-sm text-primary mb-2" role="status"></div>
                            <div class="small">در حال تحلیل گفتگو...</div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
@endsection

@section('customjs')
<script>
(function () {
    var card = document.getElementById('biataAnalysisCard');
    var body = document.getElementById('biataAnalysisBody');
    var thread = document.getElementById('biataAdminThread');
    if (!card || !body) return;

    var highlightTimer = null;

    function esc(s) {
        return String(s).replace(/[&<>"']/g, function (c) {
            return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[c];
        });
    }

    function clearHighlights() {
        document.querySelectorAll('.chat-message.is-highlighted').forEach(function (el) {
            el.classList.remove('is-highlighted');
        });
    }

    function highlightMessages(ids) {
        clearHighlights();
        if (!ids || !ids.length) return;

        var first = null;
        ids.forEach(function (id) {
            var el = document.getElementById('msg-' + id);
            if (!el) return;
            el.classList.add('is-highlighted');
            if (!first) first = el;
        });

        if (first) {
            first.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }

        if (highlightTimer) clearTimeout(highlightTimer);
        highlightTimer = setTimeout(clearHighlights, 3500);
    }

    function idsAttr(ids) {
        return esc((ids || []).join(','));
    }

    function render(report) {
        var topics = (report && report.topics) || [];
        var products = (report && report.products) || [];

        var html = '';
        html += '<div class="mb-4">';
        html += '<h6 class="text-muted text-uppercase small mb-2"><i class="ti ti-list-details ti-xs me-1"></i>موضوعات اصلی</h6>';
        if (!topics.length) {
            html += '<p class="text-muted small mb-0">موضوع مشخصی استخراج نشد.</p>';
        } else {
            html += '<ul class="biata-analysis-list list-unstyled mb-0">';
            topics.forEach(function (t) {
                var title = typeof t === 'string' ? t : (t.title || '');
                var ids = (t && t.message_ids) ? t.message_ids : [];
                html += '<li class="biata-jump-item" data-msg-ids="' + idsAttr(ids) + '" title="رفتن به پیام مرتبط">';
                html += '<span class="biata-analysis-dot"></span><span>' + esc(title) + '</span>';
                html += '</li>';
            });
            html += '</ul>';
        }
        html += '</div><hr class="my-3"><div>';
        html += '<h6 class="text-muted text-uppercase small mb-2"><i class="ti ti-shopping-bag ti-xs me-1"></i>محصولات مورد سوال</h6>';
        if (!products.length) {
            html += '<p class="text-muted small mb-0">محصول مشخصی در پیام‌های کاربر پیدا نشد.</p>';
        } else {
            html += '<ul class="biata-analysis-products list-unstyled mb-0">';
            products.forEach(function (p) {
                var ids = p.message_ids || [];
                html += '<li class="biata-jump-item" data-msg-ids="' + idsAttr(ids) + '" title="رفتن به پیام مرتبط">';
                html += '<div class="biata-analysis-product-row">';
                html += '<i class="ti ti-message-2 ti-xs"></i><span>' + esc(p.title) + '</span>';
                if (p.url) {
                    html += '<a class="biata-analysis-open-tab" href="' + esc(p.url) + '" target="_blank" rel="noopener" title="باز کردن صفحه محصول" onclick="event.stopPropagation()">';
                    html += '<i class="ti ti-external-link ti-xs"></i></a>';
                }
                html += '</div></li>';
            });
            html += '</ul>';
        }
        html += '</div>';
        body.innerHTML = html;
    }

    body.addEventListener('click', function (e) {
        var item = e.target.closest('.biata-jump-item');
        if (!item) return;
        var raw = item.getAttribute('data-msg-ids') || '';
        var ids = raw.split(',').map(function (x) { return parseInt(x, 10); }).filter(Boolean);
        highlightMessages(ids);
    });

    // Scroll chat to bottom on load
    if (thread) {
        setTimeout(function () { thread.scrollTop = thread.scrollHeight; }, 50);
    }

    fetch(card.dataset.url, {
        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
        credentials: 'same-origin',
    })
    .then(function (r) { return r.json(); })
    .then(function (j) {
        if (j && j.ok && j.report) {
            render(j.report);
        } else {
            body.innerHTML = '<p class="text-danger small mb-0">خطا در دریافت تحلیل.</p>';
        }
    })
    .catch(function () {
        body.innerHTML = '<p class="text-danger small mb-0">ارتباط برای تحلیل برقرار نشد.</p>';
    });
})();
</script>
@endsection
