<?php
/**
 * index.php - Workspace AI Master Edition
 * Fitur: Copy Code, Sidebar, Multi-File, Voice, & UI Expert (Dengan Tabel Word-Ready)
 * Developer: Sikawarsito, S.Kom
 */
session_set_cookie_params(['lifetime' => 31536000, 'path' => '/']);
ini_set('session.gc_maxlifetime', 31536000);
session_start();

// Anti-cache untuk memastikan perubahan responsif langsung terasa di hosting
header("Cache-Control: no-cache, no-store, must-revalidate"); 
header("Pragma: no-cache"); 
header("Expires: 0"); 

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

include 'config/database.php';

// Cek Login ------------------------------------
$cfg = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM settings WHERE id = 1"));
$logo_html = (!empty($cfg['logo']) && file_exists($cfg['logo'])) ? '<img src="' . $cfg['logo'] . '" alt="Logo" style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;">' : '<i class="bi bi-robot"></i>';
$is_guest = false;
$history_count = 0;
$active_session = $_GET['session'] ?? ''; 

if (!isset($_SESSION['user_id'])) {
    $is_guest = true;
    $user_id = 0;
    $nama_siswa = "Tamu (Trial)";
    $nama_depan = "Tamu";
    $role_user = "guest";
    $status_label = "TRIAL 5X";
    $status_broadcast = "none";
    $raw_status = "free";
    $username_user = "";
    $email_user = "";
    
    if (!isset($_SESSION['guest_count'])) { $_SESSION['guest_count'] = 0; }
    $js_session_id = "guest_sess_" . session_id(); 
} else {
    $user_id = $_SESSION['user_id'];
    $nama_siswa = $_SESSION['nama'] ?? 'User';
    $nama_depan = explode(' ', trim($nama_siswa))[0];

    // Tambahkan kolom email_guru pada kueri SELECT
    $stmt_user = mysqli_prepare($conn, "SELECT username, email_guru, status_akun, role, status_broadcast FROM users WHERE id = ?");
    mysqli_stmt_bind_param($stmt_user, "s", $user_id); 
    mysqli_stmt_execute($stmt_user);
    $res_user = mysqli_stmt_get_result($stmt_user);
    $u_data = mysqli_fetch_assoc($res_user);

    $role_user = $u_data['role'] ?? 'siswa';
    $username_user = $u_data['username'] ?? '';
    $email_user = $u_data['email_guru'] ?? ''; // Tarik data email_guru
    $raw_status = strtolower(trim($u_data['status_akun'] ?? 'free')); 
    $status_broadcast = $u_data['status_broadcast'] ?? 'none'; 
    $status_label = ($role_user === 'admin') ? 'ADMIN PRO' : strtoupper($raw_status);
    mysqli_stmt_close($stmt_user);

    $active_session = $_GET['session'] ?? '';
    $js_session_id = !empty($active_session) ? $active_session : 'sess_' . bin2hex(random_bytes(8));

    $query_sidebar = "
        SELECT c1.session_id, c1.user_message
        FROM chat_history c1
        INNER JOIN (
            SELECT session_id, MIN(id) as first_id
            FROM chat_history
            WHERE user_id = ?
            GROUP BY session_id
        ) c2 ON c1.id = c2.first_id
        ORDER BY c1.id DESC
    ";
    $stmt_sidebar = mysqli_prepare($conn, $query_sidebar);
    mysqli_stmt_bind_param($stmt_sidebar, "s", $user_id);
    mysqli_stmt_execute($stmt_sidebar);
    $res_sidebar = mysqli_stmt_get_result($stmt_sidebar);
    $chat_sessions = [];
    while ($row = mysqli_fetch_assoc($res_sidebar)) {
        $chat_sessions[] = $row;
    }
    mysqli_stmt_close($stmt_sidebar);

    if (!empty($active_session)) {
        $stmt_history = mysqli_prepare($conn, "SELECT user_message, ai_response FROM chat_history WHERE user_id = ? AND session_id = ? ORDER BY id ASC");
        mysqli_stmt_bind_param($stmt_history, "ss", $user_id, $active_session); 
    } else {
        $stmt_history = mysqli_prepare($conn, "SELECT user_message, ai_response FROM chat_history WHERE user_id = ? AND session_id = 'NEW_ROOM' ORDER BY id ASC");
        mysqli_stmt_bind_param($stmt_history, "s", $user_id); 
    }
    mysqli_stmt_execute($stmt_history);
    $result_history = mysqli_stmt_get_result($stmt_history);
    $history_count = mysqli_num_rows($result_history);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>XIEQA AI</title>
    
    <meta name="csrf-token" content="<?= $_SESSION['csrf_token'] ?>">
    <link rel="manifest" href="manifest.json">
    <meta name="theme-color" content="#1a73e8">
    <link rel="apple-touch-icon" href="assets/app-icon.svg">
    
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
    
    <style>
        :root { 
            --sidebar-width: 280px; 
            --gemini-blue: #1a73e8; 
            --full-h: 100dvh; 
            --bg-chat: #ffffff;
            --gemini-gradient: linear-gradient(90deg, #4285f4, #9b72cb, #d96570);
        }
        * { font-family: 'Inter', sans-serif; box-sizing: border-box; }
        html, body { height: 100%; height: var(--full-h); margin: 0; padding: 0; overflow-x: hidden; background: var(--bg-chat); width: 100%; -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }
        
        .main-wrapper { display: flex; height: var(--full-h); width: 100%; max-width: 100vw; overflow-x: hidden; position: relative; }
        
        @media (max-width: 768px) {
            .main-wrapper { display: block; position: relative; }
            .chat-area { width: 100% !important; height: 100% !important; }
        }
        
        .sidebar { 
            width: var(--sidebar-width); background: #f8fafc; border-right: 1px solid #e2e8f0; 
            display: flex; flex-direction: column; height: 100%; padding: 20px; 
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); flex-shrink: 0; z-index: 2000; overflow: hidden; white-space: nowrap;
        }

        .sidebar.collapsed { width: 0; padding: 0; opacity: 0; border: none; }
        .chat-area { flex: 1; display: flex; flex-direction: column; height: 100%; background: white; position: relative; min-width: 0; max-width: 100%; overflow: hidden; }
        .top-bar { padding: 10px 15px; border-bottom: 1px solid #f1f5f9; display: flex; align-items: center; justify-content: space-between; background: rgba(255,255,255,0.9); backdrop-filter: blur(5px); z-index: 10; }
        
        .toggle-btn { background: none; border: none; font-size: 24px; color: #444746; padding: 5px; border-radius: 50%; cursor: pointer; transition: 0.2s; }
        .toggle-btn:hover { background: #f0f4f9; }

        .btn-live-gemini {
            display: flex; align-items: center; gap: 8px; background: var(--gemini-gradient);
            border: none; padding: 6px 16px; border-radius: 50px; color: white;
            font-size: 13px; font-weight: 700; text-decoration: none; transition: all 0.3s ease; box-shadow: 0 4px 12px rgba(66, 133, 244, 0.2);
        }
        .btn-live-gemini:hover { transform: translateY(-2px); color: white; box-shadow: 0 6px 15px rgba(155, 114, 203, 0.4); }
        .live-pulse-dot { width: 8px; height: 8px; background: white; border-radius: 50%; position: relative; }
        .live-pulse-dot::after { content: ''; position: absolute; width: 100%; height: 100%; background: white; border-radius: 50%; animation: pulse-ring 1.5s infinite; }
        @keyframes pulse-ring { 0% { transform: scale(1); opacity: 1; } 100% { transform: scale(3); opacity: 0; } }

        .btn-close-sidebar { position: absolute; top: 15px; right: 15px; background: none; border: none; color: #64748b; cursor: pointer; display: none; }
        @media (min-width: 992px) { .btn-close-sidebar { display: block; } }

        #chat-box { flex-grow: 1; overflow-y: auto; padding: 20px 0; display: flex; flex-direction: column; gap: 25px; scroll-behavior: smooth; }
        .msg-container { width: 100%; max-width: 850px; margin: 0 auto; padding: 0 16px; display: flex; gap: 14px; }
        .avatar { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
        .avatar-ai { color: var(--gemini-blue); font-size: 1.4rem; }
        .avatar-user { background: #5f6368; color: white; font-size: 0.9rem; }
        
        .u-msg { background: #f0f4f9; color: #1f1f1f; padding: 12px 18px; border-radius: 18px; font-size: 16px; line-height: 1.6; max-width: 85%; border-top-right-radius: 4px; }
        .a-msg { color: #1f1f1f; font-size: 16px; line-height: 1.7; flex: 1; overflow-wrap: break-word; }

        /* ===================== CODE BLOCK - GEMINI STYLE ===================== */
        .code-container {
            position: relative;
            margin: 14px 0;
            border-radius: 12px;
            overflow: hidden;
            background: #0d1117;
            border: 1px solid #30363d;
            display: flex;
            flex-direction: column;
        }
        /* Header bar selalu terlihat di atas — tidak ikut scroll */
        .code-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 6px 12px;
            background: #161b22;
            border-bottom: 1px solid #30363d;
            flex-shrink: 0;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        .code-lang-label {
            font-size: 11px;
            font-weight: 600;
            color: #8b949e;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            font-family: 'Consolas', monospace;
        }
        .code-actions { display: flex; gap: 6px; align-items: center; }
        .copy-btn, .save-btn {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 4px 10px;
            font-size: 11px;
            font-weight: 500;
            background: rgba(255,255,255,0.07);
            color: #c9d1d9;
            border: 1px solid rgba(255,255,255,0.15);
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
            white-space: nowrap;
        }
        .copy-btn:hover, .save-btn:hover { background: rgba(255,255,255,0.15); border-color: rgba(255,255,255,0.3); color: #fff; }
        .copy-btn.copied { background: rgba(74,222,128,0.15); border-color: rgba(74,222,128,0.4); color: #4ade80; }
        .save-btn { background: rgba(59, 130, 246, 0.1); border-color: rgba(59, 130, 246, 0.3); color: #60a5fa; }
        .save-btn:hover { background: rgba(59, 130, 246, 0.2); border-color: rgba(59, 130, 246, 0.5); color: #93c5fd; }
        /* Area kode — responsif, wrap otomatis, tanpa scroll samping */
        .code-scroll-area {
            overflow-x: hidden;   /* tidak perlu scroll kanan */
            overflow-y: auto;
            max-height: 500px;
        }
        .code-scroll-area::-webkit-scrollbar { width: 5px; }
        .code-scroll-area::-webkit-scrollbar-track { background: #0d1117; }
        .code-scroll-area::-webkit-scrollbar-thumb { background: #30363d; border-radius: 3px; }
        .code-scroll-area::-webkit-scrollbar-thumb:hover { background: #58a6ff; }
        pre { margin: 0; }
        pre code {
            display: block;
            padding: 1.1em 1.2em !important;
            font-size: 0.85rem;
            font-family: 'Consolas', 'Fira Code', monospace;
            color: #e6edf3;
            border-radius: 0 !important;
            white-space: pre-wrap;   /* wrap otomatis ikut lebar layar */
            word-break: break-all;   /* potong kata panjang agar tidak meluber */
            overflow-wrap: break-word;
            line-height: 1.65;
        }
        /* Nomor baris */
        .code-line-count {
            font-size: 10px;
            color: #484f58;
            font-family: monospace;
        }
        /* =====================================================================*/

        /* ========================================================================= */
/* STYLING TABEL ELEGAN & MODERN */
/* ========================================================================= */
.table-wrapper {
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    overflow: hidden;
    margin: 20px 0;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
}
.table-header-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 16px;
    background: #f8fafc;
    border-bottom: 1px solid #e2e8f0;
}
.table-title {
    font-size: 0.85rem;
    font-weight: 600;
    color: #475569;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.table-actions {
    display: flex;
    gap: 8px;
}
.btn-table-action {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 6px 12px;
    font-size: 12px;
    font-weight: 500;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
    border: 1px solid transparent;
}
.btn-excel { background: rgba(16, 185, 129, 0.1); color: #059669; }
.btn-excel:hover { background: #10b981; color: white; }
.btn-word { background: rgba(59, 130, 246, 0.1); color: #2563eb; }
.btn-word:hover { background: #3b82f6; color: white; }
.table-scroll {
    overflow-x: auto;
    width: 100%;
}
.a-msg table { 
    width: 100%; 
    border-collapse: collapse !important; 
    font-size: 0.9em; 
    color: #334155; 
    margin: 0;
}
.a-msg th, .a-msg td { 
    padding: 12px 16px; 
    border-bottom: 1px solid #f1f5f9 !important;
    border-left: none !important;
    border-right: none !important;
    border-top: none !important;
}
.a-msg th { 
    background-color: #ffffff !important; 
    font-weight: 600; 
    text-align: left; 
    color: #0f172a; 
    border-bottom: 2px solid #e2e8f0 !important;
    white-space: nowrap;
}
.a-msg tr:hover td {
    background-color: #f8fafc;
}
.a-msg tr:last-child td {
    border-bottom: none !important;
}
/* ========================================================================= */
        /* ========================================================================= */

        .suggestion-card { transition: all 0.2s; cursor: pointer; border: 1px solid #e2e8f0; background: #f8fafc; height: 100%; }
        .suggestion-card:hover { transform: translateY(-3px); border-color: var(--gemini-blue); background: #f0f4f9; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }

        .input-container { padding: 10px 16px 20px; background: white; width: 100%; }
        .input-inner { max-width: 850px; margin: 0 auto; position: relative; }
        
        .mode-selector { display: flex; gap: 8px; margin-bottom: 12px; overflow-x: auto; scrollbar-width: none; padding-bottom: 2px; }
        .mode-btn { white-space: nowrap; padding: 6px 16px; border-radius: 50px; border: 1px solid #e2e8f0; background: white; font-size: 13px; color: #444746; font-weight: 500; cursor: pointer; transition: 0.2s; display: flex; align-items: center; gap: 6px; }
        .mode-btn.active { background: #e8f0fe; border-color: transparent; color: #1a73e8; font-weight: 600; }
        
        /* Tombol Mode RPP */
        .mode-btn[data-mode="rpp_maker"].active { background: #fff1f2; color: #e11d48; }

        .input-wrapper { background: #f0f4f9; border-radius: 32px; padding: 14px 24px; display: flex; align-items: flex-end; gap: 14px; transition: 0.2s; border: 1px solid transparent; box-shadow: 0 2px 6px rgba(0,0,0,0.05); }
        #user-input { border: none; background: transparent; font-size: 16px; width: 100%; outline: none; padding: 6px 0; resize: none; max-height: 250px; overflow-y: auto; line-height: 1.6; color: #1f1f1f; min-height: 24px; }
        
        .typing-indicator {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 10px 16px;
            background: #f0f4f9;
            border-radius: 18px;
            width: fit-content;
            border-top-left-radius: 4px;
        }
        .typing-dots-wrap { display: flex; gap: 5px; align-items: center; }
        .typing-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #94a3b8;
            animation: typing-bounce 1.4s infinite ease-in-out both;
        }
        .typing-dot:nth-child(1) { animation-delay: 0s;    background: #60a5fa; }
        .typing-dot:nth-child(2) { animation-delay: 0.2s;  background: #818cf8; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s;  background: #a78bfa; }
        .typing-label {
            font-size: 12px;
            color: #64748b;
            font-style: italic;
            margin-left: 4px;
            animation: typing-fade 1.4s infinite ease-in-out;
            transition: color 0.5s;
        }
        /* --- COOLDOWN STATES: Indikator AI sedang antri --- */
        .typing-cooldown-warn .typing-dot { background: #fbbf24 !important; }
        .typing-cooldown-warn .typing-label { color: #d97706; }
        .typing-cooldown-busy .typing-dot { background: #f87171 !important; }
        .typing-cooldown-busy .typing-label { color: #dc2626; }
        @keyframes typing-bounce {
            0%, 80%, 100% { transform: translateY(0);   opacity: 0.4; }
            40%            { transform: translateY(-6px); opacity: 1;   }
        }
        @keyframes typing-fade {
            0%, 100% { opacity: 0.5; }
            50%       { opacity: 1;   }
        }
        
        .typing-cursor {
            display: inline-block;
            width: 6px;
            height: 1.1em;
            background-color: var(--gemini-blue);
            vertical-align: middle;
            animation: blink 1s step-end infinite;
            margin-left: 2px;
            border-radius: 2px;
        }
        @keyframes blink {
            50% { opacity: 0; }
        }

        /* === FILE QUEUE CHIPS === */
        #preview-container { display: none; margin-bottom: 8px; margin-left: 2px; }
        #file-chips-wrap { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
        .file-chip {
            display: inline-flex; align-items: center; gap: 6px;
            background: #e8f0fe; color: #1a73e8;
            padding: 5px 10px 5px 8px;
            border-radius: 20px; font-size: 12px; font-weight: 600;
            border: 1px solid #d2e3fc;
            animation: chipIn 0.18s cubic-bezier(0.34,1.56,0.64,1);
            max-width: 180px;
        }
        .file-chip.is-image { background: #f0fdf4; color: #16a34a; border-color: #bbf7d0; }
        .file-chip .chip-icon { font-size: 13px; flex-shrink: 0; }
        .file-chip .chip-name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .file-chip .chip-remove { flex-shrink: 0; cursor: pointer; color: #94a3b8; font-size: 14px; line-height: 1; transition: color 0.15s; }
        .file-chip .chip-remove:hover { color: #ef4444; }
        #file-count-badge { font-size: 11px; color: #64748b; margin-left: 2px; }
        @keyframes chipIn {
            from { transform: scale(0.7); opacity: 0; }
            to   { transform: scale(1);   opacity: 1; }
        }

        @media (max-width: 1199px) {
            .sidebar { position: fixed; left: -280px; transition: transform 0.3s ease; height: 100% !important; }
            .sidebar.active { transform: translateX(280px); box-shadow: 10px 0 20px rgba(0,0,0,0.1); width: 280px !important; opacity: 1 !important; padding: 20px !important; }
            .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.4); z-index: 1999; }
            .sidebar.active + .sidebar-overlay { display: block; }
            .msg-container, .input-inner { max-width: 100% !important; padding: 0 12px; }
            .u-msg, .a-msg { font-size: 16px !important; }
        }
        
        /* Khusus Layar Panjang (Tinggi) Seperti Redmi 13 */
        @media screen and (max-aspect-ratio: 13/24) {
            .input-wrapper { padding: 12px 18px !important; }
            #user-input { font-size: 16px !important; }
        }
        
        .copyright-dev { font-size: 10px; color: #94a3b8; margin-top: auto; text-align: center; border-top: 1px solid #f1f5f9; padding-top: 15px; }
        .limit-reached #chat-box { filter: blur(2px); pointer-events: none; user-select: none; }
        .modal { z-index: 9999 !important; }
        .modal-backdrop { z-index: 9998 !important; }

        /* ===================== XIEQA MAPS STYLE ===================== */
        @keyframes pulseMapIcon {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.3); opacity: 0.5; }
            100% { transform: scale(1); opacity: 1; }
        }
        .map-pulse {
            animation: pulseMapIcon 1.2s infinite ease-in-out;
            display: inline-block;
        }
        .xieqa-map-brand {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            background: #ffffff;
            color: #222;
            padding: 6px 15px;
            font-size: 12px;
            font-weight: 800;
            letter-spacing: 0.5px;
            z-index: 100;
            pointer-events: none;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .xieqa-map-brand i { color: #ff4757; margin-right: 6px; font-size: 14px; }
        .xieqa-map-dark-filter {
            filter: invert(100%) hue-rotate(180deg) brightness(95%) contrast(90%);
        }
        .xieqa-map-iframe { transition: filter 0.4s ease; border:0; margin-bottom: -5px; }

    </style>
</head>
<body>

<div class="main-wrapper">
    <div class="sidebar" id="sidebar">
        <button class="btn-close-sidebar" id="closeSidebarDesktop" title="Ciutkan Menu">
            <i class="bi bi-layout-sidebar-inset"></i>
        </button>

        <a href="index.php" class="btn btn-primary rounded-pill mb-4 py-2 fw-bold shadow-sm text-center d-block text-decoration-none">
            <i class="bi bi-plus-lg me-1"></i> Chat Baru
        </a>
        
        <div class="px-3 py-2 bg-white border rounded-3 mb-3 shadow-sm d-flex align-items-center">
            <div class="bg-primary bg-opacity-10 text-primary rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 32px; height: 32px; flex-shrink: 0;">
                <i class="bi bi-person-fill" style="font-size: 16px;"></i>
            </div>
            <div class="text-truncate flex-grow-1">
                <span class="text-muted d-block fw-bold" style="font-size: 9px; letter-spacing: 0.5px;">STATUS AKUN</span>
                <span class="fw-bold text-dark text-truncate d-block" style="font-size: 13px;"><?= htmlspecialchars($nama_siswa) ?></span>
            </div>
        </div>

        <div class="chat-list-container mb-3" style="flex-grow: 1; overflow-y: auto; overflow-x: hidden; padding-right: 5px;">
            <small class="text-muted d-block mb-2 fw-bold" style="font-size: 10px; letter-spacing: 0.5px;">RIWAYAT OBROLAN</small>
            <?php if(!$is_guest && !empty($chat_sessions)): ?>
                <?php foreach($chat_sessions as $cs): ?>
                    <div class="d-flex align-items-center mb-2 position-relative group-chat-item">
                        <a href="?session=<?= $cs['session_id'] ?>" class="btn btn-light text-start rounded-3 text-truncate d-flex align-items-center gap-2 flex-grow-1 <?= ($active_session === $cs['session_id']) ? 'border-primary border-2 bg-primary bg-opacity-10 text-primary fw-bold' : 'text-secondary border-0 shadow-sm' ?>" style="font-size: 13px; padding-right: 35px;">
                            <i class="bi bi-chat-left-text"></i> 
                            <span class="text-truncate"><?= htmlspecialchars(substr($cs['user_message'], 0, 25)) ?>...</span>
                        </a>
                        
                        <div class="dropdown position-absolute end-0 me-1">
                            <button class="btn btn-sm text-secondary p-1 border-0 shadow-none" type="button" data-bs-toggle="dropdown" aria-expanded="false" style="background: transparent;">
                                <i class="bi bi-three-dots-vertical"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end shadow border-0" style="font-size: 13px; z-index: 9999;">
                                <li>
                                    <button class="dropdown-item text-danger fw-bold btn-delete-session" data-session="<?= $cs['session_id'] ?>">
                                        <i class="bi bi-trash3 me-2"></i> Hapus Obrolan
                                    </button>
                                </li>
                            </ul>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="text-muted small fst-italic">Belum ada riwayat</div>
            <?php endif; ?>
        </div>
        
        <?php if ($raw_status !== 'pro' && $role_user !== 'admin' && !$is_guest): ?>
            <a href="upgrade_pro.php" class="btn btn-warning w-100 text-start mb-2 rounded-pill small fw-bold shadow-sm" style="background: linear-gradient(90deg, #f59e0b, #d97706); color: white; border: none;">
                <i class="bi bi-star-fill me-2"></i> Upgrade PRO
            </a>
        <?php endif; ?>
        <button class="btn btn-light w-100 text-start mb-2 rounded-pill small text-danger" id="btn-del">
            <i class="bi bi-trash3 me-2"></i> Hapus Histori
        </button>

        <?php if($role_user == 'admin'): ?>
            <a href="admin/dashboard.php" class="btn btn-light w-100 text-start mb-2 rounded-pill small">
                <i class="bi bi-speedometer2 me-2"></i> Admin Panel
            </a>
        <?php endif; ?>

        <?php if(!$is_guest): ?>
            <div class="dropup w-100 mb-2">
                <button class="btn btn-light w-100 text-start rounded-pill small d-flex justify-content-between align-items-center" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                    <span><i class="bi bi-grid-fill me-2 text-primary"></i> Ekosistem</span>
                    <i class="bi bi-chevron-up" style="font-size: 10px;"></i>
                </button>
                <ul class="dropdown-menu shadow border-0 w-100 mb-2 rounded-4 p-2" style="font-size: 13px; z-index: 9999;">
                    <li>
                        <a href="ekosistem.php" class="dropdown-item rounded py-2 d-flex align-items-center fw-bold text-primary bg-primary bg-opacity-10 mb-1">
                            <i class="bi bi-grid-3x3-gap-fill me-2"></i> Portal Ekosistem
                        </a>
                    </li>
                    <li>
                        <button type="button" class="dropdown-item rounded py-2 d-flex align-items-center" data-bs-toggle="modal" data-bs-target="#settingModal">
                            <i class="bi bi-gear text-secondary me-2"></i> Pengaturan Akun
                        </button>
                    </li>
                    <li>
                        <?php if ($raw_status === 'pro' || $role_user === 'admin'): ?>
                            <a class="dropdown-item rounded py-2 d-flex align-items-center text-success fw-bold" href="analisis/index.php">
                                <i class="bi bi-graph-up-arrow me-2"></i> Analisis Trend
                                <span class="badge ms-auto rounded-pill text-white" style="background:linear-gradient(90deg,#10b981,#059669);font-size:9px;">PRO</span>
                            </a>
                        <?php else: ?>
                            <a class="dropdown-item rounded py-2 d-flex align-items-center text-secondary" style="opacity: 0.7;" href="upgrade_pro.php">
                                <i class="bi bi-lock-fill me-2"></i> Analisis Tred
                                <span class="badge bg-danger ms-auto rounded-pill" style="font-size: 9px;">PRO</span>
                            </a>
                        <?php endif; ?>
                    </li>
                    <li>
                        <a class="dropdown-item rounded py-2 d-flex align-items-center" href="llm/index.php">
                            <i class="bi bi-key text-warning me-2"></i> LLM API Key
                        </a>
                    </li>
                    <li>
                        <a class="dropdown-item rounded py-2 d-flex align-items-center" href="apikey/index.php">
                            <i class="bi bi-cpu text-info me-2"></i> IoT Integrasi
                        </a>
                    </li>
                    <li>
                        <a class="dropdown-item rounded py-2 d-flex align-items-center" href="robot_simulator/index.php">
                            <i class="bi bi-display text-primary me-2"></i> IoT Simulator
                            <span class="badge ms-auto rounded-pill text-white bg-blue-500" style="font-size:9px;">NEW</span>
                        </a>
                    </li>
                    <li>
                        <?php if ($raw_status === 'pro' || $role_user === 'admin'): ?>
                            <a class="dropdown-item rounded py-2 d-flex align-items-center" href="autokoding/index.php">
                                <i class="bi bi-robot me-2" style="color: #8b5cf6;"></i> Agent Koding
                                <span class="badge ms-auto rounded-pill text-white" style="background:linear-gradient(90deg,#8b5cf6,#6d28d9);font-size:9px;">PRO</span>
                            </a>
                        <?php else: ?>
                            <a class="dropdown-item rounded py-2 d-flex align-items-center text-secondary" style="opacity: 0.7;" href="upgrade_pro.php">
                                <i class="bi bi-lock-fill me-2"></i> Agent Koding
                                <span class="badge bg-danger ms-auto rounded-pill" style="font-size: 9px;">PRO</span>
                            </a>
                        <?php endif; ?>
                    </li>
                    <li>
                        <?php if ($role_user === 'admin' || $status_broadcast === 'approved'): ?>
                            <a class="dropdown-item rounded py-2 d-flex align-items-center text-success fw-bold" href="generate_share.php">
                                <i class="bi bi-broadcast me-2"></i> Broadcast
                            </a>
                        <?php elseif ($status_broadcast === 'pending'): ?>
                            <a class="dropdown-item rounded py-2 d-flex align-items-center text-secondary" href="#" onclick="alert('Pengajuan fitur Broadcast sedang diverifikasi admin. Mohon tunggu 1x24 Jam.'); return false;">
                                <i class="bi bi-hourglass-split me-2"></i> Broadcast (Pending)
                            </a>
                        <?php elseif ($status_broadcast === 'blocked'): ?>
                            <a class="dropdown-item rounded py-2 d-flex align-items-center text-danger" href="#" onclick="alert('Maaf, fitur ini terblokir. Silakan hubungi Admin.'); return false;">
                                <i class="bi bi-shield-x me-2"></i> Broadcast (Terblokir)
                            </a>
                        <?php else: ?>
                            <a class="dropdown-item rounded py-2 d-flex align-items-center text-secondary" href="#" <?php if(!$is_guest): ?>data-bs-toggle="modal" data-bs-target="#modalBroadcast"<?php endif; ?>>
                                <i class="bi bi-lock-fill me-2"></i> Broadcast
                            </a>
                        <?php endif; ?>
                    </li>
                </ul>
            </div>
        <?php endif; ?>

        <?php if($is_guest): ?>
            <a href="auth/login_page.php" class="btn btn-primary w-100 mt-auto rounded-pill fw-bold small shadow-sm">
                <i class="bi bi-person-plus-fill me-2"></i> Daftar / Login
            </a>
        <?php else: ?>
            <a href="auth/logout.php" class="btn btn-outline-secondary w-100 mt-auto rounded-pill fw-bold small">
                <i class="bi bi-box-arrow-right me-2"></i> Logout
            </a>
        <?php endif; ?>

        <div class="copyright-dev">
            &copy; <?= date('Y') ?> <b>sikawarsito.s.kom</b><br>
            All Rights Reserved
        </div>
    </div>
    <div class="sidebar-overlay" id="overlay"></div>

    <div class="chat-area">
        <div class="top-bar">
            <div class="d-flex align-items-center gap-3">
                <button class="toggle-btn" id="toggleSidebar" title="Menu">
                    <i class="bi bi-list"></i>
                </button>
                <div class="fw-bold small text-secondary d-flex align-items-center gap-2" style="max-width: 50vw;">
                    <span class="badge bg-primary rounded-pill flex-shrink-0"><?= $status_label ?></span>
                    <span class="text-truncate">XIEQA AI</span>
                </div>
            </div>

            <div class="d-flex align-items-center gap-2">
                <a href="live.php" class="btn-live-gemini">
                    <div class="live-pulse-dot"></div> LIVE
                </a>
            </div>
        </div>

        <div id="chat-box">
            <?php if($history_count == 0): ?>
                <div class="empty-state text-center mt-5 fade-in">
                    <div class="mb-4">
                        <span class="bg-white p-3 rounded-circle shadow-sm d-inline-block" style="width: 80px; height: 80px; display: inline-flex !important; align-items: center; justify-content: center; overflow: hidden;">
                            <?php if (!empty($cfg['logo']) && file_exists($cfg['logo'])): ?>
                                <img src="<?= $cfg['logo'] ?>" alt="Logo" style="width: 100%; height: 100%; object-fit: cover;">
                            <?php else: ?>
                                <i class="bi bi-robot text-primary fs-1"></i>
                            <?php endif; ?>
                        </span>
                    </div>
                    
                    <h4 class="fw-bold text-dark">Halo, <?= htmlspecialchars($nama_depan) ?>!</h4>
                    <p class="text-muted px-3" style="max-width: 600px; margin: 0 auto;">
                        <?= htmlspecialchars($cfg['pesan_sambutan']) ?>
                    </p>
                    
                    <div class="row g-2 justify-content-center mt-3 px-3" style="max-width: 600px; width: 100%; margin: 0 auto;">
                        <!-- Agent Koding -->
                        <div class="col-md-4 col-4">
                            <?php if ($raw_status === 'pro' || $role_user === 'admin'): ?>
                                <a href="autokoding/index.php" class="suggestion-card d-block p-2 rounded-3 text-center h-100 text-decoration-none shadow-sm position-relative overflow-hidden" style="border: 1px solid rgba(139, 92, 246, 0.2); background: linear-gradient(145deg, #ffffff, #f8faff);">
                            <?php else: ?>
                                <a href="upgrade_pro.php" class="suggestion-card d-block p-2 rounded-3 text-center h-100 text-decoration-none shadow-sm position-relative overflow-hidden" style="border: 1px solid #e2e8f0; background: #f8fafc; opacity: 0.9;">
                            <?php endif; ?>
                                <div class="mb-1 d-flex justify-content-center">
                                    <div class="rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px; background: rgba(139, 92, 246, 0.1);">
                                        <i class="bi bi-robot" style="color: #8b5cf6; font-size: 15px;"></i>
                                    </div>
                                </div>
                                <div class="fw-bold text-dark mb-1" style="font-size: 10px; line-height: 1.2;">Agent Koding</div>
                                <div class="text-muted" style="font-size: 8px; line-height: 1.1;">Asisten coding</div>
                                <?php if ($raw_status !== 'pro' && $role_user !== 'admin'): ?>
                                    <span class="badge bg-danger position-absolute top-0 end-0 m-1 rounded-pill" style="font-size: 7px; padding: 2px 4px;">PRO</span>
                                <?php endif; ?>
                            </a>
                        </div>
                        
                        <!-- IoT Simulator -->
                        <div class="col-md-4 col-4">
                            <a href="robot_simulator/index.php" class="suggestion-card d-block p-2 rounded-3 text-center h-100 text-decoration-none shadow-sm position-relative overflow-hidden" style="border: 1px solid rgba(59, 130, 246, 0.2); background: linear-gradient(145deg, #ffffff, #f0f7ff);">
                                <div class="mb-1 d-flex justify-content-center">
                                    <div class="rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px; background: rgba(59, 130, 246, 0.1);">
                                        <i class="bi bi-display text-primary" style="font-size: 15px;"></i>
                                    </div>
                                </div>
                                <div class="fw-bold text-dark mb-1" style="font-size: 10px; line-height: 1.2;">IoT Simulator</div>
                                <div class="text-muted" style="font-size: 8px; line-height: 1.1;">Simulasi 3D</div>
                                <span class="badge bg-primary position-absolute top-0 end-0 m-1 rounded-pill" style="font-size: 7px; padding: 2px 4px;">NEW</span>
                            </a>
                        </div>
                        
                        <!-- Analisis Trend -->
                        <div class="col-md-4 col-4">
                            <?php if ($raw_status === 'pro' || $role_user === 'admin'): ?>
                                <a href="analisis/index.php" class="suggestion-card d-block p-2 rounded-3 text-center h-100 text-decoration-none shadow-sm position-relative overflow-hidden" style="border: 1px solid rgba(16, 185, 129, 0.2); background: linear-gradient(145deg, #ffffff, #f0fdf4);">
                            <?php else: ?>
                                <a href="upgrade_pro.php" class="suggestion-card d-block p-2 rounded-3 text-center h-100 text-decoration-none shadow-sm position-relative overflow-hidden" style="border: 1px solid #e2e8f0; background: #f8fafc; opacity: 0.9;">
                            <?php endif; ?>
                                <div class="mb-1 d-flex justify-content-center">
                                    <div class="rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px; background: rgba(16, 185, 129, 0.1);">
                                        <i class="bi bi-graph-up-arrow text-success" style="font-size: 15px;"></i>
                                    </div>
                                </div>
                                <div class="fw-bold text-dark mb-1" style="font-size: 10px; line-height: 1.2;">Analisis Trend</div>
                                <div class="text-muted" style="font-size: 8px; line-height: 1.1;">Data analitik</div>
                                <?php if ($raw_status !== 'pro' && $role_user !== 'admin'): ?>
                                    <span class="badge bg-danger position-absolute top-0 end-0 m-1 rounded-pill" style="font-size: 7px; padding: 2px 4px;">PRO</span>
                                <?php endif; ?>
                            </a>
                        </div>

                        <!-- IoT Integrasi -->
                        <div class="col-md-4 col-4">
                            <a href="apikey/index.php" class="suggestion-card d-block p-2 rounded-3 text-center h-100 text-decoration-none shadow-sm position-relative overflow-hidden" style="border: 1px solid rgba(6, 182, 212, 0.2); background: linear-gradient(145deg, #ffffff, #ecfeff);">
                                <div class="mb-1 d-flex justify-content-center">
                                    <div class="rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px; background: rgba(6, 182, 212, 0.1);">
                                        <i class="bi bi-cpu text-info" style="font-size: 15px;"></i>
                                    </div>
                                </div>
                                <div class="fw-bold text-dark mb-1" style="font-size: 10px; line-height: 1.2;">IoT Integrasi</div>
                                <div class="text-muted" style="font-size: 8px; line-height: 1.1;">Koneksi API</div>
                            </a>
                        </div>
                        
                        <!-- LLM API Key -->
                        <div class="col-md-4 col-4">
                            <a href="llm/index.php" class="suggestion-card d-block p-2 rounded-3 text-center h-100 text-decoration-none shadow-sm position-relative overflow-hidden" style="border: 1px solid rgba(245, 158, 11, 0.2); background: linear-gradient(145deg, #ffffff, #fffbeb);">
                                <div class="mb-1 d-flex justify-content-center">
                                    <div class="rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px; background: rgba(245, 158, 11, 0.1);">
                                        <i class="bi bi-key text-warning" style="font-size: 15px;"></i>
                                    </div>
                                </div>
                                <div class="fw-bold text-dark mb-1" style="font-size: 10px; line-height: 1.2;">LLM API Key</div>
                                <div class="text-muted" style="font-size: 8px; line-height: 1.1;">AI kustom</div>
                            </a>
                        </div>
                        
                        <!-- Modul Template -->
                        <div class="col-md-4 col-4">
                            <a href="#" onclick="$('.mode-btn[data-mode=\'rpp_maker\']').click(); return false;" class="suggestion-card d-block p-2 rounded-3 text-center h-100 text-decoration-none shadow-sm position-relative overflow-hidden" style="border: 1px solid rgba(239, 68, 68, 0.2); background: linear-gradient(145deg, #ffffff, #fef2f2);">
                                <div class="mb-1 d-flex justify-content-center">
                                    <div class="rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px; background: rgba(239, 68, 68, 0.1);">
                                        <i class="bi bi-file-earmark-text text-danger" style="font-size: 15px;"></i>
                                    </div>
                                </div>
                                <div class="fw-bold text-dark mb-1" style="font-size: 10px; line-height: 1.2;">Modul Template</div>
                                <div class="text-muted" style="font-size: 8px; line-height: 1.1;">Template siap pakai</div>
                            </a>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <?php if($history_count > 0 && !empty($result_history)): ?>
                <?php while($h = mysqli_fetch_assoc($result_history)): ?>
                    <div class="msg-container">
                        <div class="avatar avatar-user"><i class="bi bi-person-circle"></i></div>
                        <div class="u-msg"><?= htmlspecialchars($h['user_message']) ?></div>
                    </div>
                    <div class="msg-container">
                        <div class="avatar avatar-ai"><?= $logo_html ?></div>
                        <div class="a-msg render-markdown"><?= htmlspecialchars($h['ai_response']) ?></div>
                    </div>
                <?php endwhile; ?>
                <?php mysqli_stmt_close($stmt_history); ?>
            <?php endif; ?>
        </div>

        <div class="input-container">
            <div class="input-inner">
                <div id="preview-container">
                    <div id="file-chips-wrap"></div>
                    <span id="file-count-badge" style="display:none;"></span>
                </div>

                <div class="mode-selector">
                    <button class="mode-btn active" type="button" data-mode="cepat"><i class="bi bi-lightning-charge-fill"></i> Cepat</button>
                    <button class="mode-btn" type="button" data-mode="penalaran"><i class="bi bi-diagram-3-fill"></i> Penalaran</button>
                    <button class="mode-btn" type="button" data-mode="pro"><i class="bi bi-robot"></i> Pro Expert</button>
                    <!-- TOMBOL RPP MAKER -->
                    <button class="mode-btn" type="button" data-mode="rpp_maker"><i class="bi bi-file-earmark-word-fill"></i> Template Modul</button>
                </div>

                <form id="chat-form">
                    <div class="input-wrapper" id="input-wrapper-box">
                        <label for="image-input" style="cursor:pointer; padding-bottom: 8px;" title="Upload Gambar/Dokumen">
                            <i class="bi bi-paperclip text-secondary fs-5" id="icon-paperclip"></i>
                            <input type="file" id="image-input" accept="image/*, .pdf, .docx, .xlsx, .txt, .csv, .html, .php, .ino, .css, .js" multiple style="display:none;">
                        </label>
                        <i class="bi bi-mic text-secondary fs-5" id="start-mic" style="cursor:pointer; padding-bottom: 8px;" title="Voice Input"></i>
                        <textarea id="user-input" rows="1" placeholder="Tanya sesuatu..." required></textarea>
                        <button type="submit" class="btn p-0 text-primary" id="btn-send" title="Kirim" style="padding-bottom: 8px;"><i class="bi bi-send-fill fs-5"></i></button>
                        <button type="button" class="btn p-0 text-secondary" id="btn-stop" title="Berhenti" style="padding-bottom: 8px; display: none;"><i class="bi bi-stop-fill fs-3"></i></button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Modal Premium Feature -->
<div class="modal fade" id="modalPremiumFeature" tabindex="-1" aria-hidden="true" style="z-index: 99999;">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4 border-0 shadow">
            <div class="modal-body text-center p-5">
                <div class="mb-4">
                    <div class="bg-warning bg-opacity-10 text-warning rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 80px; height: 80px;">
                        <i class="bi bi-star-fill text-warning" style="font-size: 2.5rem;"></i>
                    </div>
                </div>
                <h4 class="fw-bold text-dark mb-3">SILAHKAN LOGIN</h4>
                <p class="text-muted mb-4">Maaf, untuk menggunakan fitur Upload File, Voice, Live, dan Mode Pro/Penalaran, Anda harus Login atau Registrasi terlebih dahulu.</p>
                <div class="d-flex justify-content-center gap-3">
                    <button type="button" class="btn btn-light rounded-pill px-4 fw-bold" data-bs-dismiss="modal">Tutup</button>
                    <a href="auth/login_page.php" class="btn btn-primary rounded-pill px-4 shadow-sm fw-bold">Login Sekarang</a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ===== MODAL ERROR NOTIFIKASI ===== -->
<div class="modal fade" id="modalErrorNotif" tabindex="-1" aria-hidden="true" style="z-index: 99999;">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 420px;">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 20px; overflow: hidden;">
            <div class="modal-body p-0">
                <!-- Header gradient -->
                <div id="errorNotifHeader" class="d-flex align-items-center gap-3 p-4" style="background: linear-gradient(135deg, #ff6b6b, #ee5a24);">
                    <div class="d-flex align-items-center justify-content-center rounded-circle" style="width:52px;height:52px;background:rgba(255,255,255,0.25);flex-shrink:0;">
                        <i id="errorNotifIcon" class="bi bi-exclamation-triangle-fill" style="font-size:1.5rem;color:white;"></i>
                    </div>
                    <div>
                        <div class="fw-bold text-white" style="font-size:1rem;" id="errorNotifTitle">Oops, Ada Kendala!</div>
                        <div class="text-white" style="font-size:11px;opacity:0.85;">Sistem Xieqa AI</div>
                    </div>
                </div>
                <!-- Body -->
                <div class="p-4">
                    <p class="text-secondary mb-4" style="font-size:14px;line-height:1.7;" id="errorNotifMsg">
                        Maaf, terjadi kendala saat menghubungi AI. Silakan coba beberapa saat lagi.
                    </p>
                    <div class="d-flex gap-2 justify-content-end">
                        <button type="button" class="btn btn-light rounded-pill px-4 fw-semibold" data-bs-dismiss="modal" style="font-size:13px;">Tutup</button>
                        <button type="button" class="btn rounded-pill px-4 fw-bold text-white" id="errorNotifRetryBtn" data-bs-dismiss="modal" style="font-size:13px;background:linear-gradient(135deg,#667eea,#764ba2);border:none;"
                            onclick="document.getElementById('user-input').focus()">
                            <i class="bi bi-arrow-clockwise me-1"></i> Coba Lagi
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- ===== END MODAL ERROR NOTIFIKASI ===== -->

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- MAMMOTH.JS UNTUK BACA DOCX -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.21/mammoth.browser.min.js"></script>
<!-- PDF.JS UNTUK BACA PDF -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script>
    if (typeof pdfjsLib !== 'undefined') {
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
    }
</script>

<script>
    let activeMode = 'cepat';
    let extractedDocxText = ''; 
    const synth = window.speechSynthesis;
    
    function toggleSidebar() {
        const isMobile = window.innerWidth <= 991;
        const sidebar = $('#sidebar');
        if (isMobile) sidebar.toggleClass('active');
        else sidebar.toggleClass('collapsed');
    }

    $('#toggleSidebar, #overlay, #closeSidebarDesktop').click(toggleSidebar);

    $('.mode-btn').click(function(e) {
        if (isGuest && $(this).data('mode') !== 'cepat') {
            e.preventDefault(); e.stopPropagation();
            new bootstrap.Modal(document.getElementById('modalPremiumFeature')).show();
            return false;
        }

        $('.mode-btn').removeClass('active');
        $(this).addClass('active');
        activeMode = $(this).data('mode');
        
        if (activeMode === 'rpp_maker') {
            $('#user-input').attr('placeholder', 'Ketik Topik / Judul Materi yang ingin diisikan ke template...');
            $('#image-input').attr('accept', '.docx'); 
            $('#icon-paperclip').removeClass('text-secondary').addClass('text-danger');
            $('#input-wrapper-box').css('border', '1px solid #fda4af');
            new bootstrap.Modal(document.getElementById('modalRppUpload')).show();
        } else {
            $('#user-input').attr('placeholder', 'Tanya sesuatu...');
            $('#image-input').attr('accept', 'image/*, .pdf, .docx, .xlsx, .txt, .csv, .html, .php, .ino, .css, .js');
            $('#icon-paperclip').removeClass('text-danger').addClass('text-secondary');
            $('#input-wrapper-box').css('border', '1px solid transparent');
        }
    });

    $('#user-input').on('input', function() {
        this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';
    });

    $('#user-input').on('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); $('#chat-form').submit(); }
    });

    // === FILE QUEUE: Akumulasi file satu per satu seperti Gemini ===
    let fileQueue = []; // Array of File objects, urutan terjaga

    function getFileIcon(file) {
        if (file.type.startsWith('image/')) return 'bi-image text-success';
        if (file.name.endsWith('.pdf'))    return 'bi-file-earmark-pdf text-danger';
        if (file.name.endsWith('.docx') || file.name.endsWith('.doc')) return 'bi-file-earmark-word text-primary';
        if (file.name.endsWith('.xlsx') || file.name.endsWith('.xls')) return 'bi-file-earmark-excel text-success';
        if (file.name.endsWith('.txt') || file.name.endsWith('.csv')) return 'bi-file-earmark-text text-secondary';
        return 'bi-file-earmark-code text-warning';
    }

    function renderFileChips() {
        const $wrap = $('#file-chips-wrap');
        $wrap.empty();
        if (fileQueue.length === 0) {
            $('#preview-container').fadeOut(150);
            $('#file-count-badge').hide();
            return;
        }
        $('#preview-container').show();
        fileQueue.forEach(function(file, idx) {
            const isImage = file.type.startsWith('image/');
            const shortName = file.name.length > 18 ? file.name.substring(0,15) + '...' : file.name;
            const $chip = $(`
                <div class="file-chip${isImage?' is-image':''}" data-idx="${idx}" title="${file.name}">
                    <i class="bi ${getFileIcon(file)} chip-icon"></i>
                    <span class="chip-name">${shortName}</span>
                    <span class="chip-remove" data-idx="${idx}"><i class="bi bi-x-lg"></i></span>
                </div>
            `);
            $wrap.append($chip);
        });
        // Badge jumlah jika > 1
        if (fileQueue.length > 1) {
            $('#file-count-badge').text(fileQueue.length + ' file siap dikirim').show();
        } else {
            $('#file-count-badge').hide();
        }
    }

    // Hapus satu file dari antrian
    $(document).on('click', '.chip-remove', function(e) {
        e.stopPropagation();
        const idx = parseInt($(this).data('idx'));
        // Jika file yang dihapus adalah template RPP (index 0), reset juga docx text
        if (idx === 0 && activeMode === 'rpp_maker') extractedDocxText = '';
        fileQueue.splice(idx, 1);
        renderFileChips();
        // Reset input agar bisa pilih file yang sama lagi
        $('#image-input').val('');
    });

    $('#image-input').change(function() {
        const newFiles = Array.from(this.files);
        if (!newFiles.length) return;

        // Cegah duplikat berdasarkan nama + ukuran
        newFiles.forEach(function(newFile) {
            const isDuplicate = fileQueue.some(f => f.name === newFile.name && f.size === newFile.size);
            if (isDuplicate) return;

            if (fileQueue.length >= 10) {
                alert('Maksimal 10 file. File "' + newFile.name + '" tidak ditambahkan.');
                return;
            }

            // Cek total ukuran
            const currentTotal = fileQueue.reduce((s, f) => s + f.size, 0);
            if ((currentTotal + newFile.size) > 25 * 1024 * 1024) {
                alert('Batas 25MB tercapai. File "' + newFile.name + '" tidak ditambahkan.');
                return;
            }

            // Jika mode RPP, baca docx pertama sebagai template
            if (activeMode === 'rpp_maker' && newFile.name.endsWith('.docx') && extractedDocxText === '') {
                const reader = new FileReader();
                reader.onload = function(event) {
                    mammoth.convertToHtml({arrayBuffer: event.target.result})
                        .then(function(result) { extractedDocxText = result.value; })
                        .catch(function(err) { alert('Gagal membaca template DOCX: ' + err.message); });
                };
                reader.readAsArrayBuffer(newFile);
            }

            fileQueue.push(newFile);
        });

        // Reset input value agar file yang sama bisa dipilih lagi
        setTimeout(() => {
            $('#image-input').val('');
            renderFileChips();
        }, 10);
    });

    function resetFile() {
        fileQueue = [];
        extractedDocxText = '';
        $('#image-input').val('');
        $('#file-chips-wrap').empty();
        $('#file-count-badge').hide();
        $('#preview-container').fadeOut(150);
    }
    function scrollBottom() { const b = document.getElementById('chat-box'); b.scrollTop = b.scrollHeight; }

    // --- TOGGLE MAP DARK MODE ---
    $(document).on('click', '.btn-map-dark-toggle', function() {
        let $frame = $(this).closest('.xieqa-map-container').find('iframe');
        $frame.toggleClass('xieqa-map-dark-filter');
        if($frame.hasClass('xieqa-map-dark-filter')) {
            $(this).html('<i class="bi bi-sun-fill text-warning"></i> Terang');
        } else {
            $(this).html('<i class="bi bi-moon-fill text-primary"></i> Gelap');
        }
    });

    // --- GEOLOCATION TRACKER (DIPINDAH KE ON-DEMAND / REQ_GPS) ---
    window.userLocationString = "";
    
    const isGuest = <?= $is_guest ? 'true' : 'false' ?>;
    let guestChatCount = <?= $is_guest ? $_SESSION['guest_count'] : 0 ?>;

    if (isGuest) {
        $('.mode-btn[data-mode!="cepat"], #start-mic, .bi-paperclip, .btn-live-gemini').css({'opacity': '0.5', 'cursor': 'not-allowed'});
        
        $(document).on('click', '#start-mic, label[for="image-input"], .btn-live-gemini', function(e) {
            e.preventDefault(); e.stopPropagation();
            new bootstrap.Modal(document.getElementById('modalPremiumFeature')).show();
            return false;
        });
    }

    // Setup Keamanan DOMPurify Khusus (Hanya Izinkan Iframe YouTube & Google Maps)
    DOMPurify.addHook('uponSanitizeElement', function(node, data) {
        if (data.tagName === 'iframe') {
            const src = node.getAttribute('src') || '';
            if (!src.startsWith('https://www.youtube.com/embed/') && 
                !src.startsWith('https://www.youtube-nocookie.com/embed/') && 
                !src.startsWith('https://maps.google.com/maps')) {
                node.parentNode.removeChild(node);
            }
        }
    });

    // Fungsi untuk mendownload tabel
    window.downloadTable = function(button, type) {
        const table = $(button).closest('.table-wrapper').find('table')[0];
        let html = table.outerHTML;
        
        let prefix = "";
        let suffix = "</body></html>";
        let fileName = "Tabel_" + new Date().getTime();
        
        if (type === 'excel') {
            prefix = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export Excel</title></head><body>";
            fileName += ".xls";
        } else if (type === 'word') {
            prefix = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export Word</title><style>table {width:100%; border-collapse: collapse;} th, td {border: 1px solid black; padding: 5px;}</style></head><body>";
            fileName += ".doc";
        }
        
        const blob = new Blob(['\ufeff', prefix + html + suffix], { type: 'application/vnd.ms-' + type });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    };

    function parseMsg(el, voice = false) {
        let t = el.text().replace(/<user_query>[\s\S]*?<\/user_query>/g, '');
        let rawHtml = marked.parse(t);
        
        // Izinkan tag iframe beserta atribut bawaannya
        let safeHtml = DOMPurify.sanitize(rawHtml, {
            ADD_TAGS: ['iframe'],
            ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling', 'src', 'width', 'height', 'marginwidth', 'marginheight']
        });
        
        el.html(safeHtml);

        el.find('pre code').each((i, b) => {
            hljs.highlightElement(b);
            const $pre = $(b).parent();
            // Deteksi nama bahasa dari class hljs
            const langClass = b.className.match(/language-(\S+)/);
            const langName  = langClass ? langClass[1].replace('language-', '') : 'code';
            const lineCount = b.textContent.split('\n').filter(l => l.trim()).length;

            // Bungkus dalam struktur baru: header + scroll-area
            $pre.wrap('<div class="code-scroll-area"></div>');
            $pre.parent().wrap('<div class="code-container"></div>');

            // Inject header bar di ATAS scroll-area
            const $container = $pre.closest('.code-container');
            $container.prepend(`
                <div class="code-header">
                    <span class="code-lang-label">${langName}</span>
                    <div class="code-actions">
                        <span class="code-line-count">${lineCount} baris</span>
                        <button class="save-btn" type="button" data-lang="${langName}">
                            <i class="bi bi-download"></i> Simpan
                        </button>
                        <button class="copy-btn" type="button">
                            <i class="bi bi-clipboard"></i> Salin
                        </button>
                    </div>
                </div>
            `);
        });

        // Parse tabel
        el.find('table').each((i, t) => {
            const $table = $(t);
            $table.wrap('<div class="table-scroll"></div>');
            $table.parent().wrap('<div class="table-wrapper"></div>');
            
            const $wrapper = $table.closest('.table-wrapper');
            $wrapper.prepend(`
                <div class="table-header-toolbar">
                    <div class="table-title">
                        <i class="bi bi-table text-primary"></i> Data Tabel
                    </div>
                    <div class="table-actions">
                        <button class="btn-table-action btn-excel" type="button" onclick="downloadTable(this, 'excel')">
                            <i class="bi bi-file-earmark-excel-fill"></i> Excel
                        </button>
                        <button class="btn-table-action btn-word" type="button" onclick="downloadTable(this, 'word')">
                            <i class="bi bi-file-earmark-word-fill"></i> Word
                        </button>
                    </div>
                </div>
            `);
        });

       // el.removeClass('render-markdown');
    }

    // FUNGSI KOMPRESI GAMBAR (Klien)
    async function compressImage(file, maxWidth = 1024, maxHeight = 1024, quality = 0.7) {
        return new Promise((resolve) => {
            if (!file.type.match(/image.*/)) {
                resolve(file);
                return;
            }
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function(event) {
                const img = new Image();
                img.src = event.target.result;
                img.onload = function() {
                    const canvas = document.createElement('canvas');
                    let width = img.width;
                    let height = img.height;

                    if (width > height) {
                        if (width > maxWidth) { height *= maxWidth / width; width = maxWidth; }
                    } else {
                        if (height > maxHeight) { width *= maxHeight / height; height = maxHeight; }
                    }

                    canvas.width = width;
                    canvas.height = height;
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, width, height);

                    canvas.toBlob(function(blob) {
                        resolve(new File([blob], file.name, { type: 'image/jpeg', lastModified: Date.now() }));
                    }, 'image/jpeg', quality);
                };
            };
        });
    }

    $(document).ready(() => { $('.render-markdown').each(function() { parseMsg($(this)); }); scrollBottom(); });

    $('#chat-form').on('submit', async function(e) {
        e.preventDefault();

        if (isGuest && guestChatCount >= 5) {
            $('body').addClass('limit-reached'); 
            $('#limitModal').modal('show');
            return false;
        }

        const msg = $('#user-input').val().trim();
        if (!window.silentSubmit) {
            window.lastUserMessage = msg; // Simpan pesan asli
        }

        // Gunakan fileQueue (akumulatif) bukan fileInput.files
        if (fileQueue.length > 0) {
            let totalSizeMB = fileQueue.reduce((s, f) => s + f.size, 0) / 1024 / 1024;
            if (totalSizeMB > 25) {
                alert('Total ukuran file terlalu besar. Maksimal 25MB keseluruhan.');
                resetFile(); 
                return; 
            }
        }

        if(!msg && fileQueue.length === 0) return;

        if (activeMode === 'rpp_maker') {
            if (extractedDocxText === '') {
                alert('Tolong lampirkan file Template DOCX terlebih dahulu agar AI tahu format yang digunakan sekolah/kampus Anda.');
                return false;
            }
        }

        // Tampilkan nama file di bubble user (urutan terjaga)
        if (!window.silentSubmit) {
            let userHtml = `<div class="msg-container"><div class="avatar avatar-user"><i class="bi bi-person"></i></div><div class="u-msg">${msg.replace(/\n/g, '<br>')}`;
            if (fileQueue.length === 1) {
                userHtml += `<div class="mt-2 text-primary small"><i class="bi bi-paperclip"></i> ${fileQueue[0].name}</div>`;
            } else if (fileQueue.length > 1) {
                const fileNames = fileQueue.map((f,i) => `<span style="opacity:0.8">${i+1}.</span> ${f.name}`).join('<br>');
                userHtml += `<div class="mt-2 text-primary small"><i class="bi bi-paperclip"></i> ${fileQueue.length} file:<br>${fileNames}</div>`;
            }
            userHtml += `</div></div>`;
            $('#chat-box').append(userHtml); $('.empty-state').fadeOut();
        } else {
            window.silentSubmit = false; // reset flag
        }

        const loadingId = 'loading-' + Date.now();
        $('#chat-box').append(`
            <div class="msg-container" id="${loadingId}">
                <div class="avatar avatar-ai"><?= $logo_html ?></div>
                <div class="typing-indicator">
                    <div class="typing-dots-wrap">
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                    </div>
                    <span class="typing-label">Sedang mengetik...</span>
                </div>
            </div>
        `);
        scrollBottom();

        // --- COOLDOWN TIMER: Ubah warna indikator berdasarkan lama menunggu ---
        const $indicator = $(`#${loadingId} .typing-indicator`);
        const cooldownWarnTimer = setTimeout(() => {
            $indicator.addClass('typing-cooldown-warn');
            let warnText = 'Sedang merumuskan jawaban terbaik...';
            if (activeMode === 'rpp_maker') warnText = 'Membaca template & materi Anda...';
            else if (activeMode === 'penalaran') warnText = 'Mengumpulkan data & menyusun logika...';
            else if (activeMode === 'pro') warnText = 'Menelusuri referensi ahli secara akurat...';
            $indicator.find('.typing-label').text(warnText);
            scrollBottom();
        }, 15000); // 15 detik → kuning
        
        const cooldownBusyTimer = setTimeout(() => {
            $indicator.removeClass('typing-cooldown-warn').addClass('typing-cooldown-busy');
            let busyText = 'Sistem memproses...';
            if (activeMode === 'rpp_maker') busyText = 'Menyusun teks panjang, mohon tunggu...';
            else if (activeMode === 'penalaran') busyText = 'Berpikir mendalam...';
            else if (activeMode === 'pro') busyText = 'Menganalisa data kompleks...';
            else busyText = 'Jaringan lambat atau server sibuk...';
            $indicator.find('.typing-label').text(busyText);
            scrollBottom();
        }, 45000); // 45 detik → merah

        let currentSessionId = "<?= $js_session_id ?>";
        let formData = new FormData();
        
        let ajaxUrl = 'api/gemini.php'; 
        
        if (activeMode === 'rpp_maker') {
            ajaxUrl = 'api/routerrpp.php';
            formData.append('topik', msg);
            formData.append('template', extractedDocxText);
            formData.append('materi_text', extractedMateriText);
            formData.append('session_id', currentSessionId);
        } else {
            formData.append('pesan', msg); 
            formData.append('mode', activeMode);
            formData.append('session_id', currentSessionId); 
            
            // Sertakan data lokasi jika ada
            if (window.userLocationString) {
                formData.append('user_location', window.userLocationString);
            }
            // Kirim fileQueue secara berurutan (file pertama dibaca pertama)
            if (fileQueue.length > 0) {
                for (let i = 0; i < fileQueue.length; i++) {
                    let fileUpload = fileQueue[i];
                    if (fileUpload.type.match(/image.*/)) {
                        fileUpload = await compressImage(fileUpload, 1024, 1024, 0.7);
                    }
                    formData.append('gambar[]', fileUpload);
                }
            }
        }

        if (!window.location.search.includes("session=")) {
            window.history.pushState(null, '', '?session=' + currentSessionId);
        }

        $('#user-input').val('').css('height', 'auto'); 
        resetFile();

        $('#btn-send').hide();
        $('#btn-stop').show();

        if (window.currentChatRequest) {
            window.currentChatRequest.abort();
        }

        window.currentChatRequest = $.ajax({
            url: ajaxUrl, 
            type: 'POST', 
            data: formData, 
            processData: false, 
            contentType: false, 
            dataType: 'json',
            success: function(res) {
                clearTimeout(cooldownWarnTimer);
                clearTimeout(cooldownBusyTimer);
                $(`#${loadingId}`).remove(); 
                if (isGuest) guestChatCount++;
                
                $('#btn-stop').hide();
                $('#btn-send').show();

                if(res.jawaban) {
                    let fullText = res.jawaban;
                    
                    // --- INTERCEPT REQ_GPS ---
                    let gpsMatch = fullText.match(/\[REQ_GPS\](.*)/s);
                    if (gpsMatch) {
                        let gpsMsg = gpsMatch[1].trim();
                        Swal.fire({
                            title: 'Izin Lokasi',
                            html: `<div style="font-size: 13px; color: #666;">${gpsMsg}</div>`,
                            icon: 'info',
                            width: '320px',
                            padding: '1.2rem',
                            showCancelButton: true,
                            confirmButtonText: '<i class="bi bi-geo-alt-fill"></i> Izinkan',
                            cancelButtonText: 'Nanti Saja',
                            customClass: {
                                popup: 'rounded-4 shadow',
                                title: 'fs-6 fw-bold mb-0',
                                confirmButton: 'btn btn-primary btn-sm rounded-pill px-3 mx-1',
                                cancelButton: 'btn btn-light btn-sm rounded-pill px-3 mx-1 text-secondary border'
                            },
                            buttonsStyling: false
                        }).then((result) => {
                            if (result.isConfirmed) {
                                if (navigator.geolocation) {
                                    Swal.fire({
                                        title: 'Melacak Lokasi...',
                                        text: 'Mohon tunggu sebentar...',
                                        allowOutsideClick: false,
                                        didOpen: () => { Swal.showLoading() }
                                    });
                                    navigator.geolocation.getCurrentPosition(function(position) {
                                        let lat = position.coords.latitude;
                                        let lon = position.coords.longitude;
                                        $.getJSON(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lon}&zoom=14`, function(data) {
                                            if(data && data.display_name) {
                                                window.userLocationString = lat + "," + lon + " (" + data.display_name + ")";
                                            } else {
                                                window.userLocationString = lat + "," + lon;
                                            }
                                            Swal.close();
                                            $('#user-input').val(window.lastUserMessage);
                                            window.silentSubmit = true;
                                            $('#chat-form').submit();
                                        }).fail(function() {
                                            window.userLocationString = lat + "," + lon;
                                            Swal.close();
                                            $('#user-input').val(window.lastUserMessage);
                                            window.silentSubmit = true;
                                            $('#chat-form').submit();
                                        });
                                    }, function(error) {
                                        Swal.fire('Gagal', 'Akses lokasi ditolak atau GPS tidak aktif.', 'error');
                                    });
                                }
                            }
                        });
                        return; // Hentikan render pesan [REQ_GPS] ke layar chat
                    }
                    // --- END INTERCEPT ---

                    const $ai = $(`<div class="msg-container"><div class="avatar avatar-ai"><?= $logo_html ?></div><div class="a-msg"></div></div>`);
                    $('#chat-box').append($ai); 
                    
                    let currentText = "";
                    let charIndex = 0;
                    let $msgBox = $ai.find('.a-msg');
                    
                    // Kecepatan mengetik dinamis berdasarkan panjang teks
                    let charsToType = Math.max(1, Math.floor(fullText.length / 250));
                    
                    function typeWriter() {
                        if (charIndex < fullText.length) {
                            currentText += fullText.substring(charIndex, charIndex + charsToType);
                            charIndex += charsToType;
                            
                            // Parse markdown sementara untuk rendering (tanpa highlight blok kode)
                            let rawHtml = marked.parse(currentText);
                            let safeHtml = DOMPurify.sanitize(rawHtml, {
                                ADD_TAGS: ['iframe'],
                                ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling', 'src', 'width', 'height', 'marginwidth', 'marginheight']
                            });
                            
                            $msgBox.html(safeHtml + '<span class="typing-cursor"></span>');
                            scrollBottom();
                            
                            setTimeout(typeWriter, 15);
                        } else {
                            // Teks selesai, kembalikan ke full text dan lakukan parseMsg untuk rendering highlight kode secara utuh
                            $msgBox.text(fullText); 
                            parseMsg($msgBox, true);
                            scrollBottom();
                            
                            // --- TAMBAHAN FITUR DOWNLOAD WORD UNTUK MODE RPP ---
                            if (activeMode === 'rpp_maker') {
                                const btnDownload = $(`<button class="btn btn-outline-danger mt-3 mb-2 px-3 py-2 fw-bold shadow-sm d-flex align-items-center gap-2" style="border-radius: 8px; font-size: 14px;">
                                    <i class="bi bi-file-earmark-word-fill fs-5"></i> Simpan Hasil ke Ms. Word
                                </button>`);
                                
                                btnDownload.click(function() {
                                    const contentHtml = $msgBox.html();
                                    const preHtml = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>RPP AI</title><style>table {width:100%; border-collapse: collapse;} th, td {border: 1px solid black; padding: 5px;}</style></head><body>";
                                    const postHtml = "</body></html>";
                                    const html = preHtml + contentHtml + postHtml;
                                    const blob = new Blob(['\ufeff', html], { type: 'application/msword' });
                                    const url = URL.createObjectURL(blob);
                                    const a = document.createElement('a');
                                    a.href = url;
                                    a.download = 'Hasil_RPP_AI_' + new Date().getTime() + '.doc';
                                    document.body.appendChild(a);
                                    a.click();
                                    document.body.removeChild(a);
                                    URL.revokeObjectURL(url);
                                });
                                $msgBox.append(btnDownload);
                            }
                        }
                    }
                    typeWriter();
                } else {
                    // Deteksi pesan error / busy dari server — tampilkan sebagai popup ramah
                    let popupTitle  = 'Oops, Ada Kendala!';
                    let popupMsg    = 'Maaf, terjadi kendala saat menghubungi AI. Silakan coba beberapa saat lagi.';
                    let popupIcon   = 'bi-exclamation-triangle-fill';
                    let headerColor = 'linear-gradient(135deg, #ff6b6b, #ee5a24)';

                    if (res.status === 'busy' || (res.message && res.message.toLowerCase().includes('sibuk'))) {
                        popupTitle  = 'Server AI Sedang Sibuk 🙏';
                        popupMsg    = 'Server AI sedang melayani banyak pengguna sekaligus. Silakan tunggu sebentar dan coba lagi dalam 1–2 menit.';
                        popupIcon   = 'bi-hourglass-split';
                        headerColor = 'linear-gradient(135deg, #f093fb, #f5576c)';
                    } else if (res.message) {
                        popupMsg = res.message;
                    } else if (res.error) {
                        popupMsg = res.error;
                    }

                    $('#errorNotifTitle').text(popupTitle);
                    $('#errorNotifMsg').text(popupMsg);
                    $('#errorNotifIcon').attr('class', 'bi ' + popupIcon).css('font-size','1.5rem').css('color','white');
                    $('#errorNotifHeader').css('background', headerColor);
                    new bootstrap.Modal(document.getElementById('modalErrorNotif')).show();
                }
                scrollBottom();
            },
            error: function(xhr, status, error) {
                clearTimeout(cooldownWarnTimer);
                clearTimeout(cooldownBusyTimer);
                $(`#${loadingId}`).remove();

                $('#btn-stop').hide();
                $('#btn-send').show();

                if (status === 'abort') {
                    return; // Jangan tampilkan error jika dibatalkan oleh user
                }

                // Tampilkan popup ramah — jangan bocorkan detail teknis ke user
                let popupTitle  = 'Koneksi Terputus';
                let popupMsg    = 'Tidak dapat menghubungi server. Periksa koneksi internet Anda dan coba lagi.';
                let popupIcon   = 'bi-wifi-off';
                let headerColor = 'linear-gradient(135deg, #4facfe, #00f2fe)';

                if (xhr.status === 0) {
                    popupMsg = 'Tidak ada koneksi internet. Pastikan perangkat Anda terhubung ke jaringan.';
                } else if (xhr.status >= 500) {
                    popupTitle  = 'Server Sedang Gangguan';
                    popupMsg    = 'Server sedang mengalami gangguan sementara. Tim kami sedang bekerja memulihkannya. Silakan coba lagi nanti.';
                    popupIcon   = 'bi-cloud-slash-fill';
                    headerColor = 'linear-gradient(135deg, #f093fb, #f5576c)';
                } else if (xhr.status === 429) {
                    popupTitle  = 'Terlalu Banyak Permintaan';
                    popupMsg    = 'Anda mengirim terlalu banyak pesan dalam waktu singkat. Mohon tunggu sebentar sebelum mencoba lagi.';
                    popupIcon   = 'bi-speedometer2';
                    headerColor = 'linear-gradient(135deg, #f7971e, #ffd200)';
                }

                $('#errorNotifTitle').text(popupTitle);
                $('#errorNotifMsg').text(popupMsg);
                $('#errorNotifIcon').attr('class', 'bi ' + popupIcon).css('font-size','1.5rem').css('color','white');
                $('#errorNotifHeader').css('background', headerColor);
                new bootstrap.Modal(document.getElementById('modalErrorNotif')).show();
                scrollBottom();
            }
        });
    });

    $('#btn-stop').click(function() {
        if (window.currentChatRequest) {
            window.currentChatRequest.abort();
            window.currentChatRequest = null;
        }
        $('#btn-stop').hide();
        $('#btn-send').show();
        $('.typing-indicator').closest('.msg-container').remove();
    });

    const Rec = window.SpeechRecognition || window.webkitSpeechRecognition;
    if(Rec) {
        const r = new Rec();
        r.lang = 'id-ID';
        r.continuous = true;
        r.interimResults = false;
        
        let voiceTimer;

        $('#start-mic').click(() => {
            if ($('#start-mic').hasClass('text-danger')) {
                r.stop();
            } else {
                r.start();
            }
        });

        r.onstart = () => {
            $('#start-mic').removeClass('text-secondary').addClass('text-danger');
            resetVoiceTimer();
        };

        r.onresult = (e) => {
            let final_transcript = '';
            for (let i = e.resultIndex; i < e.results.length; ++i) {
                if (e.results[i].isFinal) {
                    final_transcript += e.results[i][0].transcript;
                }
            }
            if (final_transcript) {
                const currentVal = $('#user-input').val();
                $('#user-input').val(currentVal + (currentVal ? ' ' : '') + final_transcript);
                $('#user-input').trigger('input'); 
            }
            resetVoiceTimer();
        };

        r.onend = () => {
            $('#start-mic').removeClass('text-danger').addClass('text-secondary');
            clearTimeout(voiceTimer);
        };

        function resetVoiceTimer() {
            clearTimeout(voiceTimer);
            voiceTimer = setTimeout(() => {
                r.stop();
            }, 5000); 
        }
    }

    const csrfToken = $('meta[name="csrf-token"]').attr('content');

    $('#btn-del').click(function() {
        Swal.fire({
            title: '<strong style="font-size: 16px;">Hapus Seluruh Histori?</strong>',
            html: '<span style="font-size: 13px; color: #64748b;">Aksi ini tidak bisa dibatalkan.</span>',
            icon: 'warning',
            width: '320px',
            padding: '1.2em',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#94a3b8',
            confirmButtonText: '<span style="font-size: 13px;">Ya, Hapus</span>',
            cancelButtonText: '<span style="font-size: 13px;">Batal</span>',
            backdrop: `rgba(0,0,0,0.4)`,
            customClass: {
                popup: 'rounded-4 shadow-sm border',
                icon: 'mt-0 mb-2'
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('api/clear_history.php', { csrf_token: csrfToken }, () => location.reload());
            }
        });
    });

    $(document).on('click', '.btn-delete-session', function(e) {
        e.preventDefault();
        const sessionIdToDelete = $(this).data('session');
        const csrfToken = $('meta[name="csrf-token"]').attr('content');
        let isCurrentSession = ("<?= $active_session ?>" === sessionIdToDelete);
        
        Swal.fire({
            title: '<strong style="font-size: 16px;">Hapus Obrolan Ini?</strong>',
            html: '<span style="font-size: 13px; color: #64748b;">Obrolan akan dihapus permanen.</span>',
            icon: 'warning',
            width: '320px',
            padding: '1.2em',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#94a3b8',
            confirmButtonText: '<span style="font-size: 13px;">Ya, Hapus</span>',
            cancelButtonText: '<span style="font-size: 13px;">Batal</span>',
            backdrop: `rgba(0,0,0,0.4)`,
            customClass: {
                popup: 'rounded-4 shadow-sm border',
                icon: 'mt-0 mb-2'
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('api/clear_history.php', { csrf_token: csrfToken, session_id: sessionIdToDelete }, function(res) {
                    if (res.status === 'success') {
                        if (isCurrentSession) window.location.href = 'index.php';
                        else location.reload();
                    } else {
                        Swal.fire('Gagal', 'Gagal menghapus: ' + res.message, 'error');
                    }
                });
            }
        });
    });

    $(document).on('click', '.copy-btn', function() {
        const $container = $(this).closest('.code-container');
        const codeText   = $container.find('code').text();
        const $btn = $(this);
        navigator.clipboard.writeText(codeText).then(() => {
            $btn.addClass('copied').html('<i class="bi bi-check-lg"></i> Tersalin!');
            setTimeout(() => { $btn.removeClass('copied').html('<i class="bi bi-clipboard"></i> Salin'); }, 2500);
        }, () => {
            $btn.html('<i class="bi bi-x-circle"></i> Gagal');
            setTimeout(() => { $btn.html('<i class="bi bi-clipboard"></i> Salin'); }, 2000);
        });
    });

    $(document).on('click', '.save-btn', function() {
        const $container = $(this).closest('.code-container');
        const codeText   = $container.find('code').text();
        const lang       = $(this).data('lang') || 'txt';
        
        const extMap = {
            'html': 'html', 'php': 'php', 'javascript': 'js', 'js': 'js', 'python': 'py', 'py': 'py',
            'css': 'css', 'sql': 'sql', 'arduino': 'ino', 'ino': 'ino', 'cpp': 'cpp', 'c': 'c', 'java': 'java',
            'json': 'json', 'markdown': 'md', 'md': 'md', 'bash': 'sh', 'sh': 'sh', 'xml': 'xml'
        };
        let ext = extMap[lang.toLowerCase()] || 'txt';

        // Smart Check: Jika terdeteksi C++ tapi ada setup/loop, ubah ke .ino (Arduino)
        if (ext === 'cpp' || ext === 'c' || ext === 'txt') {
            if (codeText.includes('void setup') || codeText.includes('void loop')) {
                ext = 'ino';
            }
        }

        const filename = 'code_' + new Date().getTime() + '.' + ext;

        const blob = new Blob([codeText], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    });

    $(document).on('submit', '#form-setting-akun', function(e) {
        e.preventDefault();
        const emailBaru    = $('#editEmail').val().trim();
        const usernameBaru = $('#editUsername').val().trim();
        const passwordBaru = $('#editPassword').val().trim();
        const btnSave = $('#btn-save-setting');
        const token = $('meta[name="csrf-token"]').attr('content');
        btnSave.html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Menyimpan...').prop('disabled', true);
        $.ajax({
            url: 'api/update_account.php', type: 'POST',
            data: { csrf_token: token, email: emailBaru, username: usernameBaru, password: passwordBaru },
            dataType: 'json',
            success: function(res) {
                if(res.status === 'success') { alert('Profil berhasil diperbarui!'); location.reload(); }
                else { alert('Gagal: ' + res.message); btnSave.html('Simpan Perubahan').prop('disabled', false); }
            },
            error: function() { alert('Terjadi kesalahan pada server.'); btnSave.html('Simpan Perubahan').prop('disabled', false); }
        });
    });

    $(document).on('submit', '#form-pengajuan-broadcast', function(e) {
        e.preventDefault();
        const emailGuru = $('#inputEmailGuru').val().trim().toLowerCase();
        const btnSubmit = $('#btn-submit-broadcast');
        if (!emailGuru.includes('belajar.id') && !emailGuru.includes('guru.id')) {
            $('#inputEmailGuru').addClass('is-invalid'); return false;
        } else { $('#inputEmailGuru').removeClass('is-invalid'); }
        const token = $('meta[name="csrf-token"]').attr('content');
        btnSubmit.html('<span class="spinner-border spinner-border-sm me-2"></span>Mengirim...').prop('disabled', true);
        $.ajax({
            url: 'api/ajukan_broadcast.php', type: 'POST',
            data: { csrf_token: token, email: emailGuru }, dataType: 'json',
            success: function(res) {
                if(res.status === 'success') {
                    $('#area-input-email').slideUp(300, function() { $('#area-input-otp').slideDown(300); $('#inputOTP').focus(); });
                } else { alert('Gagal: ' + res.message); btnSubmit.html('Kirim Kode OTP').prop('disabled', false); }
            },
            error: function() { alert('Terjadi kesalahan server.'); btnSubmit.html('Kirim Kode OTP').prop('disabled', false); }
        });
    });

    $(document).on('submit', '#form-verifikasi-otp', function(e) {
        e.preventDefault();
        const otp = $('#inputOTP').val().trim();
        const emailGuru = $('#inputEmailGuru').val().trim().toLowerCase();
        const btnSubmitOtp = $('#btn-submit-otp');
        const token = $('meta[name="csrf-token"]').attr('content');
        btnSubmitOtp.html('<span class="spinner-border spinner-border-sm me-2"></span>Memverifikasi...').prop('disabled', true);
        $.ajax({
            url: 'api/verifikasi_otp.php', type: 'POST',
            data: { csrf_token: token, otp: otp, email: emailGuru }, dataType: 'json',
            success: function(res) {
                if(res.status === 'success') { alert('Verifikasi Berhasil! Pengajuan Anda sedang ditinjau Admin.'); location.reload(); }
                else { alert('Gagal: ' + res.message); btnSubmitOtp.html('Verifikasi & Ajukan').prop('disabled', false); }
            },
            error: function() { alert('Terjadi kesalahan server saat memverifikasi kode.'); btnSubmitOtp.html('Verifikasi & Ajukan').prop('disabled', false); }
        });
    });
</script>

<!-- ===== LIMIT MODAL ===== -->
<div class="modal fade" id="limitModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered" style="max-width:380px;">
        <div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
            <div class="modal-body text-center p-5">
                <div class="mb-3"><i class="bi bi-lock-fill text-danger" style="font-size:3rem;"></i></div>
                <h5 class="fw-bold">Batas Percobaan Tamu</h5>
                <p class="text-muted small">Anda telah menggunakan 5 percobaan gratis. Daftar atau login untuk melanjutkan tanpa batas.</p>
                <a href="auth/login_page.php" class="btn btn-primary rounded-pill fw-bold px-4 w-100 mb-2">Login Sekarang</a>
                <button class="btn btn-outline-secondary rounded-pill px-4 w-100" data-bs-dismiss="modal" onclick="$('body').removeClass('limit-reached')">Nanti</button>
            </div>
        </div>
    </div>
</div>

<!-- ===== MODAL BROADCAST ===== -->
<div class="modal fade" id="modalBroadcast" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
            <div class="modal-header bg-light border-bottom-0 p-4 pb-2">
                <h5 class="modal-title fw-bold text-dark"><i class="bi bi-shield-lock text-success me-2"></i> Verifikasi Pendidik</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4 pt-3">
                <div id="area-input-email">
                    <p class="text-secondary small mb-4">Fitur Broadcast Tugas hanya untuk Pendidik. Masukkan email resmi Anda, kami akan mengirimkan 6 digit kode verifikasi.</p>
                    <form id="form-pengajuan-broadcast">
                        <div class="mb-3">
                            <label class="form-label text-muted small fw-bold">Email Belajar.id / Guru.id</label>
                            <input type="email" class="form-control rounded-3" id="inputEmailGuru" placeholder="nama@belajar.id" required>
                            <div class="invalid-feedback">Gunakan email belajar.id atau guru.id</div>
                        </div>
                        <button type="submit" class="btn btn-success rounded-pill fw-bold w-100" id="btn-submit-broadcast">Kirim Kode OTP</button>
                    </form>
                </div>
                <div id="area-input-otp" style="display:none;">
                    <p class="text-secondary small mb-4">Kode OTP telah dikirim ke email Anda. Masukkan kode tersebut di bawah.</p>
                    <form id="form-verifikasi-otp">
                        <div class="mb-3">
                            <label class="form-label text-muted small fw-bold">Kode OTP (6 Digit)</label>
                            <input type="text" class="form-control rounded-3 text-center fw-bold fs-4 letter-spacing-3" id="inputOTP" maxlength="6" placeholder="------" required>
                        </div>
                        <button type="submit" class="btn btn-success rounded-pill fw-bold w-100" id="btn-submit-otp">Verifikasi & Ajukan</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if(!$is_guest): ?>
<div class="modal fade" id="settingModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
            <div class="modal-header bg-light border-bottom-0 p-4 pb-2">
                <h5 class="modal-title fw-bold text-dark"><i class="bi bi-gear text-primary me-2"></i> Pengaturan Akun</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4 pt-3">
                <form id="form-setting-akun">
                    <div class="mb-3">
                        <label class="form-label text-muted small fw-bold">Email Terdaftar</label>
                        <input type="email" class="form-control rounded-3" id="editEmail" value="<?= htmlspecialchars($email_user) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted small fw-bold">Username (Untuk Login)</label>
                        <input type="text" class="form-control rounded-3" id="editUsername" value="<?= htmlspecialchars($username_user) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted small fw-bold">Password Baru</label>
                        <input type="password" class="form-control rounded-3" id="editPassword" placeholder="Isi jika ingin ganti password...">
                        <small class="text-muted" style="font-size:11px;">*Kosongkan jika tidak ingin mengubah password.</small>
                    </div>
                    <div class="d-grid mt-4">
                        <button type="submit" class="btn btn-primary rounded-pill py-2 fw-bold shadow-sm" id="btn-save-setting">Simpan Perubahan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- ===== MODAL TEMPLATE MODUL (ELEGAN v2) ===== -->
<div class="modal fade" id="modalRppUpload" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered" style="max-width:460px;margin:auto;padding:12px;">
        <div class="modal-content border-0 shadow-lg" style="border-radius:22px;overflow:hidden;">
            <div style="background:linear-gradient(135deg,#e11d48 0%,#9f1239 100%);padding:22px 24px 20px;position:relative;">
                <button type="button" class="btn-close btn-close-white" style="position:absolute;top:14px;right:16px;opacity:.85;" onclick="cancelRppModal()" data-bs-dismiss="modal"></button>
                <div class="d-flex align-items-center gap-3">
                    <div style="background:rgba(255,255,255,.15);border-radius:14px;padding:10px 13px;">
                        <i class="bi bi-file-earmark-word-fill text-white" style="font-size:1.6rem;"></i>
                    </div>
                    <div>
                        <h6 class="text-white fw-bold mb-0" style="font-size:.93rem;">Mode Template Modul</h6>
                        <small style="color:rgba(255,255,255,.72);font-size:11px;">AI isi template sesuai format & materi Anda</small>
                    </div>
                </div>
            </div>
            <div style="padding:20px 22px 0;max-height:65vh;overflow-y:auto;">
                <!-- Upload 1: Template (Wajib) -->
                <div class="mb-1">
                    <div class="d-flex align-items-center gap-2 mb-2">
                        <div style="min-width:22px;height:22px;background:#fff1f2;border-radius:50%;display:flex;align-items:center;justify-content:center;"><span style="font-size:10px;font-weight:800;color:#e11d48;">1</span></div>
                        <span class="fw-bold" style="font-size:13px;color:#111;">Template Modul</span>
                        <span class="badge rounded-pill ms-1" style="background:#fff1f2;color:#e11d48;font-size:10px;">Wajib · .docx</span>
                    </div>
                    <div id="rpp-dropzone" style="border:2px dashed #fda4af;border-radius:14px;padding:16px;text-align:center;cursor:pointer;background:#fff5f6;transition:all .25s;"
                        onclick="document.getElementById('image-input').click();"
                        onmouseenter="this.style.background='#ffe4e8'" onmouseleave="if(!rppFileReady)this.style.background='#fff5f6'">
                        <i class="bi bi-file-earmark-word" style="font-size:1.8rem;color:#e11d48;"></i>
                        <p class="fw-bold mb-0 mt-1" style="font-size:13px;color:#1f2937;">Klik pilih file template</p>
                        <small style="color:#9ca3af;font-size:11px;"><strong>.docx</strong> &nbsp;|&nbsp; Maks. 5MB</small>
                    </div>
                    <div id="rpp-file-info" class="mt-2 d-none">
                        <div class="d-flex align-items-center gap-2 px-3 py-2 rounded-3" style="background:#f0fdf4;border:1px solid #bbf7d0;">
                            <i class="bi bi-file-earmark-check-fill text-success" style="flex-shrink:0;"></i>
                            <span id="rpp-fname" class="fw-semibold small text-success text-truncate" style="max-width:260px;"></span>
                            <button type="button" class="btn p-0 ms-auto" onclick="clearRppFile()"><i class="bi bi-x-circle text-secondary"></i></button>
                        </div>
                    </div>
                </div>
                <hr style="border-color:#f1f5f9;margin:14px 0;">
                <!-- Upload 2: Materi (Opsional) -->
                <div class="mb-1">
                    <div class="d-flex align-items-center gap-2 mb-1">
                        <div style="min-width:22px;height:22px;background:#eff6ff;border-radius:50%;display:flex;align-items:center;justify-content:center;"><span style="font-size:10px;font-weight:800;color:#2563eb;">2</span></div>
                        <span class="fw-bold" style="font-size:13px;color:#111;">File Materi / Teori</span>
                        <span class="badge rounded-pill ms-1" style="background:#eff6ff;color:#2563eb;font-size:10px;">Opsional · PDF / DOCX</span>
                    </div>
                    <p style="font-size:12px;color:#6b7280;margin:0 0 10px 30px;">
                        Jika diisi → AI <strong>mengambil isi file ini</strong> sebagai sumber materi.<br>
                        Jika kosong → AI <strong>generate dari pengetahuannya sendiri</strong>.
                    </p>
                    <div id="materi-dropzone" style="border:2px dashed #bfdbfe;border-radius:14px;padding:14px;text-align:center;cursor:pointer;background:#f0f9ff;transition:all .25s;"
                        onclick="document.getElementById('materi-input').click();"
                        onmouseenter="this.style.background='#dbeafe'" onmouseleave="if(!materiFileReady)this.style.background='#f0f9ff'">
                        <i class="bi bi-cloud-arrow-up" style="font-size:1.7rem;color:#3b82f6;"></i>
                        <p class="fw-bold mb-0 mt-1" style="font-size:13px;color:#1e3a5f;">Klik pilih file materi</p>
                        <small style="color:#93c5fd;font-size:11px;"><strong>PDF</strong> atau <strong>DOCX</strong> &nbsp;|&nbsp; Maks. 10MB</small>
                    </div>
                    <div id="materi-progress" class="mt-2 d-none">
                        <div class="d-flex align-items-center gap-2 px-3 py-2 rounded-3" style="background:#eff6ff;border:1px solid #bfdbfe;">
                            <div class="spinner-border spinner-border-sm text-primary" role="status" style="width:16px;height:16px;"></div>
                            <small class="text-primary fw-semibold">Membaca isi file materi...</small>
                        </div>
                    </div>
                    <div id="materi-file-info" class="mt-2 d-none">
                        <div class="d-flex align-items-center gap-2 px-3 py-2 rounded-3" style="background:#eff6ff;border:1px solid #93c5fd;">
                            <i class="bi bi-file-earmark-check-fill text-primary" style="flex-shrink:0;"></i>
                            <div style="flex:1;min-width:0;">
                                <span id="materi-fname" class="fw-semibold small text-primary text-truncate d-block" style="max-width:240px;"></span>
                                <small id="materi-chars" style="font-size:10px;color:#6b7280;"></small>
                            </div>
                            <button type="button" class="btn p-0 ms-1" onclick="clearMateriFile()"><i class="bi bi-x-circle text-secondary"></i></button>
                        </div>
                    </div>
                </div>
                <input type="file" id="materi-input" accept=".pdf,.docx" style="display:none;">
            </div>
            <div style="padding:16px 22px 22px;display:flex;gap:10px;border-top:1px solid #f1f5f9;margin-top:6px;">
                <button type="button" class="btn btn-light rounded-pill fw-semibold" style="flex:1;font-size:13px;" onclick="cancelRppModal()" data-bs-dismiss="modal">Batal</button>
                <button type="button" id="btn-rpp-mulai" class="btn rounded-pill fw-bold disabled"
                    style="flex:1.6;font-size:13px;background:linear-gradient(135deg,#e11d48,#9f1239);color:#fff;border:none;opacity:.45;transition:all .2s;"
                    onclick="startRppMode()">
                    <i class="bi bi-arrow-right-circle-fill me-1"></i> Mulai Tulis Topik
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let rppFileReady    = false;
let materiFileReady = false;
let extractedMateriText = '';

// FILE 1: Template DOCX
document.getElementById('image-input').addEventListener('change', function() {
    if (activeMode !== 'rpp_maker' || !this.files.length) return;
    const file = this.files[0];
    if (!file.name.toLowerCase().endsWith('.docx')) { alert('Harap pilih file .docx'); this.value=''; return; }
    rppFileReady = true;
    document.getElementById('rpp-fname').textContent = file.name;
    document.getElementById('rpp-file-info').classList.remove('d-none');
    const dz = document.getElementById('rpp-dropzone');
    dz.style.borderColor='#4ade80'; dz.style.background='#f0fdf4';
    checkEnableRppBtn();
});

// FILE 2: Materi (PDF / DOCX)
document.getElementById('materi-input').addEventListener('change', function() {
    if (!this.files.length) return;
    const file = this.files[0];
    const isPdf  = file.name.toLowerCase().endsWith('.pdf');
    const isDocx = file.name.toLowerCase().endsWith('.docx');
    if (!isPdf && !isDocx) { alert('Pilih file PDF atau DOCX.'); this.value=''; return; }
    if (file.size > 10*1024*1024) { alert('File materi maksimal 10MB.'); this.value=''; return; }
    document.getElementById('materi-progress').classList.remove('d-none');
    document.getElementById('materi-file-info').classList.add('d-none');
    document.getElementById('materi-dropzone').style.opacity = '0.5';
    const reader = new FileReader();
    reader.onload = function(e) {
        if (isPdf) {
            pdfjsLib.getDocument({ data: new Uint8Array(e.target.result) }).promise
                .then(pdf => {
                    let pages = [];
                    for (let i=1; i<=pdf.numPages; i++)
                        pages.push(pdf.getPage(i).then(p=>p.getTextContent()).then(tc=>tc.items.map(s=>s.str).join(' ')));
                    Promise.all(pages).then(texts => { extractedMateriText=texts.join('\n\n'); showMateriReady(file.name, extractedMateriText.length); });
                }).catch(()=>{ alert('Gagal baca PDF.'); clearMateriFile(); });
        } else {
            mammoth.extractRawText({ arrayBuffer: e.target.result })
                .then(r=>{ extractedMateriText=r.value; showMateriReady(file.name,r.value.length); })
                .catch(()=>{ alert('Gagal baca DOCX materi.'); clearMateriFile(); });
        }
    };
    reader.readAsArrayBuffer(file);
});

function showMateriReady(fname, chars) {
    materiFileReady = true;
    document.getElementById('materi-progress').classList.add('d-none');
    document.getElementById('materi-fname').textContent = fname;
    document.getElementById('materi-chars').textContent = chars.toLocaleString() + ' karakter terbaca ✓';
    document.getElementById('materi-file-info').classList.remove('d-none');
    const dz = document.getElementById('materi-dropzone');
    dz.style.borderColor='#93c5fd'; dz.style.background='#dbeafe'; dz.style.opacity='1';
}
function clearMateriFile() {
    materiFileReady = false; extractedMateriText = '';
    document.getElementById('materi-input').value = '';
    document.getElementById('materi-file-info').classList.add('d-none');
    document.getElementById('materi-progress').classList.add('d-none');
    document.getElementById('materi-fname').textContent = '';
    document.getElementById('materi-chars').textContent = '';
    const dz = document.getElementById('materi-dropzone');
    dz.style.borderColor='#bfdbfe'; dz.style.background='#f0f9ff'; dz.style.opacity='1';
}
function clearRppFile() {
    rppFileReady = false; extractedDocxText = '';
    document.getElementById('image-input').value = '';
    document.getElementById('rpp-file-info').classList.add('d-none');
    document.getElementById('rpp-fname').textContent = '';
    const dz = document.getElementById('rpp-dropzone');
    dz.style.borderColor='#fda4af'; dz.style.background='#fff5f6';
    document.getElementById('preview-container').style.display = 'none';
    const btn = document.getElementById('btn-rpp-mulai');
    btn.classList.add('disabled'); btn.style.opacity='.45';
}
function checkEnableRppBtn() {
    const btn = document.getElementById('btn-rpp-mulai');
    if (rppFileReady) { btn.classList.remove('disabled'); btn.style.opacity='1'; }
}
function cancelRppModal() {
    $('.mode-btn').removeClass('active');
    $('.mode-btn[data-mode="cepat"]').addClass('active');
    activeMode = 'cepat';
    $('#user-input').attr('placeholder','Tanya sesuatu...');
    $('#image-input').attr('accept','image/*, .pdf, .docx, .xlsx, .txt, .csv');
    $('#icon-paperclip').removeClass('text-danger').addClass('text-secondary');
    $('#input-wrapper-box').css('border','1px solid transparent');
    clearRppFile(); clearMateriFile();
}
function startRppMode() {
    const modal = bootstrap.Modal.getInstance(document.getElementById('modalRppUpload'));
    if (modal) modal.hide();
    setTimeout(() => document.getElementById('user-input').focus(), 380);
}
</script>

<!-- ===== PWA INSTALL MODAL ===== -->
<div class="modal fade" id="pwaInstallModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 360px;">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 20px; overflow: hidden; background: var(--bg-chat);">
            <div class="text-center position-relative" style="background: var(--gemini-gradient); padding: 40px 20px 20px;">
                <div class="bg-white rounded-circle shadow-sm d-inline-flex align-items-center justify-content-center" style="width: 70px; height: 70px; position: absolute; bottom: -35px; left: 50%; transform: translateX(-50%); padding: 2px; overflow: hidden;">
                    <?= $logo_html ?>
                </div>
            </div>
            <div class="modal-body text-center" style="padding: 50px 24px 30px;">
                <h5 class="fw-bold mb-2">Install Aplikasi AI</h5>
                <p class="text-muted small mb-4">Akses lebih cepat tanpa perlu mengetik URL! Install aplikasi SEKARANG dan nikmati pengalaman AI terbaik di perangkat Anda (Tombol Nanti Saja akan langsung menuju web).</p>
                <button type="button" id="btn-install-pwa" class="btn btn-primary rounded-pill fw-bold w-100 py-2 mb-2 shadow-sm" style="background: var(--gemini-blue);">
                    <i class="bi bi-download me-2"></i> Install App Sekarang
                </button>
                <button type="button" class="btn btn-light rounded-pill fw-bold w-100 py-2 text-secondary" data-bs-dismiss="modal" onclick="sessionStorage.setItem('pwaDismissed', 'true');">
                    Nanti Saja
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// PWA Installation script
let deferredPrompt;
let pwaModalInstance;

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('./sw.js')
            .then(reg => console.log('Service Worker terdaftar di scope:', reg.scope))
            .catch(err => console.log('Service Worker gagal didaftarkan:', err));
    });
}

window.addEventListener('beforeinstallprompt', (e) => {
    // Cegah kemunculan JIKA user sudah install (tercatat di localStorage)
    // ATAU user menekan Nanti Saja pada TAB/SESI ini (tercatat di sessionStorage)
    if (localStorage.getItem('pwaDismissed') === 'true' || sessionStorage.getItem('pwaDismissed') === 'true') {
        return;
    }
    
    // Cegah kemunculan bila pengguna BUKA aplikasi yang sudah di-install
    if (window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true) {
        return;
    }

    // Mencegah mini-infobar muncul di mobile
    e.preventDefault();
    deferredPrompt = e;
    
    // Tampilkan modal custom kita jika pengguna belum install app
    setTimeout(() => {
        if (!document.getElementById('pwaInstallModal').classList.contains('show')) {
            pwaModalInstance = new bootstrap.Modal(document.getElementById('pwaInstallModal'));
            pwaModalInstance.show();
        }
    }, 1000);
});

document.getElementById('btn-install-pwa').addEventListener('click', async () => {
    if (deferredPrompt) {
        // Hide modal
        if (pwaModalInstance) pwaModalInstance.hide();
        
        // Tampilkan prompt natif bawaan browser
        deferredPrompt.prompt();
        
        // Tunggu user klik install atau cancel di prompt natif
        const { outcome } = await deferredPrompt.userChoice;
        console.log('User response the install prompt:', outcome);
        
        if (outcome === 'accepted') {
            localStorage.setItem('pwaDismissed', 'true');
        }
        
        deferredPrompt = null;
    }
});

// Tutup celah jika berhasil install dari sumber lain
window.addEventListener('appinstalled', () => {
    localStorage.setItem('pwaDismissed', 'true');
});
</script>

</body>
</html>



