<?php $__env->startSection('title', 'AI Chat Assistant | SEF Digital'); ?>

<?php $__env->startSection('content'); ?>
<div class="sef-chat-page py-4 py-md-5">
    <div class="container">
        <div class="sef-chat-shell">
            <div class="sef-chat-topbar">
                <div>
                    <h1 class="sef-chat-heading mb-1">AI Chat Assistant</h1>
                    <p class="sef-chat-subtitle mb-0">আপনার ভিজিটর এখানে মেসেজ করলে Gemini API দিয়ে সাথে সাথে উত্তর পাবে।</p>
                </div>
                <a href="<?php echo e(route('home')); ?>" class="btn sef-show-product-btn">Show Product</a>
            </div>

            <div class="sef-chat-restore-row">
                <div>
                    <div class="sef-restore-title">ফোন নম্বর দিন</div>
                    <div class="sef-restore-text">একই নম্বরে আগের chat restore করা যাবে</div>
                </div>
                <div class="sef-restore-actions">
                    <input type="text" id="visitorPhone" class="form-control sef-phone-input" placeholder="01XXXXXXXXX">
                    <button type="button" id="restoreBtn" class="btn sef-restore-btn">Start / Restore</button>
                </div>
            </div>

            <div id="chatMessages" class="sef-chat-messages">
                <div class="sef-message-row sef-bot-row">
                    <div class="sef-avatar">S</div>
                    <div class="sef-message sef-bot-message">
                        আসসালামু আলাইকুম। আমি আপনার AI Assistant। পণ্য, দাম, অর্ডার, ডেলিভারি বা যেকোনো তথ্য জানতে মেসেজ করুন।
                    </div>
                </div>
            </div>

            <div class="sef-chat-input-wrap">
                <button type="button" class="sef-plus-btn" aria-label="Add">+</button>
                <input type="text" id="chatInput" class="sef-chat-input" placeholder="আপনার সমস্যাটি লিখুন...">
                <button type="button" id="sendBtn" class="btn sef-send-btn">Send</button>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('style'); ?>
<style>
    :root {
        --sef-primary: #009de7;
        --sef-primary-dark: #0679b1;
        --sef-bg: #030817;
        --sef-bg-2: #071125;
        --sef-card: rgba(10, 19, 39, 0.92);
        --sef-border: rgba(255,255,255,0.08);
        --sef-text: #e6f0ff;
        --sef-text-soft: #9fb5d8;
        --sef-input: rgba(255,255,255,0.06);
    }
    .sef-chat-page { min-height: calc(100vh - 140px); background: radial-gradient(circle at top left, rgba(0,157,231,.16), transparent 28%), radial-gradient(circle at top right, rgba(0,157,231,.10), transparent 25%), linear-gradient(180deg, var(--sef-bg-2) 0%, var(--sef-bg) 100%); }
    .sef-chat-shell { border: 1px solid var(--sef-border); border-radius: 28px; overflow: hidden; background: linear-gradient(180deg, rgba(8,17,34,.98), rgba(3,8,23,.98)); box-shadow: 0 30px 80px rgba(0,0,0,.35); }
    .sef-chat-topbar, .sef-chat-restore-row { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:22px 24px; border-bottom:1px solid var(--sef-border); }
    .sef-chat-heading { color: var(--sef-text); font-size:1.45rem; font-weight:700; }
    .sef-chat-subtitle, .sef-restore-text { color: var(--sef-text-soft); font-size:.94rem; }
    .sef-show-product-btn, .sef-restore-btn, .sef-send-btn { background: var(--sef-primary); border:0; color:#04111f; font-weight:700; border-radius:999px; padding:12px 22px; min-width:140px; }
    .sef-show-product-btn:hover, .sef-restore-btn:hover, .sef-send-btn:hover { background: var(--sef-primary-dark); color:#fff; }
    .sef-restore-title { color:#fff; font-size:1rem; font-weight:700; margin-bottom:4px; }
    .sef-restore-actions { display:flex; align-items:center; gap:12px; }
    .sef-phone-input, .sef-chat-input { background: var(--sef-input); border:1px solid var(--sef-border); color:#fff; border-radius:16px; min-height:54px; padding:14px 18px; }
    .sef-phone-input { min-width:280px; }
    .sef-phone-input::placeholder, .sef-chat-input::placeholder { color:#7f92b0; }
    .sef-phone-input:focus, .sef-chat-input:focus { background: rgba(255,255,255,.08); color:#fff; border-color: rgba(0,157,231,.5); box-shadow: 0 0 0 .2rem rgba(0,157,231,.12); }
    .sef-chat-messages { min-height:480px; max-height:65vh; overflow-y:auto; padding:28px 24px 18px; }
    .sef-message-row { display:flex; align-items:flex-end; gap:12px; margin-bottom:18px; }
    .sef-user-row { justify-content:flex-end; }
    .sef-avatar { width:44px; height:44px; flex:0 0 44px; border-radius:50%; display:grid; place-items:center; color:#fff; font-weight:700; background: linear-gradient(180deg, #b5bfd0, #677387); box-shadow: 0 10px 25px rgba(0,0,0,.25); }
    .sef-user-avatar { background: linear-gradient(180deg, var(--sef-primary), var(--sef-primary-dark)); }
    .sef-message { max-width:min(78%, 860px); border-radius:24px; padding:18px 20px; line-height:1.7; white-space:pre-wrap; word-break:break-word; border:1px solid var(--sef-border); }
    .sef-bot-message { color:#dce8fb; background:#0b1630; }
    .sef-user-message { color:#fff; background: linear-gradient(135deg, rgba(0,157,231,.35), rgba(0,157,231,.18)); }
    .sef-chat-input-wrap { display:flex; align-items:center; gap:12px; padding:18px 24px 24px; border-top:1px solid var(--sef-border); background: rgba(255,255,255,.02); }
    .sef-plus-btn { width:48px; height:48px; border-radius:50%; border:1px solid var(--sef-border); background: rgba(255,255,255,.05); color:#fff; font-size:1.6rem; line-height:1; }
    .sef-chat-input { flex:1; border-radius:999px; min-height:58px; }
    .sef-typing { opacity:.8; font-style:italic; color: var(--sef-text-soft); }
    @media (max-width: 767.98px) {
        .sef-chat-topbar, .sef-chat-restore-row, .sef-chat-input-wrap { flex-direction:column; align-items:stretch; }
        .sef-restore-actions { flex-direction:column; align-items:stretch; }
        .sef-phone-input, .sef-restore-btn, .sef-show-product-btn, .sef-send-btn { width:100%; min-width:100%; }
        .sef-chat-messages { min-height:420px; max-height:60vh; padding:20px 16px 12px; }
        .sef-message { max-width:90%; }
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('script'); ?>
<script>
(() => {
    const chatMessages = document.getElementById('chatMessages');
    const chatInput = document.getElementById('chatInput');
    const sendBtn = document.getElementById('sendBtn');
    const restoreBtn = document.getElementById('restoreBtn');
    const visitorPhone = document.getElementById('visitorPhone');
    const endpoint = <?php echo json_encode(route('chatbot.send'), 15, 512) ?>;
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

    let currentPhone = '';
    let history = [];
    let sending = false;

    function getStorageKey(phone) { return 'sef_chatbot_history_' + (phone || 'guest'); }
    function saveHistory() {
        localStorage.setItem(getStorageKey(currentPhone), JSON.stringify(history));
        localStorage.setItem('sef_chatbot_last_phone', currentPhone || '');
    }
    function loadHistory(phone) {
        try {
            const raw = localStorage.getItem(getStorageKey(phone));
            history = raw ? JSON.parse(raw) : [];
        } catch (e) {
            history = [];
        }
    }
    function scrollToBottom() { chatMessages.scrollTop = chatMessages.scrollHeight; }
    function appendMessage(role, text, save = true) {
        const row = document.createElement('div');
        row.className = 'sef-message-row ' + (role === 'user' ? 'sef-user-row' : 'sef-bot-row');
        const avatar = document.createElement('div');
        avatar.className = 'sef-avatar ' + (role === 'user' ? 'sef-user-avatar' : '');
        avatar.textContent = role === 'user' ? 'Y' : 'S';
        const bubble = document.createElement('div');
        bubble.className = 'sef-message ' + (role === 'user' ? 'sef-user-message' : 'sef-bot-message');
        bubble.textContent = text;
        if (role === 'user') { row.appendChild(bubble); row.appendChild(avatar); } else { row.appendChild(avatar); row.appendChild(bubble); }
        chatMessages.appendChild(row);
        if (save) { history.push({ role, text }); saveHistory(); }
        scrollToBottom();
    }
    function renderHistory() {
        chatMessages.innerHTML = '';
        if (!history.length) {
            appendMessage('model', 'আসসালামু আলাইকুম। আমি আপনার AI Assistant। পণ্য, দাম, অর্ডার, ডেলিভারি বা যেকোনো তথ্য জানতে মেসেজ করুন।', false);
            return;
        }
        history.forEach(item => appendMessage(item.role, item.text, false));
        scrollToBottom();
    }
    function addTyping() {
        const row = document.createElement('div');
        row.className = 'sef-message-row sef-bot-row';
        row.id = 'typingRow';
        row.innerHTML = '<div class="sef-avatar">S</div><div class="sef-message sef-bot-message sef-typing">Typing...</div>';
        chatMessages.appendChild(row);
        scrollToBottom();
    }
    function removeTyping() { document.getElementById('typingRow')?.remove(); }

    async function sendMessage() {
        const message = chatInput.value.trim();
        if (!message || sending) return;
        sending = true;
        appendMessage('user', message, true);
        chatInput.value = '';
        addTyping();
        try {
            const response = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken,
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ message, phone: currentPhone, history: history.slice(-12) })
            });
            const data = await response.json();
            removeTyping();
            if (!response.ok || !data.success) {
                console.error('Gemini chat error:', data);
                appendMessage('model', data.message || 'দুঃখিত, এই মুহূর্তে উত্তর দেওয়া যাচ্ছে না। পরে আবার চেষ্টা করুন।', true);
                return;
            }
            appendMessage('model', data.answer, true);
        } catch (error) {
            console.error('Gemini network error:', error);
            removeTyping();
            appendMessage('model', 'দুঃখিত, network বা server সমস্যার কারণে উত্তর আনা যায়নি।', true);
        } finally {
            sending = false;
        }
    }

    sendBtn.addEventListener('click', sendMessage);
    chatInput.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') { e.preventDefault(); sendMessage(); }
    });
    restoreBtn.addEventListener('click', function () {
        currentPhone = visitorPhone.value.trim();
        loadHistory(currentPhone);
        renderHistory();
    });
    const lastPhone = localStorage.getItem('sef_chatbot_last_phone') || '';
    if (lastPhone) {
        visitorPhone.value = lastPhone;
        currentPhone = lastPhone;
        loadHistory(currentPhone);
    }
    renderHistory();
})();
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('frontend.layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/emdadtwa/sefcard.com/resources/views/frontend/chatbot.blade.php ENDPATH**/ ?>