<?php
session_start();
include '../config/database.php';

// Cek Login (Sederhana)
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login_page.php");
    exit;
}

// Cek Proteksi Akun PRO — ambil dari DB (session tidak menyimpan status_akun)
$stmt_cek = mysqli_prepare($conn, "SELECT status_akun, role FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt_cek, "s", $_SESSION['user_id']);
mysqli_stmt_execute($stmt_cek);
$data_cek = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt_cek));
mysqli_stmt_close($stmt_cek);

$status_akun = strtolower(trim($data_cek['status_akun'] ?? 'free'));
$role = strtolower(trim($data_cek['role'] ?? 'siswa'));

if ($status_akun !== 'pro' && $role !== 'admin') {
    echo "<script>
        alert('MOHON MAAF: Fitur Aistem Autokoding eksklusif HANYA untuk pengguna Akun PRO (Atau Admin). Silakan Upgrade akun Anda untuk bisa memprogram web & IoT secara otomatis!');
        window.location.href = '../upgrade_pro.php';
    </script>";
    exit;
}

$user_id = $_SESSION['user_id'];
$nama_siswa = $_SESSION['nama'] ?? 'User';

// Ambil cfg untuk nama aplikasi ringan
$cfg = mysqli_fetch_assoc(mysqli_query($conn, "SELECT nama_aplikasi, logo FROM settings WHERE id = 1"));
$nama_app = htmlspecialchars($cfg['nama_aplikasi']);
$logo_html = (!empty($cfg['logo']) && file_exists('../' . $cfg['logo'])) ? '<img src="../' . $cfg['logo'] . '" alt="Logo" style="width: 100%; height: 100%; border-radius: 5px; object-fit: cover;">' : '<i class="bi bi-robot brand-icon"></i>';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Agent Koding - <?= $nama_app ?></title>
    
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;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 {
            --bg-light: #f0f4ff;
            --panel-bg: #ffffff;
            --border-color: #e2e8f0;
            --accent-primary: #4f46e5;
            --accent-secondary: #7c3aed;
            --accent-glow: rgba(79, 70, 229, 0.2);
            --text-main: #1e293b;
            --text-muted: #64748b;
            --text-sub: #94a3b8;
            --shadow-sm: 0 2px 8px rgba(79,70,229,0.08);
            --shadow-md: 0 8px 30px rgba(79,70,229,0.12);
            --shadow-lg: 0 20px 50px rgba(79,70,229,0.15);
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--bg-light);
            background-image:
                radial-gradient(at 10% 0%, rgba(99, 102, 241, 0.12) 0px, transparent 55%),
                radial-gradient(at 90% 10%, rgba(167, 139, 250, 0.1) 0px, transparent 50%),
                radial-gradient(at 50% 100%, rgba(59, 130, 246, 0.08) 0px, transparent 50%);
            background-attachment: fixed;
            color: var(--text-main);
            min-height: 100vh;
            margin: 0;
            display: flex;
            flex-direction: column;
        }

        .glass-header {
            background: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            border-bottom: 1px solid var(--border-color);
            box-shadow: 0 2px 12px rgba(79,70,229,0.07);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .brand-logo {
            font-weight: 700;
            font-size: 1.2rem;
            color: var(--text-main);
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .brand-icon {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-size: 1.5rem;
        }

        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            max-width: 1000px;
            margin: 20px auto;
            width: 100%;
            height: calc(100vh - 150px);
            background: var(--panel-bg);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            box-shadow: var(--shadow-lg);
            overflow: hidden;
        }

        .chat-header {
            padding: 15px 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-weight: 600;
            background: linear-gradient(135deg, #f8f7ff, #f0f4ff);
            color: var(--text-main);
        }

        .chat-body {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 20px;
            scroll-behavior: smooth;
            background: #fafbff;
        }

        .chat-body::-webkit-scrollbar { width: 6px; }
        .chat-body::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 10px; }
        .chat-body::-webkit-scrollbar-thumb { background: #c7d2fe; border-radius: 10px; }
        .chat-body::-webkit-scrollbar-thumb:hover { background: #a5b4fc; }

        .chat-bubble {
            max-width: 85%;
            padding: 16px 22px;
            border-radius: 20px;
            font-size: 0.95rem;
            line-height: 1.6;
            animation: fadeIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px) scale(0.98); }
            to { opacity: 1; transform: translateY(0) scale(1); }
        }

        .chat-user {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            align-self: flex-end;
            border-bottom-right-radius: 4px;
            box-shadow: 0 8px 20px rgba(79, 70, 229, 0.25);
        }

        .chat-ai {
            background: #ffffff;
            border: 1px solid #e8edff;
            color: var(--text-main);
            align-self: flex-start;
            border-bottom-left-radius: 4px;
            box-shadow: 0 4px 15px rgba(79,70,229,0.08);
        }

        .chat-system {
            background: linear-gradient(90deg, rgba(99,102,241,0.08), rgba(167,139,250,0.08));
            border: 1px solid rgba(99,102,241,0.2);
            color: #4f46e5;
            font-weight: 500;
            align-self: center;
            border-radius: 16px;
            padding: 12px 25px;
            font-size: 0.85rem;
            text-align: center;
            width: 80%;
            margin: 10px 0;
            letter-spacing: 0.3px;
        }

        .chat-footer {
            padding: 20px;
            border-top: 1px solid var(--border-color);
            background: #f8f7ff;
            display: flex;
            gap: 15px;
            align-items: flex-end;
            position: relative;
        }

        .chat-input {
            flex: 1;
            background: #ffffff;
            border: 1.5px solid #e2e8f0;
            color: var(--text-main);
            padding: 16px 20px;
            border-radius: 16px;
            outline: none;
            resize: none;
            min-height: 58px;
            max-height: 150px;
            font-family: inherit;
            transition: all 0.3s;
            box-shadow: 0 2px 8px rgba(79,70,229,0.05);
        }

        .chat-input::placeholder { color: #a0aec0; }

        .chat-input:focus {
            border-color: #818cf8;
            box-shadow: 0 0 0 3px rgba(99,102,241,0.12);
        }

        .chat-input:disabled {
            background: #f8fafc;
            border-color: #e2e8f0;
            color: #a0aec0;
            cursor: not-allowed;
        }

        .btn-send {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            border: none;
            width: 58px;
            height: 58px;
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            font-size: 1.3rem;
            box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3);
            cursor: pointer;
        }

        .btn-send:hover {
            transform: translateY(-2px) scale(1.02);
            box-shadow: 0 12px 25px rgba(79, 70, 229, 0.4);
        }

        .btn-send:disabled {
            background: #e2e8f0;
            color: #a0aec0;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        /* Markdown Styling inside Chat */
        .markdown-body pre {
            margin: 15px 0;
            padding: 0;
            background: transparent !important;
            border: none;
        }

        /* ===================== CODE BLOCK ===================== */
        .code-container {
            position: relative;
            margin: 14px 0;
            border-radius: 12px;
            overflow: hidden;
            background: #1e1e2e;
            border: 1px solid #313244;
            display: flex;
            flex-direction: column;
        }
        .code-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 6px 12px;
            background: #181825;
            border-bottom: 1px solid #313244;
            flex-shrink: 0;
        }
        .code-lang-label {
            font-size: 11px;
            font-weight: 600;
            color: #cba6f7;
            text-transform: uppercase;
            font-family: 'Consolas', monospace;
        }
        .code-actions { display: flex; gap: 6px; align-items: center; }
        .copy-btn {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 4px 10px;
            font-size: 12px;
            font-weight: 500;
            background: rgba(255,255,255,0.08);
            color: #cdd6f4;
            border: 1px solid rgba(255,255,255,0.12);
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .copy-btn:hover { background: rgba(255,255,255,0.15); color: #fff; }
        .copy-btn.copied { background: rgba(166,227,161,0.15); border-color: rgba(166,227,161,0.4); color: #a6e3a1; }
        .code-scroll-area {
            overflow-x: hidden;
            overflow-y: auto;
            max-height: 500px;
        }
        .code-scroll-area::-webkit-scrollbar { width: 5px; }
        .code-scroll-area::-webkit-scrollbar-track { background: #1e1e2e; }
        .code-scroll-area::-webkit-scrollbar-thumb { background: #45475a; border-radius: 3px; }
        .code-scroll-area::-webkit-scrollbar-thumb:hover { background: #cba6f7; }
        .markdown-body code {
            font-family: 'Consolas', 'Courier New', monospace;
            font-size: 0.9em;
            background: #eef2ff;
            color: #4338ca;
            padding: 2px 6px;
            border-radius: 4px;
        }
        pre code {
            display: block;
            padding: 1.1em 1.2em !important;
            font-size: 0.85rem;
            color: #cdd6f4;
            border-radius: 0 !important;
            white-space: pre-wrap;
            word-break: break-all;
            overflow-wrap: break-word;
            line-height: 1.65;
            background: #1e1e2e !important;
        }
        .code-line-count { font-size: 10px; color: #6c7086; font-family: monospace; }
        /* ===================== END CODE BLOCK ===================== */

        .markdown-body h1, .markdown-body h2, .markdown-body h3 {
            color: var(--text-main);
            margin-top: 1em;
            margin-bottom: 0.5em;
            font-weight: 600;
        }
        .markdown-body p { color: var(--text-main); }
        .markdown-body li { color: var(--text-main); }
        .markdown-body table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        .markdown-body th, .markdown-body td {
            border: 1px solid #e2e8f0;
            padding: 8px 12px;
            color: var(--text-main);
        }
        .markdown-body th {
            background: #eef2ff;
            color: #4338ca;
            font-weight: 600;
        }
        .markdown-body td { background: #ffffff; }
        .markdown-body a { color: #4f46e5; }

        .typing-indicator {
            display: none;
            align-self: flex-start;
            padding: 12px 20px;
            background: #ffffff;
            border: 1px solid #e8edff;
            border-radius: 16px;
            margin-bottom: 10px;
            box-shadow: 0 4px 15px rgba(79,70,229,0.08);
            color: var(--text-main);
        }

        .radar-spinner {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            border: 2px solid transparent;
            border-top-color: #4f46e5;
            border-bottom-color: #7c3aed;
            animation: spin 1s cubic-bezier(0.68, -0.55, 0.265, 1.55) infinite;
            margin-right: 12px;
        }
        @keyframes spin { 100% { transform: rotate(360deg); } }

        .pulsing-text {
            animation: pulse-text 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            color: var(--text-main);
        }
        @keyframes pulse-text {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        /* ===================== PROMPT GENERATOR MODAL ===================== */
        .modal-prompt-helper {
            background: rgba(248, 250, 252, 0.95);
            backdrop-filter: blur(10px);
        }
        .modal-prompt-helper .modal-content {
            border-radius: 24px;
            border: 1px solid var(--border-color);
            box-shadow: var(--shadow-lg);
            overflow: hidden;
        }
        .modal-prompt-helper .modal-header {
            background: linear-gradient(135deg, #f8f7ff, #f0f4ff);
            border-bottom: 1px solid var(--border-color);
            padding: 20px 25px;
        }
        .prompt-config-card {
            background: #ffffff;
            padding: 1.5rem;
            border-radius: 1.2rem;
            border: 1px solid #e2e8f0;
            margin-bottom: 1rem;
        }
        .prompt-section-title {
            font-size: 1.1rem;
            font-weight: 700;
            margin-bottom: 1.2rem;
            color: var(--accent-primary);
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .prompt-form-group { margin-bottom: 1rem; }
        .prompt-form-group label {
            display: block;
            font-size: 0.85rem;
            font-weight: 600;
            margin-bottom: 6px;
            color: var(--text-main);
        }
        .prompt-input, .prompt-select, .prompt-textarea {
            width: 100%;
            padding: 10px 14px;
            border-radius: 10px;
            border: 1.5px solid #e2e8f0;
            background: #fff;
            font-size: 0.9rem;
            transition: all 0.2s;
        }
        .prompt-input:focus {
            border-color: var(--accent-primary);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
            outline: none;
        }
        .field-list-container {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .field-item-row {
            display: flex;
            gap: 8px;
            align-items: center;
        }
        .btn-remove-field {
            background: #fff5f5;
            color: #ef4444;
            border: 1px solid #fee2e2;
            padding: 8px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .btn-remove-field:hover { background: #fee2e2; }
        .btn-add-field {
            background: transparent;
            color: var(--accent-primary);
            border: 1px dashed var(--accent-primary);
            padding: 8px;
            border-radius: 10px;
            font-size: 0.85rem;
            font-weight: 600;
            width: 100%;
            margin-top: 8px;
            transition: all 0.2s;
        }
        .btn-add-field:hover { background: rgba(79, 70, 229, 0.05); }
        .prompt-checkbox-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
            gap: 10px;
            background: #f8fafc;
            padding: 12px;
            border-radius: 12px;
            border: 1px solid #e2e8f0;
        }
        .prompt-checkbox-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 0.82rem;
            cursor: pointer;
            color: var(--text-main);
        }
        .prompt-result-area {
            background: #0f172a;
            color: #94a3b8;
            padding: 20px;
            border-radius: 14px;
            font-family: 'Consolas', monospace;
            font-size: 0.85rem;
            line-height: 1.6;
            white-space: pre-wrap;
            height: 100%;
            min-height: 400px;
            max-height: 600px;
            overflow-y: auto;
            border: 1px solid #334155;
            position: relative;
        }
        .prompt-result-area::-webkit-scrollbar { width: 6px; }
        .prompt-result-area::-webkit-scrollbar-thumb { background: #334155; border-radius: 10px; }
        
        .prompt-actions-header {
            display: flex;
            gap: 12px;
            padding: 12px;
            background: #1e293b;
            border-bottom: 1px solid #334155;
            border-top-left-radius: 14px;
            border-top-right-radius: 14px;
            justify-content: center;
        }
        .btn-prompt-action {
            padding: 10px 20px;
            border-radius: 12px;
            font-size: 0.88rem;
            font-weight: 700;
            border: none;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            gap: 8px;
            letter-spacing: 0.3px;
        }
        .btn-copy-prompt { 
            background: rgba(255, 255, 255, 0.1); 
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        .btn-use-prompt { 
            background: linear-gradient(135deg, #4f46e5, #7c3aed); 
            color: white;
            box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3);
        }
        .btn-copy-prompt:hover { 
            background: rgba(255, 255, 255, 0.2); 
            transform: translateY(-2px);
        }
        .btn-use-prompt:hover { 
            filter: brightness(1.1);
            transform: translateY(-2px) scale(1.02);
            box-shadow: 0 8px 20px rgba(79, 70, 229, 0.4);
        }
        @keyframes soft-breath {
            0% { transform: scale(1); filter: brightness(1); box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3); }
            50% { transform: scale(1.02); filter: brightness(1.15); box-shadow: 0 8px 25px rgba(79, 70, 229, 0.5); }
            100% { transform: scale(1); filter: brightness(1); box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3); }
        }
        .btn-prompt-helper-main {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white !important;
            border: 1px solid rgba(255, 255, 255, 0.2);
            padding: 8px 20px;
            font-size: 0.82rem;
            font-weight: 700;
            animation: soft-breath 3s ease-in-out infinite;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 10px;
            letter-spacing: 0.3px;
            box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3);
        }
        .btn-prompt-helper-main:hover {
            transform: translateY(-2px) scale(1.05);
            filter: brightness(1.2);
            box-shadow: 0 12px 30px rgba(79, 70, 229, 0.5);
            animation-play-state: paused;
        }
        .quick-replies {
            display: none;
            gap: 12px;
            padding: 12px 20px;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-top: 1px solid var(--border-color);
            justify-content: center;
            animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            z-index: 5;
        }
        @keyframes slideUp {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        .btn-quick {
            padding: 10px 24px;
            border-radius: 14px;
            font-size: 0.88rem;
            font-weight: 700;
            border: none;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }
        .btn-quick-yes { background: linear-gradient(135deg, #10b981, #059669); color: white; }
        .btn-quick-no { background: #ffffff; color: #ef4444; border: 1px solid #fee2e2; }
        .btn-quick:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(0,0,0,0.1); }
        .btn-quick-yes:hover { filter: brightness(1.1); }
        .btn-quick-no:hover { background: #fff5f5; }
    </style>
</head>
<body>

    <header class="glass-header py-3">
        <div class="container d-flex justify-content-between align-items-center">
            <a href="../index.php" class="brand-logo">
                <span style="width: 28px; height: 28px; display: inline-block;">
                    <?= $logo_html ?>
                </span>
                Agent Koding
            </a>
            <div class="d-flex align-items-center gap-3">
                <span class="badge p-2 rounded-pill" style="background:linear-gradient(135deg,#4f46e5,#7c3aed);color:#fff;">
                    <i class="bi bi-cpu me-1"></i> Auto-Loop AI Active
                </span>
                <a href="../index.php" class="btn btn-sm fw-bold rounded-pill" style="background:#eef2ff;color:#4f46e5;border:1px solid #c7d2fe;">
                    <i class="bi bi-arrow-left"></i> Kembali
                </a>
            </div>
        </div>
    </header>

    <div class="container-fluid px-4 flex-grow-1 d-flex flex-column align-items-center">
        
        <div class="text-center mt-4 mb-2">
            <h2 class="fw-bold mb-2" style="background: linear-gradient(to right, #4f46e5, #7c3aed); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">Profesional Web & IoT Builder</h2>
            <p class="small" style="color:#64748b;">Cukup deskripsikan ide aplikasi Anda. AI akan merancang & menulis kodenya otomatis tahap demi tahap.</p>
        </div>

        <!-- DATABASE MODE SELECTOR -->
        <div class="db-mode-selector mb-3" id="db-mode-selector">
            <div class="mode-toggle-wrapper">
                <button class="mode-btn active" data-mode="json" id="btn-mode-json">
                    <i class="bi bi-filetype-json"></i>
                    <span class="mode-label">JSON Storage</span>
                    <span class="mode-badge">Rekomendasi</span>
                </button>
                <button class="mode-btn" data-mode="mysql" id="btn-mode-mysql">
                    <i class="bi bi-database"></i>
                    <span class="mode-label">MySQL (SQL)</span>
                    <span class="mode-badge mode-badge-adv">Advanced</span>
                </button>
                <button class="mode-btn" data-mode="excel" id="btn-mode-excel">
                    <i class="bi bi-file-earmark-spreadsheet"></i>
                    <span class="mode-label">Google Sheets</span>
                    <span class="mode-badge mode-badge-excel">Sheets DB</span>
                </button>
            </div>
            <p class="mode-desc" id="mode-desc">
                <i class="bi bi-check-circle-fill text-success"></i> 
                Zero config — project langsung jalan tanpa setup database
            </p>
        </div>

        <!-- SHEETS SETUP GUIDE (hanya muncul saat mode excel aktif) -->
        <div id="sheets-setup-guide" style="display:none;max-width:680px;width:100%;margin-bottom:12px;">
            <div class="sheets-guide-card">
                <div class="sheets-guide-header">
                    <i class="bi bi-google"></i>
                    <span>Panduan Setup Google Sheets</span>
                    <button class="sheets-guide-toggle" id="sheets-guide-toggle" title="Tampilkan/Sembunyikan">
                        <i class="bi bi-chevron-down"></i>
                    </button>
                </div>
                <div class="sheets-guide-body" id="sheets-guide-body">
                    <ol class="sheets-steps">
                        <li><i class="bi bi-1-circle-fill"></i> Generate project → Download ZIP</li>
                        <li><i class="bi bi-2-circle-fill"></i> Buka <a href="https://script.google.com" target="_blank">script.google.com</a> → Buat project baru</li>
                        <li><i class="bi bi-3-circle-fill"></i> Paste isi file <code>AppScript.gs</code> dari ZIP ke editor</li>
                        <li><i class="bi bi-4-circle-fill"></i> Klik <b>Deploy → New Deployment → Web App</b><br><small>Execute as: <i>Me</i> &nbsp;|&nbsp; Access: <i>Anyone</i></small></li>
                        <li><i class="bi bi-5-circle-fill"></i> Copy URL Deploy → Paste ke <code>config/sheets_config.php</code></li>
                        <li><i class="bi bi-6-circle-fill"></i> ✅ Data otomatis masuk Google Sheets!</li>
                    </ol>
                </div>
            </div>
        </div>


        <style>
            .db-mode-selector {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 8px;
            }
            .mode-toggle-wrapper {
                display: flex;
                gap: 8px;
                background: #ffffff;
                padding: 6px;
                border-radius: 16px;
                border: 1px solid #e2e8f0;
                box-shadow: 0 2px 10px rgba(79,70,229,0.08);
                flex-wrap: wrap;
                justify-content: center;
            }
            .mode-btn {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 10px 18px;
                border: 1px solid transparent;
                border-radius: 12px;
                background: transparent;
                color: var(--text-muted);
                font-family: 'Inter', sans-serif;
                font-size: 0.88rem;
                font-weight: 500;
                cursor: pointer;
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
            .mode-btn:hover:not(.active):not(.locked) {
                background: #eef2ff;
                color: #4f46e5;
            }
            .mode-btn.active {
                background: linear-gradient(135deg, #eef2ff, #ede9fe);
                border-color: #a5b4fc;
                color: #4f46e5;
                box-shadow: 0 2px 10px rgba(79,70,229,0.15);
            }
            #btn-mode-excel.active {
                background: linear-gradient(135deg, #ecfdf5, #d1fae5);
                border-color: #6ee7b7;
                color: #059669;
                box-shadow: 0 2px 10px rgba(16,185,129,0.15);
            }
            .mode-btn.locked {
                opacity: 0.5;
                cursor: not-allowed;
            }
            .mode-badge {
                font-size: 0.65rem;
                padding: 2px 8px;
                border-radius: 20px;
                background: #dcfce7;
                color: #16a34a;
                font-weight: 600;
                text-transform: uppercase;
                letter-spacing: 0.5px;
            }
            .mode-badge-adv {
                background: #fef9c3;
                color: #a16207;
            }
            .mode-badge-excel {
                background: #d1fae5;
                color: #059669;
            }
            .mode-desc {
                font-size: 0.78rem;
                color: var(--text-muted);
                margin: 0;
                transition: all 0.3s;
            }
            /* Sheets Setup Guide */
            .sheets-guide-card {
                background: rgba(52, 168, 83, 0.06);
                border: 1px solid rgba(52, 168, 83, 0.25);
                border-radius: 14px;
                overflow: hidden;
                animation: fadeIn 0.3s ease;
            }
            .sheets-guide-header {
                display: flex;
                align-items: center;
                gap: 10px;
                padding: 10px 16px;
                background: rgba(52, 168, 83, 0.1);
                color: #34d399;
                font-size: 0.85rem;
                font-weight: 600;
                border-bottom: 1px solid rgba(52, 168, 83, 0.2);
            }
            .sheets-guide-header i:first-child { font-size: 1rem; }
            .sheets-guide-header span { flex: 1; }
            .sheets-guide-toggle {
                background: none;
                border: none;
                color: #34d399;
                cursor: pointer;
                padding: 2px 6px;
                border-radius: 6px;
                transition: all 0.2s;
                font-size: 0.85rem;
            }
            .sheets-guide-toggle:hover { background: rgba(52,168,83,0.15); }
            .sheets-guide-body {
                padding: 12px 16px;
                transition: all 0.3s;
            }
            .sheets-guide-body.collapsed { display: none; }
            .sheets-steps {
                list-style: none;
                padding: 0;
                margin: 0;
                display: flex;
                flex-direction: column;
                gap: 7px;
            }
            .sheets-steps li {
                display: flex;
                align-items: flex-start;
                gap: 10px;
                font-size: 0.82rem;
                color: var(--text-muted);
                line-height: 1.5;
            }
            .sheets-steps li i { color: #34d399; font-size: 1rem; flex-shrink: 0; margin-top: 1px; }
            .sheets-steps a { color: #34d399; text-decoration: underline dotted; }
            .sheets-steps code {
                background: rgba(52,168,83,0.12);
                color: #86efac;
                padding: 1px 6px;
                border-radius: 4px;
                font-size: 0.8rem;
            }
        </style>

        <div class="chat-container">
            <div class="chat-header">
                <div>
                    <span style="width: 24px; height: 24px; display: inline-block; vertical-align: middle; margin-right: 5px;">
                        <?= $logo_html ?>
                    </span> AI Koding Assistant
                </div>
                <div class="d-flex align-items-center gap-2">
                    <button class="btn btn-sm fw-bold rounded-pill btn-prompt-helper-main" data-bs-toggle="modal" data-bs-target="#promptHelperModal">
                        <i class="bi bi-stars"></i> <span>Butuh Ide? Pakai Prompt Helper</span>
                    </button>
                    <div class="text-success small fw-normal d-none d-sm-block">
                        <i class="bi bi-circle-fill" style="font-size: 8px;"></i> Online
                    </div>
                </div>
            </div>
            
            <div class="chat-body" id="chat-body">
                <div class="chat-bubble chat-ai">
                    <div class="markdown-body">
                        ✨ <b>Halo! Saya Aistem Auto Koding.</b><br><br>
                        Saya adalah AI Profesional Pembuat Website dan program IoT. Silakan beri tahu saya detail proyek yang ingin Anda buat.<br><br>
                        👉 <i>Contoh: "Buatkan saya website sekolah sederhana dengan fitur pendaftaran murid baru memakai PHP dan Bootstrap."</i><br><br>
                        💡 <b>Tips:</b> Gunakan fitur <a href="#" data-bs-toggle="modal" data-bs-target="#promptHelperModal" style="color:#4f46e5;text-decoration:underline;font-weight:700;">Prompt Helper</a> di atas agar instruksi Anda lebih presisi dan hasilnya maksimal!
                    </div>
                </div>
            </div>

            <div class="typing-indicator" id="chat-typing">
                <div class="d-flex align-items-center">
                    <div class="radar-spinner"></div>
                    <span class="pulsing-text fw-bold" style="letter-spacing: 0.5px; font-size: 0.9rem;">AI sedang merangkai struktur cerdas...</span>
                </div>
            </div>

            <div class="quick-replies" id="quick-replies">
                <button class="btn-quick btn-quick-yes" id="btn-quick-yes">
                    <i class="bi bi-check-circle-fill"></i> IYA / Lanjutkan
                </button>
                <button class="btn-quick btn-quick-no" id="btn-quick-no">
                    <i class="bi bi-x-circle-fill"></i> Batal
                </button>
            </div>

            <div class="chat-footer">
                <textarea id="chat-input" class="chat-input" placeholder="Ketik deskripsi proyek di sini... (Tekan Shift+Enter untuk baris baru)" rows="1"></textarea>
                <button class="btn-send" id="btn-send-chat" title="Kirim">
                    <i class="bi bi-send-fill"></i>
                </button>
            </div>
        </div>
        
        <!-- PROMPT HELPER MODAL -->
        <div class="modal fade modal-prompt-helper" id="promptHelperModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title fw-bold" style="color:var(--accent-primary);">
                            <i class="bi bi-stars"></i> Agent Prompt Generator Pro
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-4" style="background:#f8fafc;">
                        <div class="row g-4">
                            <!-- Left: Configuration -->
                            <div class="col-lg-6">
                                <div class="prompt-config-card">
                                    <h6 class="prompt-section-title"><i class="bi bi-gear-fill"></i> Konfigurasi Aplikasi</h6>
                                    
                                    <div class="prompt-form-group">
                                        <label>Nama Aplikasi</label>
                                        <input type="text" class="prompt-input" id="gen-app-name" placeholder="Contoh: Aplikasi Data Siswa" value="Aplikasi Data">
                                    </div>

                                    <div class="prompt-form-group">
                                        <label>Konsep Utama</label>
                                        <select class="prompt-select" id="gen-concept">
                                            <option value="CRUD (Create, Read, Update, Delete)">CRUD (Penyimpanan Data)</option>
                                            <option value="Dashboard Monitoring">Dashboard Monitoring</option>
                                            <option value="Point of Sale (POS)">Point of Sale (Sederhana)</option>
                                            <option value="To-Do List Manager">To-Do List Manager</option>
                                            <option value="Inventory Management">Inventory Management</option>
                                            <option value="Sistem Antrean">Sistem Antrean</option>
                                            <option value="E-Commerce Sederhana">E-Commerce Sederhana</option>
                                        </select>
                                    </div>

                                    <div class="prompt-form-group">
                                        <label>Stack Teknologi</label>
                                        <select class="prompt-select" id="gen-stack">
                                            <option value="localstorage">Local Storage (Tanpa Database)</option>
                                            <option value="phpmysql">PHP & MySQL (Database Relasional)</option>
                                            <option value="googlesheets">Google Sheets (Database Online)</option>
                                        </select>
                                    </div>

                                    <div class="prompt-form-group">
                                        <label>Field Data (Input Form)</label>
                                        <div id="gen-field-list" class="field-list-container">
                                            <!-- Fields will be added here -->
                                        </div>
                                        <button class="btn-add-field" id="gen-add-field">
                                            <i class="bi bi-plus-circle"></i> Tambah Field
                                        </button>
                                    </div>

                                    <div class="prompt-form-group">
                                        <label>Warna Utama & Tema</label>
                                        <div class="d-flex gap-2">
                                            <input type="color" id="gen-primary-color" value="#4f46e5" style="width: 50px; height: 38px; border-radius: 8px; padding: 2px; border: 1px solid #ddd;">
                                            <input type="text" class="prompt-input" id="gen-color-name" placeholder="Nama warna (misal: Indigo Premium)" value="Indigo / Putih / Modern">
                                        </div>
                                    </div>

                                    <div class="prompt-form-group">
                                        <label>Instruksi Khusus / Tambahan</label>
                                        <textarea class="prompt-textarea" id="gen-custom-instr" rows="3" placeholder="Contoh: Tambahkan fitur login admin, buat tampilan dashboard memakai chart, atau integrasikan dengan API luar..."></textarea>
                                    </div>

                                    <div class="prompt-form-group">
                                        <label>Fitur Tambahan</label>
                                        <div class="prompt-checkbox-grid">
                                            <label class="prompt-checkbox-item"><input type="checkbox" class="gen-feature" value="Search" checked> Pencarian</label>
                                            <label class="prompt-checkbox-item"><input type="checkbox" class="gen-feature" value="Sorting" checked> Sorting</label>
                                            <label class="prompt-checkbox-item"><input type="checkbox" class="gen-feature" value="Filter" checked> Filter</label>
                                            <label class="prompt-checkbox-item"><input type="checkbox" class="gen-feature" value="Dark Mode" checked> Dark Mode</label>
                                            <label class="prompt-checkbox-item"><input type="checkbox" class="gen-feature" value="Export JSON" checked> Export JSON</label>
                                            <label class="prompt-checkbox-item"><input type="checkbox" class="gen-feature" value="Export PDF/Excel"> Export PDF/Excel</label>
                                            <label class="prompt-checkbox-item"><input type="checkbox" class="gen-feature" value="Animations" checked> Animasi Smooth</label>
                                            <label class="prompt-checkbox-item"><input type="checkbox" class="gen-feature" value="Validation" checked> Validasi Input</label>
                                            <label class="prompt-checkbox-item"><input type="checkbox" class="gen-feature" value="Responsive Card" checked> Mobile Ready</label>
                                            <label class="prompt-checkbox-item"><input type="checkbox" class="gen-feature" value="SweetAlert2" checked> Pop-up Alert</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Right: Result Preview -->
                            <div class="col-lg-6">
                                <div class="h-100 d-flex flex-column">
                                    <div class="prompt-config-card flex-grow-1 d-flex flex-column" style="min-height: 500px;">
                                        <h6 class="prompt-section-title"><i class="bi bi-terminal"></i> AI Prompt Preview</h6>
                                        <div class="prompt-actions-header">
                                            <button class="btn-prompt-action btn-copy-prompt" id="gen-btn-copy">
                                                <i class="bi bi-clipboard"></i> Salin Prompt
                                            </button>
                                            <button class="btn-prompt-action btn-use-prompt" id="gen-btn-use">
                                                <i class="bi bi-send-check-fill"></i> Gunakan di Chat
                                            </button>
                                        </div>
                                        <div class="prompt-result-area" id="gen-prompt-result" style="border-top-left-radius: 0; border-top-right-radius: 0; min-height: 450px;">
                                            <!-- Generated prompt goes here -->
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- FOOTER COPYRIGHT -->
        <div class="text-center mt-2 mb-2 w-100">
            <p class="text-muted small fw-medium" style="letter-spacing: 0.5px;">&copy; <?= date('Y') ?> Xieqa Autokoding | Dev Sikawarsito</p>
        </div>
    </div>

    <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>

    <script>
        $(document).ready(function() {
            const chatBody = $('#chat-body');
            const chatInput = $('#chat-input');
            const btnSendChat = $('#btn-send-chat');
            const chatTyping = $('#chat-typing');
            
            window.chatHistory = [];
            let autoLoopActive = false;
            let currentTaskPhase = 'PLANNING'; // PLANNING or EXECUTION
            window.sessionId = 'ses_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            window.dbMode = 'json'; // Default: JSON Storage
            let modeLocked = false;

            // --- DATABASE MODE TOGGLE ---
            $('.mode-btn').on('click', function() {
                if (modeLocked) return;
                $('.mode-btn').removeClass('active');
                $(this).addClass('active');
                window.dbMode = $(this).data('mode');
                
                const desc = $('#mode-desc');
                const guide = $('#sheets-setup-guide');

                if (window.dbMode === 'json') {
                    desc.html('<i class="bi bi-check-circle-fill text-success"></i> Zero config — project langsung jalan tanpa setup database');
                    guide.hide();
                } else if (window.dbMode === 'mysql') {
                    desc.html('<i class="bi bi-info-circle-fill text-warning"></i> Butuh MySQL — user harus import SQL ke phpMyAdmin');
                    guide.hide();
                } else if (window.dbMode === 'excel') {
                    desc.html('<i class="bi bi-file-earmark-spreadsheet" style="color:#34d399"></i> Data tersimpan di Google Sheets — butuh setup Apps Script sekali saja');
                    guide.show();
                }
            });

            // Toggle panduan sheets
            $('#sheets-guide-toggle').on('click', function() {
                const body = $('#sheets-guide-body');
                const icon = $(this).find('i');
                body.toggleClass('collapsed');
                icon.toggleClass('bi-chevron-down bi-chevron-up');
            });



            function lockModeSelector() {
                if (!modeLocked) {
                    modeLocked = true;
                    $('.mode-btn').addClass('locked');
                    $('#db-mode-selector').css('opacity', '0.6');
                }
            }

            function scrollChatToBottom() {
                setTimeout(() => {
                    chatBody.stop().animate({ scrollTop: chatBody[0].scrollHeight }, 300);
                }, 100);
            }

            function appendChatMessage(role, content, isRaw = false) {
                if (role === 'user') {
                    chatBody.append(`<div class="chat-bubble chat-user">${$('<div>').text(content).html()}</div>`);
                } else if (role === 'system') {
                    chatBody.append(`<div class="chat-system"><i class="bi bi-info-circle-fill"></i> ${content}</div>`);
                } else {
                    let finalHtml = content;
                    if (!isRaw) {
                        let parsedHTML = marked.parse(content);
                        finalHtml = DOMPurify.sanitize(parsedHTML);
                    }
                    let $bubble = $(`<div class="chat-bubble chat-ai"><div class="markdown-body">${finalHtml}</div></div>`);
                    chatBody.append($bubble);
                    
                    // Highlight syntax
                    $bubble.find('pre code').each(function(i, block) {
                        hljs.highlightElement(block);
                        const $pre = $(block).parent();
                        const langClass = block.className.match(/language-(\S+)/);
                        const langName  = langClass ? langClass[1].replace('language-', '') : 'code';
                        const lineCount = block.textContent.split('\n').filter(l => l.trim()).length;

                        $pre.wrap('<div class="code-scroll-area"></div>');
                        $pre.parent().wrap('<div class="code-container"></div>');
                        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="copy-btn" type="button" title="Salin Kode">
                                        <i class="bi bi-clipboard"></i> Salin
                                    </button>
                                </div>
                            </div>
                        `);
                    });
                }
                scrollChatToBottom();
            }

            $(document).on('click', '.copy-btn', function() {
                const $btn = $(this);
                const $code = $btn.closest('.code-container').find('code');
                const text = $code.text();
                
                navigator.clipboard.writeText(text).then(() => {
                    $btn.addClass('copied');
                    $btn.html('<i class="bi bi-check2"></i> Tersalin');
                    setTimeout(() => {
                        $btn.removeClass('copied');
                        $btn.html('<i class="bi bi-clipboard"></i> Salin');
                    }, 2000);
                }).catch(err => {
                    console.error('Gagal menyalin:', err);
                });
            });

            // Quick Replies Logic
            function showQuickReplies() {
                $('#quick-replies').css('display', 'flex');
            }
            function hideQuickReplies() {
                $('#quick-replies').hide();
            }

            $('#btn-quick-yes').on('click', function() {
                chatInput.val('IYA');
                sendChatMessage();
                hideQuickReplies();
            });

            $('#btn-quick-no').on('click', function() {
                chatInput.val('Batal / Reset Chat');
                // Untuk batal, kita bisa mereset chat atau sekadar kirim pesan
                sendChatMessage();
                hideQuickReplies();
                // Opsional: window.location.reload(); jika benar-benar ingin reset total
            });

            // Modifikasi triggerAiRequest untuk menampilkan tombol di akhir PLANNING
            function processAiResponseText(rawText) {
                let textKeUser = rawText.replace(/\[ADA_LANJUTAN\]/g, '').replace(/\[TUGAS_SELESAI\]/g, '');
                
                // Jika di fase PLANNING dan bot tanya persetujuan, munculkan tombol
                const lowerText = textKeUser.toLowerCase();
                const triggerWords = ['setuju', 'lanjutkan', 'iya', 'konfirmasi', 'rencana', 'struktur', 'siap', 'proyek', 'aplikasi', 'bagaimana', 'ok'];
                
                if (currentTaskPhase === 'PLANNING' && triggerWords.some(word => lowerText.includes(word))) {
                    showQuickReplies();
                }

                return textKeUser.trim();
            }

            function triggerAiRequest(userMessage, isAutoLoop = false) {
                chatTyping.css('display', 'inline-flex');
                btnSendChat.prop('disabled', true);
                chatInput.prop('disabled', true);
                
                if (currentTaskPhase === 'EXECUTION') {
                    chatInput.attr('placeholder', 'Sistem sedang menggenerate koding... Harap tunggu hingga selesai.');
                    btnSendChat.html('<i class="bi bi-lock-fill"></i>');
                } else {
                    chatInput.attr('placeholder', 'AI sedang memproses balasan...');
                    btnSendChat.html('<i class="bi bi-hourglass-split"></i>');
                }

                $.ajax({
                    url: 'api/chat.php',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        message: userMessage,
                        history: window.chatHistory,
                        phase: currentTaskPhase,
                        session_id: window.sessionId,
                        db_mode: window.dbMode
                    }),
                    success: function(res) {
                        chatTyping.hide();
                        
                        if (res.error) {
                            alert(res.error);
                            btnSendChat.prop('disabled', false);
                            chatInput.prop('disabled', false);
                            return;
                        }

                        let botReply = res.reply;
                        
                        // Cek status loop dari balasan bot
                        let hasMoreTasks = botReply.includes('[ADA_LANJUTAN]');
                        let isFinished = botReply.includes('[TUGAS_SELESAI]');
                        
                        let cleanMessage = processAiResponseText(botReply);
                        appendChatMessage('ai', cleanMessage);

                        window.chatHistory.push({role: 'ai', content: botReply}); // Tetap simpan original token untuk konteks

                        if (currentTaskPhase === 'EXECUTION') {
                            // Gunakan metadata server untuk akurasi progress
                            const remainingFiles = res.remaining_files || [];
                            const nextFile       = res.next_file || null;
                            const totalPlanned   = res.total_planned || 0;
                            const totalDone      = res.total_done || 0;
                            const allPlanDone    = res.all_plan_done || false;

                            // Server adalah sumber kebenaran:
                            // isFinished jika AI bilang selesai ATAU server konfirmasi rencana tuntas
                            let serverDone = allPlanDone || (remainingFiles.length === 0 && totalPlanned > 0);

                            if (hasMoreTasks && !isFinished && !serverDone) {
                                // Masih ada file — kirim instruksi SPESIFIK ke AI
                                const progressLabel = totalPlanned > 0
                                    ? `(${totalDone}/${totalPlanned})`
                                    : `file ke-${totalDone + 1}`;
                                const pesanLanjut = nextFile
                                    ? `Tolong buat file: "${nextFile}" ${progressLabel}. Tulis kode UTUH dan LENGKAP, satu file ini saja.`
                                    : `LANJUTKAN_KE_FILE_BERIKUTNYA ${progressLabel}. Satu file saja, kode utuh.`;

                                setTimeout(() => {
                                    appendChatMessage('system',
                                        `⏳ ${progressLabel} selesai. Menyiapkan: <b>${nextFile || 'file berikutnya'}</b>... (jeda 15 detik)`);
                                    triggerAiRequest(pesanLanjut, true);
                                }, 15000);

                            } else if (isFinished || serverDone) {
                                // Selesai — cek apakah masih ada sisa di rencana
                                if (remainingFiles.length > 0 && !allPlanDone) {
                                    // AI bilang selesai tapi server tahu masih ada sisa — paksa lanjut
                                    const nextF = remainingFiles[0];
                                    setTimeout(() => {
                                        appendChatMessage('system',
                                            `⚠️ Sistem mendeteksi ${remainingFiles.length} file belum dibuat. Melanjutkan otomatis...`);
                                        triggerAiRequest(
                                            `Perhatian: file berikut belum ada: ${remainingFiles.join(', ')}. Mulai dengan "${nextF}", buat kode UTUH dan LENGKAP.`,
                                            true
                                        );
                                    }, 5000);
                                } else {
                                    // Benar-benar selesai
                                    autoLoopActive = false;
                                    currentTaskPhase = 'PLANNING';

                                    const downloadUrl  = 'api/download.php?session_id=' + window.sessionId;
                                    const summaryLabel = totalPlanned > 0 ? `${totalDone} dari ${totalPlanned} file` : '';
                                    const downloadHtml = `
                                        <div class="mt-2 p-4 text-center" style="background:rgba(74,222,128,0.05);border:1px dashed #4ade80;border-radius:12px;">
                                            <i class="bi bi-check-circle-fill text-success mb-2" style="font-size:2.2rem;"></i>
                                            <h5 class="text-success fw-bold">Proyek Selesai! ${summaryLabel}</h5>
                                            <p class="text-muted small">Semua file telah dikompilasi dan siap diunduh.</p>
                                            <a href="${downloadUrl}" class="btn btn-success fw-bold px-4 py-2 mt-2 rounded-pill shadow">
                                                <i class="bi bi-cloud-arrow-down-fill me-2"></i> Download ZIP
                                            </a>
                                        </div>`;

                                    appendChatMessage('system', '✅ Aistem Auto Koding selesai memproses proyek Anda.');
                                    appendChatMessage('ai', downloadHtml, true);
                                    btnSendChat.prop('disabled', false).html('<i class="bi bi-send-fill"></i>');
                                    chatInput.prop('disabled', false).attr('placeholder', 'Ketik deskripsi proyek di sini... (Tekan Shift+Enter untuk baris baru)').focus();
                                }
                            } else {
                                // hasMoreTasks false dan bukan finished — berarti AI tidak beri penanda
                                // Cek server apakah ada file tersisa
                                if (remainingFiles.length > 0) {
                                    const nextF = remainingFiles[0];
                                    setTimeout(() => {
                                        appendChatMessage('system',
                                            `⚠️ Sistem mendeteksi ${remainingFiles.length} file belum dibuat. Melanjutkan...`);
                                        triggerAiRequest(
                                            `Lanjutkan membuat file: "${nextF}" (${totalDone}/${totalPlanned}). Kode UTUH.`,
                                            true
                                        );
                                    }, 5000);
                                } else {
                                    btnSendChat.prop('disabled', false).html('<i class="bi bi-send-fill"></i>');
                                    chatInput.prop('disabled', false).attr('placeholder', 'Ketik deskripsi proyek di sini... (Tekan Shift+Enter untuk baris baru)').focus();
                                }
                            }
                        } else {
                            btnSendChat.prop('disabled', false).html('<i class="bi bi-send-fill"></i>');
                            chatInput.prop('disabled', false).attr('placeholder', 'Ketik deskripsi proyek di sini... (Tekan Shift+Enter untuk baris baru)').focus();
                        }
                    },
                    error: function() {
                        chatTyping.hide();
                        btnSendChat.prop('disabled', false).html('<i class="bi bi-send-fill"></i>');
                        chatInput.prop('disabled', false).attr('placeholder', 'Ketik deskripsi proyek di sini... (Tekan Shift+Enter untuk baris baru)');
                        alert("Gagal menghubungi server AI.");
                    }
                });
            }

            function sendChatMessage() {
                const message = chatInput.val().trim();
                if (!message) return;

                // Kunci mode selector setelah pesan pertama
                lockModeSelector();

                chatInput.val('');
                chatInput.css('height', '55px'); // auto reset height

                appendChatMessage('user', message);
                window.chatHistory.push({role: 'user', content: message});

                // Deteksi apakah user menyetujui (iya/lanjutkan)
                let msgLower = message.toLowerCase();
                let isAgreeing = (msgLower === 'iya' || msgLower === 'lanjutkan' || msgLower === 'ya' || msgLower === 'setuju');

                if (isAgreeing && currentTaskPhase === 'PLANNING' && window.chatHistory.length > 2) {
                    // Mulai proses koding tahap demi tahap
                    currentTaskPhase = 'EXECUTION';
                    autoLoopActive = true;
                    appendChatMessage('system', "⚠️ Peringatan: Sistem sedang memproses koding. Membutuhkan waktu beberapa menit. Harap jangan di-refresh hingga sistem ini selesai.");
                    
                    // Kita override pesan yang dikirim ke AI agar AI paham mulai eksekusi
                    setTimeout(() => {
                        triggerAiRequest("User setuju. Tolong mulai hasilkan kode untuk TUGAS PERTAMA secara lengkap dan detail.");
                    }, 500);
                } else {
                    triggerAiRequest(message);
                }
            }

            btnSendChat.click(sendChatMessage);
            
            chatInput.on('keydown', function(e) {
                if (e.which == 13 && !e.shiftKey) {
                    e.preventDefault();
                    sendChatMessage();
                }
            });

            // Auto-resize textarea
            chatInput.on('input', function() {
                this.style.height = '55px';
                this.style.height = (this.scrollHeight) + 'px';
            });

            // ===================== PROMPT GENERATOR LOGIC =====================
            let genFields = [
                { id: 1, name: 'Nama / Judul', type: 'Text' },
                { id: 2, name: 'Kategori / Jenis', type: 'Dropdown' },
                { id: 3, name: 'Keterangan / Deskripsi', type: 'Textarea' }
            ];

            function renderGenFields() {
                const container = $('#gen-field-list');
                container.empty();
                genFields.forEach((field, index) => {
                    container.append(`
                        <div class="field-item-row">
                            <input type="text" class="prompt-input" value="${field.name}" placeholder="Nama Field" onchange="updateGenField(${index}, this.value)">
                            <button class="btn-remove-field" onclick="removeGenField(${index})" title="Hapus">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    `);
                });
                generateFinalPrompt();
            }

            window.updateGenField = function(index, value) {
                genFields[index].name = value;
                generateFinalPrompt();
            }

            window.removeGenField = function(index) {
                genFields.splice(index, 1);
                renderGenFields();
            }

            $('#gen-add-field').on('click', function() {
                genFields.push({ id: Date.now(), name: '', type: 'Text' });
                renderGenFields();
            });

            function generateFinalPrompt() {
                const appName = $('#gen-app-name').val();
                const concept = $('#gen-concept').val();
                const stack   = $('#gen-stack').val();
                const color   = $('#gen-color-name').val();
                const customInstr = $('#gen-custom-instr').val().trim();
                const features = $('.gen-feature:checked').map(function() { return $(this).val(); }).get();
                
                const fieldStrings = genFields.filter(f => f.name.trim()).map(f => `- ${f.name}`).join('\n  ');
                const featureList = features.map(f => `- ${f}`).join('\n  ');
                const customSection = customInstr ? `\n⚙️ INSTRUKSI KHUSUS:\n- ${customInstr.replace(/\n/g, '\n- ')}` : '';

                let techStackText = '';
                let storageSection = '';
                let noteSection = '';
                
                if (stack === 'phpmysql') {
                    techStackText = 'PHP & MySQL (Backend)';
                    storageSection = `
💾 DATABASE & PENYIMPANAN:
- Gunakan MySQL sebagai database utama
- Backend menggunakan PHP (PDO atau MySQLi)
- Buat file 'config.php' untuk koneksi database
- Struktur tabel database:
  - id (INT AUTO_INCREMENT PRIMARY KEY)
  ${genFields.map((f, i) => `- field${i+1} (${f.name}) - VARCHAR/TEXT`).join('\n  ')}
  - created_at (TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
- Semua query SQL harus aman dari SQL Injection (Gunakan Prepared Statements)`;
                    noteSection = `
⚠️ CATATAN:
- Memerlukan Web Server (XAMPP/Laragon) untuk menjalankan PHP
- Sertakan script SQL (CREATE TABLE) di awal file
- Pisahkan logika backend dan frontend jika memungkinkan, atau buat dalam satu file PHP yang rapi`;
                } else if (stack === 'googlesheets') {
                    techStackText = 'HTML/JS & Google Sheets API';
                    storageSection = `
💾 PENYIMPANAN:
- Gunakan Google Sheets sebagai JSON Store melalui Apps Script
- Data tersimpan secara online dan real-time
- Berikan instruksi setup Apps Script (doPost/doGet)`;
                    noteSection = `
⚠️ CATATAN:
- Memerlukan Deployment Web App di Google Apps Script
- Pastikan CORS diatur dengan benar`;
                } else {
                    techStackText = 'HTML, CSS, dan JS (tanpa backend)';
                    storageSection = `
💾 PENYIMPANAN:
- Gunakan localStorage sebagai JSON Store
- Struktur data:
  - id (timestamp/random)
  ${genFields.map((f, i) => `- field${i+1} (${f.name})`).join('\n  ')}
  - tanggal
- Data tetap tersimpan saat refresh`;
                    noteSection = `
⚠️ CATATAN:
- Data hanya tersimpan di browser (localStorage)
- Tidak support multi user atau sinkronisasi antar perangkat`;
                }

                const prompt = `Buatkan saya sebuah aplikasi web ${appName} berbasis ${techStackText}, dengan spesifikasi berikut:

🎯 KONSEP:
- Aplikasi ${concept}
- Konsep visual: Modern, Clean, dan Premium
${stack === 'phpmysql' ? '- Sertakan file koneksi database dan query SQL lengkap' : '- Semua dalam 1 file HTML (tanpa server)'}

📋 FITUR UTAMA:
- Form input dinamis:
  ${fieldStrings}
- Tombol aksi:
  - Simpan / Tambah Data
  - Edit / Update Data
  - Hapus / Delete Data
  - Reset Form

📊 TAMPILAN DATA:
- Data ditampilkan dalam:
  - Tabel modern (desktop) dengan fitur responsive
  - Card list yang rapi untuk tampilan Mobile
- Kolom Tabel:
  - No
  ${genFields.map(f => `- ${f.name}`).join('\n  ')}
  - Tanggal / Waktu
  - Aksi (Edit & Hapus)

${storageSection}

🎨 DESAIN (WAJIB MODERN & ELEGAN):
- Gunakan Google Fonts (Poppins / Outfit)
- Warna soft (${color})
- Layout menggunakan Flexbox atau CSS Grid
- Card layout dengan shadow halus dan border radius besar
- Tombol dengan efek hover dan transisi smooth
- Desain Responsive (Mobile First Approach)

✨ UI/UX TAMBAHAN:
- Judul aplikasi: "${appName}"
- Toast / Alert notification untuk sukses/gagal
- Progress bar atau spinner saat proses simpan/hapus
- Empty state message jika data kosong

⚙️ FITUR TAMBAHAN:
${featureList}
- Auto reset form setelah berhasil simpan
- Konfirmasi sebelum menghapus data
${customSection}

${noteSection}

🎯 OUTPUT:
${stack === 'phpmysql' ? '- Berikan struktur folder yang rapi (misal: config.php, index.php, style.css, script.js)\n- Berikan script SQL untuk database' : '- Berikan 1 file HTML lengkap (CSS + JS internal)'}
- Kode harus bersih, rapi, dan mudah dipahami
- Siap digunakan untuk aplikasi profesional`;

                $('#gen-prompt-result').text(prompt);
            }

            // Listeners for inputs
            $('#gen-app-name, #gen-concept, #gen-stack, #gen-color-name, #gen-primary-color, #gen-custom-instr').on('input change', generateFinalPrompt);
            $(document).on('change', '.gen-feature', generateFinalPrompt);

            // Action Buttons
            $('#gen-btn-copy').on('click', function() {
                const text = $('#gen-prompt-result').text();
                navigator.clipboard.writeText(text).then(() => {
                    const btn = $(this);
                    btn.html('<i class="bi bi-check2"></i> Tersalin!');
                    setTimeout(() => btn.html('<i class="bi bi-clipboard"></i> Salin Prompt'), 2000);
                });
            });

            $('#gen-btn-use').on('click', function() {
                const text = $('#gen-prompt-result').text();
                const stack = $('#gen-stack').val();
                
                // Sinkronkan mode project utama dengan pilihan di Prompt Helper
                if (stack === 'phpmysql') {
                    $('#btn-mode-mysql').trigger('click');
                } else if (stack === 'googlesheets') {
                    $('#btn-mode-excel').trigger('click');
                } else {
                    $('#btn-mode-json').trigger('click');
                }

                $('#promptHelperModal').modal('hide');
                chatInput.val(text).trigger('input');
                sendChatMessage();
            });

            // Initial render
            renderGenFields();
        });
    </script>
</body>
</html>
