<?php
require_once 'includes/auth.php';
require_once 'includes/header.php';
?>

<div class="h-[calc(100vh-140px)] flex overflow-hidden rounded-2xl border border-gray-700 bg-dark">
    <div class="w-full lg:w-1/4 border-r border-gray-700 flex flex-col">
        <div class="p-4 border-b border-gray-700 bg-surface flex justify-between items-center">
            <div>
                <div class="font-bold text-white">My Bots</div>
                <div class="text-xs text-gray-400">Create, select, and delete</div>
            </div>
            <button onclick="openCreateModal()" class="bg-primary hover:bg-indigo-600 text-white px-3 py-2 rounded-lg text-sm font-bold">
                + New
            </button>
        </div>
        <div class="p-3 border-b border-gray-700">
            <div class="relative">
                <i class="fas fa-search absolute left-3 top-3 text-gray-500"></i>
                <input id="botSearch" type="text" placeholder="Search bots..." class="w-full bg-darker border border-gray-600 rounded-lg pl-10 pr-4 py-2 text-gray-200 focus:outline-none focus:border-primary">
            </div>
        </div>
        <div id="botList" class="flex-1 overflow-y-auto"></div>
        <div class="p-3 border-t border-gray-700">
            <button onclick="deleteSelectedBots()" class="w-full bg-red-500/10 hover:bg-red-500 text-red-400 hover:text-white py-2 rounded-lg text-sm font-bold hidden" id="deleteBtn">
                Delete Selected
            </button>
        </div>
    </div>

    <div class="hidden lg:flex w-1/4 border-r border-gray-700 flex-col" id="inboxPanel">
        <div class="p-4 border-b border-gray-700 bg-surface">
            <div class="font-bold text-white" id="selectedBotName">Select a Bot</div>
            <div class="text-xs text-gray-400">Inbox</div>
        </div>
        <div id="conversationList" class="flex-1 overflow-y-auto"></div>
    </div>

    <div class="hidden lg:flex flex-1 bg-darker flex-col" id="chatPanel">
        <div class="p-4 border-b border-gray-700 flex justify-between items-center bg-surface">
            <div class="flex items-center gap-3">
                <img id="chatAvatar" src="" class="w-9 h-9 rounded-full bg-gray-700 border border-gray-600 object-cover">
                <div class="overflow-hidden">
                    <div id="chatPartnerName" class="font-bold text-white truncate">User</div>
                    <div class="text-xs text-gray-400 font-mono" id="chatMeta"></div>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <button onclick="refreshChat()" class="p-2 bg-dark border border-gray-600 rounded-lg text-gray-300 hover:bg-gray-700">
                    <i class="fas fa-sync-alt"></i>
                </button>
            </div>
        </div>

        <div id="messagesContainer" class="flex-1 overflow-y-auto p-4 flex flex-col gap-2"></div>

        <div class="p-4 border-t border-gray-700 flex gap-2 bg-surface">
            <input type="text" id="replyInput" class="flex-1 bg-dark border border-gray-600 rounded-lg px-3 py-3 text-gray-200 focus:outline-none focus:border-primary" placeholder="Reply as bot...">
            <button onclick="sendReply()" class="bg-primary hover:bg-indigo-600 text-white px-5 py-3 rounded-lg font-bold">
                Send
            </button>
        </div>
    </div>
</div>

<div id="createModal" class="fixed inset-0 bg-black bg-opacity-60 hidden items-center justify-center z-50">
    <div class="bg-surface p-6 rounded-2xl shadow-2xl w-[420px] border border-gray-700">
        <div class="flex items-center justify-between mb-4">
            <h3 class="font-bold text-white text-lg">Create New Bot</h3>
            <button onclick="closeCreateModal()" class="text-gray-400 hover:text-white"><i class="fas fa-times"></i></button>
        </div>
        <div class="space-y-3">
            <input type="text" id="newBotName" placeholder="Username (required)" class="w-full bg-dark border border-gray-600 p-3 rounded-lg text-gray-200 focus:outline-none focus:border-primary">
            <input type="text" id="newBotDisplay" placeholder="Display Name (optional)" class="w-full bg-dark border border-gray-600 p-3 rounded-lg text-gray-200 focus:outline-none focus:border-primary">
            <textarea id="newBotBio" placeholder="Bio (e.g. 'Coffee lover ☕')" class="w-full bg-dark border border-gray-600 p-3 rounded-lg text-gray-200 focus:outline-none focus:border-primary h-24 resize-none"></textarea>
            <input type="text" id="newBotAvatar" placeholder="Avatar URL (optional)" class="w-full bg-dark border border-gray-600 p-3 rounded-lg text-gray-200 focus:outline-none focus:border-primary">
        </div>
        <div class="flex justify-end gap-2 mt-5">
            <button onclick="closeCreateModal()" class="px-4 py-2 rounded-lg text-gray-300 hover:bg-dark">Cancel</button>
            <button onclick="createBot()" class="bg-primary hover:bg-indigo-600 text-white px-4 py-2 rounded-lg font-bold">Create</button>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.6.0/axios.min.js"></script>
<script>
const API_URL = '/backend-php/public';

let currentBotId = null;
let currentBotName = null;
let currentConvId = null;
let currentPartner = null;
let chatTimer = null;
let botPollTimer = null;
let selectedForDelete = new Set();

function el(id) { return document.getElementById(id); }

function setVisible(id, visible) {
    const node = el(id);
    if (!node) return;
    node.classList.toggle('hidden', !visible);
    if (visible && id === 'createModal') node.classList.add('flex');
    if (!visible && id === 'createModal') node.classList.remove('flex');
}

function escapeHtml(str) {
    return String(str ?? '')
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;')
        .replaceAll("'", '&#039;');
}

function snapshotCheckedBots() {
    document.querySelectorAll('.bot-check').forEach(cb => {
        const id = Number(cb.value);
        if (!Number.isFinite(id)) return;
        if (cb.checked) selectedForDelete.add(id);
        else selectedForDelete.delete(id);
    });
}

function onBotCheckChange(cb) {
    const id = Number(cb.value);
    if (!Number.isFinite(id)) return;
    if (cb.checked) selectedForDelete.add(id);
    else selectedForDelete.delete(id);
    updateDeleteBtn();
}

function updateDeleteBtn() {
    el('deleteBtn').classList.toggle('hidden', selectedForDelete.size === 0);
}

async function loadBots() {
    snapshotCheckedBots();
    const res = await axios.get(`${API_URL}/seed_users`);
    const bots = Array.isArray(res.data) ? res.data : [];

    const q = (el('botSearch').value || '').toLowerCase().trim();
    const filtered = q === '' ? bots : bots.filter(b => {
        const name = (b.display_name || '').toLowerCase();
        const user = (b.username || '').toLowerCase();
        return name.includes(q) || user.includes(q);
    });

    const list = el('botList');
    list.innerHTML = '';
    if (filtered.length === 0) {
        list.innerHTML = `<div class="p-4 text-gray-500 text-sm">No bots found.</div>`;
        return;
    }

    filtered.forEach(bot => {
        const isSelected = String(bot.id) === String(currentBotId);
        const unread = Number(bot.unread_count || 0);
        const badgeHtml = unread > 0
            ? `<span class="ml-auto inline-flex items-center justify-center min-w-[22px] h-6 px-2 rounded-full bg-red-600 text-white text-xs font-extrabold">${unread}</span>`
            : '';
        const checked = selectedForDelete.has(Number(bot.id)) ? 'checked' : '';

        const row = document.createElement('div');
        row.className = `p-3 border-b border-gray-700 cursor-pointer flex items-center gap-3 ${isSelected ? 'bg-primary/10' : 'hover:bg-dark'}`;
        row.onclick = () => selectBot(bot.id, bot.display_name || bot.username);
        row.innerHTML = `
            <input type="checkbox" value="${escapeHtml(bot.id)}" ${checked} onclick="event.stopPropagation(); onBotCheckChange(this)" class="bot-check accent-primary">
            <img src="${escapeHtml(bot.avatar_url || ('https://ui-avatars.com/api/?name=' + encodeURIComponent(bot.display_name || bot.username || 'Bot')))}" class="w-10 h-10 rounded-full border border-gray-600 object-cover">
            <div class="min-w-0 flex-1">
                <div class="flex items-center gap-2">
                    <div class="font-bold text-sm text-white truncate">${escapeHtml(bot.display_name || bot.username || 'Bot')}</div>
                    ${badgeHtml}
                </div>
                <div class="text-xs text-gray-400 truncate">@${escapeHtml(bot.username || '')}</div>
            </div>
        `;
        list.appendChild(row);
    });

    updateDeleteBtn();
}

async function selectBot(id, name) {
    currentBotId = id;
    currentBotName = name;
    currentConvId = null;
    currentPartner = null;

    try {
        await axios.post(`${API_URL}/seed_users/mark_read`, { bot_id: id });
        await loadBots();
    } catch (e) {}

    el('selectedBotName').innerText = `${name}'s Inbox`;
    setVisible('inboxPanel', true);
    setVisible('chatPanel', false);
    el('conversationList').innerHTML = `<div class="p-4 text-gray-500 text-sm">Loading...</div>`;

    const res = await axios.get(`${API_URL}/seed_users/${id}/inbox`);
    const list = el('conversationList');
    list.innerHTML = '';

    const convs = Array.isArray(res.data) ? res.data : [];
    if (convs.length === 0) {
        list.innerHTML = `<div class="p-4 text-gray-500 text-sm">No conversations yet.</div>`;
        return;
    }

    convs.forEach(conv => {
        const partnerName = conv.partner_name || conv.partner_username || 'User';
        const partnerAvatar = conv.partner_avatar || '';
        const time = conv.last_message_at || conv.updated_at || null;

        const row = document.createElement('div');
        row.className = 'p-3 border-b border-gray-700 hover:bg-dark cursor-pointer';
        row.onclick = () => openChat(conv.conversation_id, partnerName, partnerAvatar);
        row.innerHTML = `
            <div class="flex justify-between gap-3">
                <span class="font-bold text-sm text-white truncate">${escapeHtml(partnerName)}</span>
                <span class="text-xs text-gray-400 whitespace-nowrap">${time ? new Date(time).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}) : ''}</span>
            </div>
            <div class="text-xs text-gray-500 truncate">${escapeHtml(conv.last_message || 'Photo/Media')}</div>
        `;
        list.appendChild(row);
    });
}

async function openChat(convId, partnerName, partnerAvatar) {
    currentConvId = convId;
    currentPartner = { name: partnerName, avatar: partnerAvatar };
    setVisible('chatPanel', true);
    el('chatPartnerName').innerText = partnerName;
    el('chatAvatar').src = partnerAvatar || ('https://ui-avatars.com/api/?name=' + encodeURIComponent(partnerName));
    el('chatMeta').innerText = `Bot: ${currentBotName} • Chat #${convId}`;
    await refreshChat();
    if (chatTimer) clearInterval(chatTimer);
    chatTimer = setInterval(() => refreshChat(true), 3000);
}

async function refreshChat(silent = false) {
    if (!currentConvId) return;
    const res = await axios.get(`${API_URL}/seed_users/messages/${currentConvId}`);
    const msgs = Array.isArray(res.data) ? res.data : [];
    const container = el('messagesContainer');
    if (!silent) container.innerHTML = '';

    if (!silent) {
        msgs.forEach(msg => {
            const isBot = String(msg.sender_id) === String(currentBotId);
            const bubble = document.createElement('div');
            bubble.className = `max-w-[70%] px-3 py-2 rounded-2xl text-sm ${isBot ? 'bg-primary text-white self-end ml-auto rounded-tr-none' : 'bg-surface text-gray-200 border border-gray-700 self-start rounded-tl-none'}`;
            bubble.innerText = msg.body_text || '';
            container.appendChild(bubble);
        });
        container.scrollTop = container.scrollHeight;
    }
}

async function sendReply() {
    const input = el('replyInput');
    const text = (input.value || '').trim();
    if (!text || !currentBotId || !currentConvId) return;

    await axios.post(`${API_URL}/seed_users/reply`, {
        bot_id: currentBotId,
        conversation_id: currentConvId,
        message: text
    });

    input.value = '';
    await refreshChat();
}

async function deleteSelectedBots() {
    const ids = Array.from(selectedForDelete.values()).filter(v => Number.isFinite(v) && v > 0);
    if (ids.length === 0) return;

    if (!confirm(`Delete ${ids.length} bots? This will delete their chats too.`)) return;
    await axios.post(`${API_URL}/seed_users/delete`, { ids });

    if (currentBotId && ids.includes(Number(currentBotId))) {
        currentBotId = null;
        currentConvId = null;
        setVisible('inboxPanel', false);
        setVisible('chatPanel', false);
    }

    selectedForDelete = new Set();
    await loadBots();
    updateDeleteBtn();
}

function openCreateModal() { setVisible('createModal', true); }
function closeCreateModal() { setVisible('createModal', false); }

async function createBot() {
    const username = (el('newBotName').value || '').trim();
    const displayName = (el('newBotDisplay').value || '').trim();
    const bio = (el('newBotBio').value || '').trim();
    const avatarUrl = (el('newBotAvatar').value || '').trim();
    if (!username) return;

    await axios.post(`${API_URL}/seed_users`, {
        username,
        display_name: displayName || undefined,
        bio: bio || undefined,
        avatar_url: avatarUrl || undefined
    });

    el('newBotName').value = '';
    el('newBotDisplay').value = '';
    el('newBotBio').value = '';
    el('newBotAvatar').value = '';
    closeCreateModal();
    await loadBots();
}

el('botSearch').addEventListener('input', () => loadBots());
el('replyInput').addEventListener('keydown', (e) => {
    if (e.key === 'Enter') sendReply();
});

loadBots();
botPollTimer = setInterval(() => loadBots(), 5000);
</script>

<?php require_once 'includes/footer.php'; ?>
