<?php
if (!defined('ABSPATH')) {
    exit;
}

$aysa_agent9_nonce = wp_create_nonce('aysa_nonce');
?>
<div class="wrap aysa-agent9-page">
    <div class="aysa-agent9-shell">
        <aside class="aysa-agent9-sidebar">
            <div class="aysa-agent9-brand">
                <div class="aysa-agent9-brand-kicker">AYSA</div>
                <h1>Agent 9</h1>
                <p>Canonical onboarding runtime cu restore controlat și UI conversațional separat.</p>
            </div>
            <div class="aysa-agent9-status-card">
                <div class="aysa-agent9-status-row">
                    <span>Fază</span>
                    <strong id="aysa-agent9-phase">setup</strong>
                </div>
                <div class="aysa-agent9-status-row">
                    <span>Step</span>
                    <strong id="aysa-agent9-step">bootstrap</strong>
                </div>
                <div class="aysa-agent9-status-row">
                    <span>Tab</span>
                    <strong id="aysa-agent9-tab">setup</strong>
                </div>
            </div>
            <div class="aysa-agent9-summary-card" id="aysa-agent9-summary">
                Agent9 pornește din canonical state și folosește snapshot-ul pluginului doar ca fallback de migrare.
            </div>
        </aside>

        <section class="aysa-agent9-chat">
            <header class="aysa-agent9-chat-header">
                <div>
                    <h2>Conversație</h2>
                    <p>Shell separat, stil chat, pregătit pentru approvals și popup boxes.</p>
                </div>
                <button type="button" class="button button-secondary" id="aysa-agent9-reset">Reset</button>
            </header>

            <div class="aysa-agent9-transcript" id="aysa-agent9-transcript"></div>

            <div class="aysa-agent9-cards" id="aysa-agent9-cards"></div>

            <div class="aysa-agent9-composer">
                <textarea id="aysa-agent9-input" rows="3" placeholder="Scrie un mesaj pentru Agent9..."></textarea>
                <div class="aysa-agent9-composer-actions">
                    <button type="button" class="button button-primary" id="aysa-agent9-send">Trimite</button>
                </div>
            </div>
        </section>
    </div>
</div>

<div class="aysa-agent9-modal" id="aysa-agent9-modal" hidden>
    <div class="aysa-agent9-modal-backdrop"></div>
    <div class="aysa-agent9-modal-dialog">
        <div class="aysa-agent9-modal-header">
            <h3 id="aysa-agent9-modal-title">Action Payload</h3>
            <button type="button" class="button-link" id="aysa-agent9-modal-close">Închide</button>
        </div>
        <textarea id="aysa-agent9-modal-json" rows="12" spellcheck="false"></textarea>
        <div class="aysa-agent9-modal-actions">
            <button type="button" class="button button-secondary" id="aysa-agent9-modal-cancel">Anulează</button>
            <button type="button" class="button button-primary" id="aysa-agent9-modal-confirm">Confirmă</button>
        </div>
    </div>
</div>

<style>
.aysa-agent9-shell{display:grid;grid-template-columns:320px minmax(0,1fr);gap:24px;margin-top:20px;min-height:calc(100vh - 180px)}
.aysa-agent9-sidebar,.aysa-agent9-chat{background:#fff;border:1px solid #dcdcde;border-radius:18px;box-shadow:0 8px 24px rgba(16,24,40,.06)}
.aysa-agent9-sidebar{padding:24px;display:flex;flex-direction:column;gap:18px;background:linear-gradient(180deg,#fafcff 0%,#f4f7fb 100%)}
.aysa-agent9-brand-kicker{font-size:11px;font-weight:700;letter-spacing:.12em;text-transform:uppercase;color:#3858e9}
.aysa-agent9-brand h1{margin:6px 0 8px;font-size:30px;line-height:1.1}
.aysa-agent9-brand p{margin:0;color:#50575e}
.aysa-agent9-status-card,.aysa-agent9-summary-card{background:#fff;border:1px solid #e2e8f0;border-radius:14px;padding:16px}
.aysa-agent9-status-row{display:flex;justify-content:space-between;gap:12px;padding:6px 0}
.aysa-agent9-status-row span{color:#6b7280}
.aysa-agent9-chat{display:flex;flex-direction:column;overflow:hidden}
.aysa-agent9-chat-header{display:flex;justify-content:space-between;gap:16px;align-items:flex-start;padding:20px 22px;border-bottom:1px solid #e5e7eb}
.aysa-agent9-chat-header h2{margin:0 0 4px}
.aysa-agent9-chat-header p{margin:0;color:#6b7280}
.aysa-agent9-transcript{flex:1;overflow:auto;padding:22px;background:#f8fafc}
.aysa-agent9-message{max-width:860px;margin:0 auto 14px;padding:14px 16px;border-radius:16px;white-space:pre-wrap;line-height:1.45}
.aysa-agent9-message-user{background:#1f2937;color:#fff;margin-left:auto}
.aysa-agent9-message-assistant{background:#fff;border:1px solid #e5e7eb}
.aysa-agent9-cards{padding:0 22px 18px;background:#f8fafc}
.aysa-agent9-card{max-width:860px;margin:0 auto 12px;background:#fff;border:1px solid #e5e7eb;border-radius:16px;padding:16px}
.aysa-agent9-card h3{margin:0 0 10px;font-size:15px}
.aysa-agent9-card pre{margin:0;white-space:pre-wrap;word-break:break-word;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}
.aysa-agent9-actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:14px}
.aysa-agent9-composer{padding:18px 22px;border-top:1px solid #e5e7eb;background:#fff}
.aysa-agent9-composer textarea{width:100%;resize:vertical;border:1px solid #cbd5e1;border-radius:14px;padding:14px;font-size:14px;line-height:1.5}
.aysa-agent9-composer-actions{display:flex;justify-content:flex-end;margin-top:12px}
.aysa-agent9-modal[hidden]{display:none}
.aysa-agent9-modal{position:fixed;inset:0;z-index:100000}
.aysa-agent9-modal-backdrop{position:absolute;inset:0;background:rgba(15,23,42,.52)}
.aysa-agent9-modal-dialog{position:relative;max-width:760px;margin:8vh auto;background:#fff;border-radius:18px;padding:20px;box-shadow:0 24px 64px rgba(15,23,42,.32)}
.aysa-agent9-modal-header{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-bottom:12px}
.aysa-agent9-modal-json{width:100%;border:1px solid #cbd5e1;border-radius:14px;padding:14px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px}
.aysa-agent9-modal-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:14px}
@media (max-width: 1100px){
    .aysa-agent9-shell{grid-template-columns:1fr}
    .aysa-agent9-sidebar{order:2}
}
</style>

<script>
(function() {
    const nonce = <?php echo wp_json_encode($aysa_agent9_nonce); ?>;
    const transcriptEl = document.getElementById('aysa-agent9-transcript');
    const cardsEl = document.getElementById('aysa-agent9-cards');
    const inputEl = document.getElementById('aysa-agent9-input');
    const sendEl = document.getElementById('aysa-agent9-send');
    const resetEl = document.getElementById('aysa-agent9-reset');
    const phaseEl = document.getElementById('aysa-agent9-phase');
    const stepEl = document.getElementById('aysa-agent9-step');
    const tabEl = document.getElementById('aysa-agent9-tab');
    const summaryEl = document.getElementById('aysa-agent9-summary');
    const modalEl = document.getElementById('aysa-agent9-modal');
    const modalTitleEl = document.getElementById('aysa-agent9-modal-title');
    const modalJsonEl = document.getElementById('aysa-agent9-modal-json');
    const modalConfirmEl = document.getElementById('aysa-agent9-modal-confirm');
    const modalCloseEl = document.getElementById('aysa-agent9-modal-close');
    const modalCancelEl = document.getElementById('aysa-agent9-modal-cancel');

    let conversationId = '';
    let pendingAction = null;

    function appendMessage(role, message) {
        const node = document.createElement('div');
        node.className = 'aysa-agent9-message ' + (role === 'user' ? 'aysa-agent9-message-user' : 'aysa-agent9-message-assistant');
        node.textContent = message || '';
        transcriptEl.appendChild(node);
        transcriptEl.scrollTop = transcriptEl.scrollHeight;
    }

    function renderCards(cards, actions, fallbackCard) {
        cardsEl.innerHTML = '';
        const normalizedCards = Array.isArray(cards) && cards.length ? cards.slice() : (fallbackCard ? [fallbackCard] : []);
        if (!normalizedCards.length) {
            return;
        }

        normalizedCards.forEach((payload, index) => {
            const card = document.createElement('div');
            card.className = 'aysa-agent9-card';
            const heading = document.createElement('h3');
            heading.textContent = payload.title || payload.type || ('Card ' + (index + 1));
            card.appendChild(heading);

            if (payload.summary) {
                const summary = document.createElement('div');
                summary.style.marginBottom = '10px';
                summary.textContent = payload.summary;
                card.appendChild(summary);
            }

            const body = document.createElement('pre');
            body.textContent = JSON.stringify(payload, null, 2);
            card.appendChild(body);
            cardsEl.appendChild(card);
        });

        if (Array.isArray(actions) && actions.length) {
            const actionCard = document.createElement('div');
            actionCard.className = 'aysa-agent9-card';
            const heading = document.createElement('h3');
            heading.textContent = 'Actions';
            actionCard.appendChild(heading);

            const actionsWrap = document.createElement('div');
            actionsWrap.className = 'aysa-agent9-actions';
            actions.forEach((action) => {
                const button = document.createElement('button');
                button.type = 'button';
                button.className = 'button button-secondary';
                button.textContent = action.label || action.action_key || 'Action';
                button.addEventListener('click', () => handleSuggestedAction(action));
                actionsWrap.appendChild(button);
            });
            actionCard.appendChild(actionsWrap);
            cardsEl.appendChild(actionCard);
        }
    }

    function setStatus(result) {
        phaseEl.textContent = result.phase || 'setup';
        stepEl.textContent = result.current_step || 'bootstrap';
        tabEl.textContent = result.tab || 'setup';
        const view = result.view || {};
        if (view.summary) {
            summaryEl.textContent = view.summary;
        } else if (result.assistant_message) {
            summaryEl.textContent = result.assistant_message;
        }
    }

    function openModal(title, payload, onConfirm) {
        pendingAction = onConfirm;
        modalTitleEl.textContent = title;
        modalJsonEl.value = JSON.stringify(payload || {}, null, 2);
        modalEl.hidden = false;
    }

    function closeModal() {
        modalEl.hidden = true;
        pendingAction = null;
    }

    function handleSuggestedAction(action) {
        const actionKey = action.action_key || '';
        const actionPayload = action.action_payload || {};
        openModal('Confirmă action payload', actionPayload, function(payload) {
            runConversation({
                mode: 'action',
                action_key: actionKey,
                action_payload: JSON.stringify(payload || {})
            });
        });
    }

    function buildRequest(extra) {
        return Object.assign({
            action: 'aysa_agent9_conversation',
            nonce: nonce,
            conversation_id: conversationId,
            conversation_language: 'ro',
            site_host: window.location.hostname
        }, extra || {});
    }

    function runConversation(extra) {
        const body = new URLSearchParams(buildRequest(extra));
        return fetch(ajaxurl, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
            body: body.toString()
        })
        .then((response) => response.json())
        .then((payload) => {
            if (!payload || !payload.success || !payload.data || !payload.data.result) {
                throw new Error(payload && payload.data && payload.data.message ? payload.data.message : 'Agent9 request failed');
            }
            const result = payload.data.result;
            conversationId = result.conversation_id || conversationId;
            transcriptEl.innerHTML = '';
            const messages = Array.isArray(result.messages) ? result.messages : [];
            messages.forEach((item) => appendMessage(item.role === 'user' ? 'user' : 'assistant', item.message || ''));
            setStatus(result);
            const view = result.view || {};
            const fallbackCard = result.action_result && result.action_result.projection ? result.action_result.projection : null;
            renderCards(view.cards, Array.isArray(result.suggested_actions) ? result.suggested_actions : [], fallbackCard);
            return result;
        });
    }

    sendEl.addEventListener('click', function() {
        const message = inputEl.value.trim();
        if (!message) {
            return;
        }
        runConversation({mode: 'message', user_message: message})
            .then(() => {
                inputEl.value = '';
            })
            .catch((error) => appendMessage('assistant', error.message || 'Request failed'));
    });

    inputEl.addEventListener('keydown', function(event) {
        if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
            sendEl.click();
        }
    });

    resetEl.addEventListener('click', function() {
        runConversation({mode: 'reset'}).catch((error) => appendMessage('assistant', error.message || 'Reset failed'));
    });

    modalCloseEl.addEventListener('click', closeModal);
    modalCancelEl.addEventListener('click', closeModal);
    modalConfirmEl.addEventListener('click', function() {
        if (typeof pendingAction !== 'function') {
            closeModal();
            return;
        }
        let parsed = {};
        try {
            parsed = modalJsonEl.value.trim() === '' ? {} : JSON.parse(modalJsonEl.value);
        } catch (error) {
            window.alert('JSON invalid în action payload.');
            return;
        }
        const callback = pendingAction;
        closeModal();
        callback(parsed);
    });

    runConversation({mode: 'bootstrap'}).catch((error) => appendMessage('assistant', error.message || 'Bootstrap failed'));
})();
</script>
