
<div id="biataBot" class="biata-bot"
     data-endpoint="<?php echo e(route('biata-bot.chat')); ?>"
     data-history-endpoint="<?php echo e(route('biata-bot.history')); ?>"
     data-csrf="<?php echo e(csrf_token()); ?>">

    <div class="biata-bot-preview" id="biataBotPreview">
        <button type="button" class="biata-bot-preview-close" id="biataBotPreviewClose" aria-label="بستن پیام">
            <i class="bi bi-x"></i>
        </button>
        <?php echo e($biataBotWelcome); ?>

    </div>

    <button type="button" class="biata-bot-toggle" id="biataBotToggle" aria-label="باز کردن چت">
        <i class="bi bi-chat-dots-fill text-white"></i>
        <span class="biata-bot-toggle-dot"></span>
    </button>

    <div class="biata-bot-panel" id="biataBotPanel" role="dialog" aria-label="چت با <?php echo e($biataBotName); ?>">

        <div class="biata-bot-header">
            <div class="d-flex align-items-center gap-2">
                <div class="biata-bot-avatar">
                    <i class="bi bi-robot text-white-50"></i>
                </div>
                <div>
                    <div class="biata-bot-title"><?php echo e($biataBotName); ?></div>
                    <div class="biata-bot-status">
                        <span class="biata-bot-status-dot"></span>
                        آنلاین
                    </div>
                </div>
            </div>
            <button type="button" class="biata-bot-close" id="biataBotClose" aria-label="بستن">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>

        <div class="biata-bot-body" id="biataBotBody">
            <div class="biata-bot-msg assistant">
                <div class="biata-bot-bubble"><?php echo e($biataBotWelcome); ?></div>
            </div>
        </div>

        <form class="biata-bot-input" id="biataBotForm" autocomplete="off">
            <input type="text" id="biataBotInput" placeholder="پیام خودت رو بنویس..." maxlength="2000" required>
            <button type="submit" id="biataBotSend" aria-label="ارسال">
                <i class="bi bi-send-fill text-white"></i>
            </button>
        </form>

    </div>
</div>

<script>
(function () {
    var root         = document.getElementById('biataBot');
    if (!root) return;
    var endpoint     = root.dataset.endpoint;
    var historyUrl   = root.dataset.historyEndpoint;
    var csrf         = root.dataset.csrf;
    var toggleBtn    = document.getElementById('biataBotToggle');
    var closeBtn     = document.getElementById('biataBotClose');
    var panel        = document.getElementById('biataBotPanel');
    var body         = document.getElementById('biataBotBody');
    var form         = document.getElementById('biataBotForm');
    var input        = document.getElementById('biataBotInput');
    var sendBtn      = document.getElementById('biataBotSend');
    var preview      = document.getElementById('biataBotPreview');
    var previewClose = document.getElementById('biataBotPreviewClose');
    var PREVIEW_KEY  = 'biataBotPreviewDismissed';

    var history = []; // [{role, content}, ...]
    var sending = false;
    var historyLoaded = false;

    // On mobile the floating toggle is hidden — park the welcome bubble above the footer chat icon.
    function syncPreviewAnchor() {
        if (!preview) return;
        var mfChat = document.querySelector('.mobile-footer .mf-item-chat');
        var mobile = window.matchMedia('(max-width: 991.98px)').matches;
        if (mobile && mfChat) {
            if (preview.parentElement !== mfChat) mfChat.appendChild(preview);
        } else if (preview.parentElement !== root) {
            root.insertBefore(preview, toggleBtn);
        }
    }
    syncPreviewAnchor();
    window.addEventListener('resize', syncPreviewAnchor);

    // Show preview bubble unless dismissed previously this session.
    if (preview) {
        if (sessionStorage.getItem(PREVIEW_KEY) === '1') {
            preview.classList.add('is-hidden');
        } else {
            setTimeout(function () { preview.classList.add('is-visible'); }, 700);
        }
    }

    function dismissPreview(persist) {
        if (!preview) return;
        preview.classList.remove('is-visible');
        preview.classList.add('is-hidden');
        if (persist) sessionStorage.setItem(PREVIEW_KEY, '1');
    }

    function open()  {
        root.classList.add('is-open');
        input.focus();
        dismissPreview(true);
        loadHistory();
    }
    function close() { root.classList.remove('is-open'); }

    toggleBtn.addEventListener('click', function () {
        root.classList.contains('is-open') ? close() : open();
    });
    closeBtn.addEventListener('click', close);
    if (previewClose) {
        previewClose.addEventListener('click', function (e) {
            e.stopPropagation();
            dismissPreview(true);
        });
    }
    if (preview) {
        preview.addEventListener('click', function (e) {
            if (e.target === previewClose || (previewClose && previewClose.contains(e.target))) return;
            open();
        });
    }

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

    function faToEnDigits(s) {
        return String(s).replace(/[۰-۹٠-٩]/g, function (d) {
            var map = {
                '۰':'0','۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9',
                '٠':'0','١':'1','٢':'2','٣':'3','٤':'4','٥':'5','٦':'6','٧':'7','٨':'8','٩':'9'
            };
            return map[d] || d;
        });
    }

    function formatBotMarkdown(text) {
        var links = [];
        var out = String(text).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, function (_, label, url) {
            var i = links.length;
            links.push({ label: label, url: faToEnDigits(url.trim()) });
            return '\u0000L' + i + '\u0000';
        });

        out = escapeHtml(out);
        out = out.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
        out = out.replace(/\u0000L(\d+)\u0000/g, function (_, i) {
            var link = links[Number(i)];
            if (!link) return '';
            return '<a class="biata-bot-link" href="' + escapeHtml(link.url) + '" target="_blank" rel="noopener noreferrer">'
                + escapeHtml(link.label) + '</a>';
        });

        return out.replace(/\n/g, '<br>');
    }

    function appendMessage(role, text) {
        var wrap = document.createElement('div');
        wrap.className = 'biata-bot-msg ' + role;
        var bubble = document.createElement('div');
        bubble.className = 'biata-bot-bubble';
        if (role === 'assistant') {
            bubble.innerHTML = formatBotMarkdown(text);
        } else {
            bubble.innerHTML = escapeHtml(text).replace(/\n/g, '<br>');
        }
        wrap.appendChild(bubble);
        body.appendChild(wrap);
        body.scrollTop = body.scrollHeight;
        return bubble;
    }

    function appendTyping() {
        var wrap = document.createElement('div');
        wrap.className = 'biata-bot-msg assistant biata-bot-typing-wrap';
        wrap.innerHTML = '<div class="biata-bot-bubble biata-bot-typing">'
            + '<span></span><span></span><span></span></div>';
        body.appendChild(wrap);
        body.scrollTop = body.scrollHeight;
        return wrap;
    }

    function loadHistory() {
        if (historyLoaded || !historyUrl) return;
        historyLoaded = true;

        fetch(historyUrl, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
            credentials: 'same-origin',
        })
        .then(function (res) { return res.json(); })
        .then(function (j) {
            if (!j || !j.ok || !Array.isArray(j.messages) || !j.messages.length) return;

            // Keep welcome bubble, then append saved messages.
            history = [];
            j.messages.forEach(function (m) {
                if (!m || (m.role !== 'user' && m.role !== 'assistant') || !m.content) return;
                appendMessage(m.role, m.content);
                history.push({ role: m.role, content: m.content });
            });
            body.scrollTop = body.scrollHeight;
        })
        .catch(function () { /* silent */ });
    }

    form.addEventListener('submit', function (e) {
        e.preventDefault();
        if (sending) return;
        var text = input.value.trim();
        if (!text) return;

        sending = true;
        sendBtn.disabled = true;
        input.value = '';

        appendMessage('user', text);
        history.push({role: 'user', content: text});

        var typing = appendTyping();

        fetch(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrf,
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            },
            credentials: 'same-origin',
            body: JSON.stringify({
                message: text,
                history: history.slice(0, -1),
            }),
        })
        .then(function (res) {
            return res.json().then(function (j) { return {ok: res.ok, json: j}; });
        })
        .then(function (r) {
            typing.remove();
            if (r.json && r.json.ok && r.json.reply) {
                appendMessage('assistant', r.json.reply);
                history.push({role: 'assistant', content: r.json.reply});
            } else {
                appendMessage('assistant', (r.json && r.json.message) || 'خطایی پیش آمد. لطفاً دوباره تلاش کن.');
            }
        })
        .catch(function () {
            typing.remove();
            appendMessage('assistant', 'ارتباط با سرور قطع شد. لطفاً دوباره تلاش کن.');
        })
        .finally(function () {
            sending = false;
            sendBtn.disabled = false;
            input.focus();
        });
    });
})();
</script>
<?php /**PATH /home/louishop/public_html/engine/resources/views/site/partials/biata-bot.blade.php ENDPATH**/ ?>