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

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

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

// Cek status akun PRO
$stmt_user = mysqli_prepare($conn, "SELECT status_akun, role FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt_user, "s", $user_id);
mysqli_stmt_execute($stmt_user);
$u_data = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt_user));
mysqli_stmt_close($stmt_user);

if (($u_data['status_akun'] ?? 'free') !== 'pro' && ($u_data['role'] ?? 'siswa') !== 'admin') {
    echo "<script>alert('Akses Ditolak! Fitur Analisis Tred terkunci dan hanya khusus untuk pengguna akun PRO.'); window.location.href='../index.php';</script>";
    exit;
}

// Ambil cfg untuk nama aplikasi ringan
$cfg = mysqli_fetch_assoc(mysqli_query($conn, "SELECT nama_aplikasi FROM settings WHERE id = 1"));
$nama_app = htmlspecialchars($cfg['nama_aplikasi']);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Analisis Tred - <?= $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-dark: #0f172a;
            --panel-bg: #1e293b;
            --border-color: #334155;
            --accent-primary: #3b82f6; 
            --accent-glow: rgba(59, 130, 246, 0.5);
            --text-main: #f8fafc;
            --text-muted: #94a3b8;
            --success: #10b981;
            --danger: #ef4444;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--bg-dark);
            color: var(--text-main);
            min-height: 100vh;
            margin: 0;
            padding-bottom: 50px;
        }

        /* Navbar & Header */
        .glass-header {
            background: rgba(30, 41, 59, 0.7);
            backdrop-filter: blur(12px);
            border-bottom: 1px solid var(--border-color);
            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, #3b82f6, #8b5cf6);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-size: 1.5rem;
        }

        /* Dashboard Container */
        .dashboard-container {
            max-width: 1200px;
            margin: 40px auto;
            padding: 0 20px;
        }

        /* Uploader Area */
        .upload-card {
            background: var(--panel-bg);
            border: 1px dashed var(--border-color);
            border-radius: 16px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }

        .upload-card:hover, .upload-card.dragover {
            border-color: var(--accent-primary);
            background: rgba(30, 41, 59, 0.9);
            box-shadow: 0 0 25px var(--accent-glow);
        }

        .upload-icon {
            font-size: 4rem;
            color: var(--accent-primary);
            margin-bottom: 20px;
            display: inline-block;
            transition: transform 0.3s ease;
        }

        .upload-card:hover .upload-icon {
            transform: scale(1.1) translateY(-5px);
        }

        .upload-btn {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 50px;
            font-weight: 600;
            margin-top: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
        }

        .upload-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(59, 130, 246, 0.5);
        }

        /* Image Preview Box */
        .preview-box {
            display: none;
            margin-top: 30px;
            background: var(--panel-bg);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 20px;
            position: relative;
        }

        #chart-preview {
            max-width: 100%;
            max-height: 400px;
            border-radius: 8px;
            object-fit: contain;
            display: block;
            margin: 0 auto;
        }

        .analyze-trigger-btn {
            width: 100%;
            background: linear-gradient(90deg, #10b981, #059669);
            color: white;
            border: none;
            padding: 16px;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 700;
            margin-top: 20px;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .analyze-trigger-btn:hover {
            transform: scale(1.02);
            box-shadow: 0 8px 25px rgba(16, 185, 129, 0.5);
        }

        /* Result Area */
        .result-container {
            display: none;
            margin-top: 40px;
        }

        .result-card {
            background: var(--panel-bg);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
        }

        .result-header {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border-color);
        }

        .result-icon {
            width: 45px;
            height: 45px;
            border-radius: 12px;
            background: rgba(139, 92, 246, 0.1);
            color: #8b5cf6;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }

        .markdown-body {
            color: var(--text-main);
            font-size: 0.95rem;
            line-height: 1.7;
        }

        /* Fix styling untuk AI respons Markdown */
        .markdown-body  h1, .markdown-body h2, .markdown-body h3 {
            color: #f8fafc;
            margin-top: 1.5em;
            margin-bottom: 0.8em;
            font-weight: 600;
        }
        
        .markdown-body h3 { font-size: 1.25rem; }

        .markdown-body strong { color: #fff; }

        .markdown-body table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            background: rgba(15, 23, 42, 0.5);
            border-radius: 8px;
            overflow: hidden;
        }

        .markdown-body th {
            background: rgba(59, 130, 246, 0.1);
            color: #60a5fa;
            text-align: left;
            padding: 12px 15px;
            border-bottom: 1px solid var(--border-color);
        }

        .markdown-body td {
            padding: 12px 15px;
            border-bottom: 1px solid var(--border-color);
        }

        .markdown-body ul, .markdown-body ol {
            padding-left: 20px;
        }

        .markdown-body li {
            margin-bottom: 8px;
        }

        /* Loading Overlay */
        .loading-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(15, 23, 42, 0.85);
            backdrop-filter: blur(8px);
            z-index: 2000;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .radar-spinner {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            border: 2px solid transparent;
            border-top-color: var(--accent-primary);
            border-bottom-color: #8b5cf6;
            animation: spin 1.5s cubic-bezier(0.68, -0.55, 0.265, 1.55) infinite;
            position: relative;
        }

        .radar-spinner::before {
            content: '';
            position: absolute;
            top: 10px; left: 10px; right: 10px; bottom: 10px;
            border-radius: 50%;
            border: 2px solid transparent;
            border-left-color: var(--success);
            border-right-color: var(--danger);
            animation: spin-reverse 2s linear infinite;
        }

        .loading-text {
            color: white;
            margin-top: 25px;
            font-size: 1.2rem;
            font-weight: 600;
            letter-spacing: 1px;
        }

        @keyframes spin { 100% { transform: rotate(360deg); } }
        @keyframes spin-reverse { 100% { transform: rotate(-360deg); } }

        /* Animation Chart */
        @keyframes drawLine {
            to { stroke-dashoffset: 0; }
        }
        .anim-line-up {
            stroke-dasharray: 400; stroke-dashoffset: 400;
            animation: drawLine 2s cubic-bezier(0.22, 1, 0.36, 1) forwards;
            filter: drop-shadow(0 0 10px rgba(34, 197, 94, 0.8));
        }
        .anim-line-down {
            stroke-dasharray: 400; stroke-dashoffset: 400;
            animation: drawLine 2s cubic-bezier(0.22, 1, 0.36, 1) forwards;
            filter: drop-shadow(0 0 10px rgba(239, 68, 68, 0.8));
        }
        .blink-text { animation: blinker 2s linear infinite; }
        @keyframes blinker { 50% { opacity: 0.5; } }
        
        @keyframes fadeUpIn {
            0% { opacity: 0; transform: translateY(15px); }
            100% { opacity: 1; transform: translateY(0); }
        }
        .anim-candle {
            opacity: 0;
            animation: fadeUpIn 0.3s ease-out forwards;
        }
        .anim-label {
            opacity: 0;
            animation: fadeUpIn 0.5s ease-out forwards;
        }

        /* Chat UI */
        .chat-card {
            background: var(--panel-bg);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            display: flex;
            flex-direction: column;
            height: 100%;
            min-height: 500px;
            max-height: 700px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
        }
        
        .chat-header {
            padding: 15px 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 600;
        }
        
        .chat-body {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .chat-bubble {
            max-width: 85%;
            padding: 12px 16px;
            border-radius: 12px;
            font-size: 0.95rem;
            line-height: 1.5;
        }

        .chat-user {
            background: var(--accent-primary);
            color: white;
            align-self: flex-end;
            border-bottom-right-radius: 4px;
        }

        .chat-ai {
            background: rgba(255,255,255,0.05);
            border: 1px solid var(--border-color);
            color: var(--text-main);
            align-self: flex-start;
            border-bottom-left-radius: 4px;
        }
        .chat-ai .markdown-body {
            font-size: 0.95rem;
            color: var(--text-main);
        }

        .chat-footer {
            padding: 15px;
            border-top: 1px solid var(--border-color);
            display: flex;
            gap: 10px;
        }

        .chat-input {
            flex: 1;
            background: rgba(0,0,0,0.2);
            border: 1px solid var(--border-color);
            color: white;
            padding: 10px 15px;
            border-radius: 20px;
            outline: none;
        }
        
        .chat-input:focus {
            border-color: var(--accent-primary);
        }
        
        .btn-send {
            background: var(--accent-primary);
            color: white;
            border: none;
            width: 45px;
            height: 45px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }
        
        .btn-send:hover {
            transform: scale(1.05);
            background: #2563eb;
        }
        
        .typing-indicator {
            display: none;
            align-self: flex-start;
            padding: 10px 15px;
            background: rgba(255,255,255,0.05);
            border-radius: 12px;
            border: 1px solid var(--border-color);
            margin-bottom: 15px;
            margin-left: 20px;
        }
        .dot {
            display: inline-block;
            width: 6px;
            height: 6px;
            background: #94a3b8;
            border-radius: 50%;
            margin: 0 2px;
            animation: bounce 1.4s infinite ease-in-out both;
        }
        .dot:nth-child(1) { animation-delay: -0.32s; }
        .dot:nth-child(2) { animation-delay: -0.16s; }
        @keyframes bounce {
            0%, 80%, 100% { transform: scale(0); }
            40% { transform: scale(1); }
        }
    </style>
</head>
<body>

    <!-- Header -->
    <header class="glass-header py-3">
        <div class="container d-flex justify-content-between align-items-center">
            <a href="../index.php" class="brand-logo">
                <i class="bi bi-graph-up-arrow brand-icon"></i>
                Analisis Tred AI
            </a>
            <div class="d-flex align-items-center gap-3">
                <span class="badge bg-primary bg-opacity-25 text-primary border border-primary p-2 rounded-pill d-none d-md-block">
                    <i class="bi bi-robot me-1"></i> Vision Model Active
                </span>
                <button class="btn btn-outline-info rounded-pill btn-sm fw-bold border-info text-info" data-bs-toggle="modal" data-bs-target="#howItWorksModal">
                    <i class="bi bi-info-circle"></i> Cara Kerja
                </button>
                <a href="../index.php" class="btn btn-outline-light rounded-pill btn-sm fw-bold border-secondary text-secondary">
                    <i class="bi bi-arrow-left"></i> Kembali
                </a>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="dashboard-container">
        
        <div class="text-center mb-5">
            <h1 class="fw-bold mb-3" style="background: linear-gradient(to right, #60a5fa, #a78bfa); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">Deep Chart Analysis</h1>
            <p class="text-light fs-5" style="opacity: 0.9; max-width: 700px; margin: 0 auto; letter-spacing: 0.5px;">Unggah screenshot grafik trading (Saham, Crypto, Forex) untuk dianalisa secara teknikal oleh AI. Membantu memberikan proyeksi trend yang komprehensif.</p>
        </div>

        <div class="row justify-content-center">
            <div class="col-lg-12">
                
                <!-- Uploader -->
                <div class="upload-card" id="drop-zone">
                    <i class="bi bi-cloud-arrow-up upload-icon"></i>
                    <h4 class="fw-bold text-white mb-2">Pilih atau Tarik Berkas</h4>
                    <p class="text-muted small mb-0">Format: JPG, PNG, WEBP, CSV, XLSX. Maks 5MB.</p>
                    <input type="file" id="file-input" accept="image/*,.csv,.xlsx" style="display: none;">
                    
                    <div class="d-flex justify-content-center gap-3 mt-3">
                        <button class="upload-btn m-0" onclick="document.getElementById('file-input').click()">
                            <i class="bi bi-folder2-open"></i> Plih File Sendiri
                        </button>
                        <button class="btn btn-outline-warning rounded-pill px-4 fw-bold shadow-sm d-flex align-items-center" id="btn-demo" style="border-width: 2px;">
                            <i class="bi bi-lightning-charge-fill text-warning me-2"></i> Coba Demo Sampel
                        </button>
                    </div>
                </div>

                <!-- Preview Box -->
                <div class="preview-box" id="preview-box">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span class="badge bg-secondary">Preview Grafik</span>
                        <button class="btn btn-sm btn-outline-danger shadow-none rounded-pill" id="btn-cancel">
                            <i class="bi bi-trash"></i> Batal
                        </button>
                    </div>
                    <img id="chart-preview" src="" alt="Chart Preview" class="mb-3">
                    
                    <div class="mb-3 text-start">
                        <label for="timeframe-select" class="form-label text-white fw-bold"><i class="bi bi-clock-history text-warning"></i> Pilih Timeframe Grafik Ini:</label>
                        <select class="form-select bg-dark text-white border-secondary" id="timeframe-select" style="border-radius: 12px; padding: 12px;">
                            <option value="Tidak Diketahui" selected>-- Otomatis Terdeteksi AI (Opsional) --</option>
                            <option value="1 Menit (1m)">1 Menit (1m)</option>
                            <option value="15 Menit (15m)">15 Menit (15m)</option>
                            <option value="1 Jam (1h)">1 Jam (1h)</option>
                            <option value="4 Jam (4h)">4 Jam (4h)</option>
                            <option value="1 Hari (1D/24h)">1 Hari (1D/24h)</option>
                            <option value="1 Minggu (1W)">1 Minggu (1W)</option>
                            <option value="1 Bulan (1M)">1 Bulan (1M)</option>
                        </select>
                        <small class="text-muted">Membantu AI menganalisis akurasi jarak target profit yang realistis.</small>
                    </div>

                    <button class="analyze-trigger-btn" id="btn-analyze">
                        <i class="bi bi-stars"></i> Mulai Analisis AI
                    </button>
                </div>

                <!-- Result Box -->
                <div class="result-container" id="result-container" style="display: none; margin-top: 40px;">
                    <div class="row">
                        <!-- Kolom Kiri: Hasil Analisis -->
                        <div class="col-lg-7 mb-4 mb-lg-0">
                            <div class="result-card" style="height: 100%;">
                                <div class="result-header">
                                    <div class="result-icon">
                                        <i class="bi bi-bar-chart-line-fill"></i>
                                    </div>
                                    <div>
                                        <h4 class="fw-bold text-white mb-0">Laporan Analisis Tred</h4>
                                        <div class="text-muted small" id="time-generated">Menunggu diproses...</div>
                                    </div>
                                </div>
                                <div class="markdown-body" id="ai-response">
                                    <!-- Hasil ditaruh disini -->
                                </div>
                                <div id="simulation-box" class="mt-4 p-4 rounded" style="background: rgba(0,0,0,0.4); border: 1px solid rgba(255,255,255,0.05); display: none;">
                                    <h5 class="fw-bold mb-3 text-white border-bottom border-secondary pb-2">
                                        <i class="bi bi-display"></i> Simulasi Proyeksi Visual AI
                                    </h5>
                                    <div id="simulation-target"></div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Kolom Kanan: Chatbot -->
                        <div class="col-lg-5">
                            <div class="chat-card">
                                <div class="chat-header">
                                    <i class="bi bi-robot text-primary fs-4"></i>
                                    <div>
                                        <div class="text-white">Tred AI Assistant</div>
                                        <div class="text-success small fw-normal"><i class="bi bi-circle-fill" style="font-size: 6px; vertical-align: middle;"></i> Online</div>
                                    </div>
                                </div>
                                <div class="chat-body" id="chat-body">
                                    <div class="chat-bubble chat-ai">
                                        <div class="markdown-body">
                                            ✨ Halo! Saya adalah AI Trading Assistant. Anda bisa menanyakan alasan di balik prediksi chart yang baru saja saya analisis, atau berkonsultasi seputar trading saat ini.
                                        </div>
                                    </div>
                                </div>
                                <div class="typing-indicator" id="chat-typing">
                                    <span class="dot"></span><span class="dot"></span><span class="dot"></span>
                                </div>
                                <div class="chat-footer">
                                    <input type="text" id="chat-input" class="chat-input" placeholder="Tanya sesuatu tentang chart ini..." autocomplete="off">
                                    <button class="btn-send" id="btn-send-chat">
                                        <i class="bi bi-send-fill"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <!-- Footer Copyright -->
        <div class="text-center mt-5 pt-4 pb-2 border-top" style="border-color: rgba(255,255,255,0.1) !important;">
            <p class="text-muted small mb-0" style="letter-spacing: 0.5px;">&copy; <?= date('Y') ?> Xieqa AI Ekosistem | Dev Sikawarsito</p>
        </div>
    </div>

    <!-- Modal Cara Kerja -->
    <div class="modal fade" id="howItWorksModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content" style="background: var(--panel-bg); border: 1px solid var(--border-color); border-radius: 16px;">
                <div class="modal-header border-bottom border-secondary">
                    <h5 class="modal-title fw-bold text-white"><i class="bi bi-lightbulb-fill text-warning me-2"></i>Bagaimana Analisis Tred Bekerja?</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-white" style="line-height: 1.8;">
                    <div class="row text-center mb-4 mt-2">
                        <div class="col-md-3">
                            <div class="p-3 mb-2 rounded" style="background: rgba(59, 130, 246, 0.1); border: 1px dashed #3b82f6;">
                                <i class="bi bi-cloud-upload" style="font-size: 2rem; color: #3b82f6;"></i>
                            </div>
                            <h6 class="fw-bold">1. Upload</h6>
                            <p class="small text-muted">Unggah gambar Chart / file CSV historis.</p>
                        </div>
                        <div class="col-md-3">
                            <div class="p-3 mb-2 rounded" style="background: rgba(139, 92, 246, 0.1); border: 1px dashed #8b5cf6;">
                                <i class="bi bi-cpu" style="font-size: 2rem; color: #8b5cf6;"></i>
                            </div>
                            <h6 class="fw-bold">2. Analisis AI</h6>
                            <p class="small text-muted">Ekstraksi pola Candlestick & Indikator.</p>
                        </div>
                        <div class="col-md-3">
                            <div class="p-3 mb-2 rounded" style="background: rgba(16, 185, 129, 0.1); border: 1px dashed #10b981;">
                                <i class="bi bi-graph-up-arrow" style="font-size: 2rem; color: #10b981;"></i>
                            </div>
                            <h6 class="fw-bold">3. Sinyal</h6>
                            <p class="small text-muted">Dapatkan prediksi arah dan titik rasio Entry.</p>
                        </div>
                        <div class="col-md-3">
                            <div class="p-3 mb-2 rounded" style="background: rgba(245, 158, 11, 0.1); border: 1px dashed #f59e0b;">
                                <i class="bi bi-robot" style="font-size: 2rem; color: #f59e0b;"></i>
                            </div>
                            <h6 class="fw-bold">4. Tanya Asisten</h6>
                            <p class="small text-muted">Klarifikasi alasan dari prediksi AI.</p>
                        </div>
                    </div>
                    <div class="alert alert-warning border border-warning" style="background: rgba(245, 158, 11, 0.1);">
                        <strong><i class="bi bi-exclamation-triangle-fill"></i> Peringatan Risiko (Explainable AI):</strong>
                        <br>
                        AI mendasarkan kesimpulan dari pengenalan pola probabilitas (Machine Learning). Kami menyajikan 'alasan analisis' (reasoning) secara transparan. <b>Ini bukan saran finansial absolut</b>, tetap gunakan manajemen risiko mandiri.
                    </div>
                    <div class="d-flex justify-content-end mt-3">
                        <button type="button" class="btn btn-secondary px-4 rounded-pill" data-bs-dismiss="modal">Mengerti</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Loading -->
    <div class="loading-overlay" id="loading-overlay">
        <div class="radar-spinner"></div>
        <div class="loading-text">AI Membaca Grafik Parameter...</div>
        <div class="text-muted small mt-2">Mohon tunggu 15-30 detik untuk akurasi penuh.</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>
        $(document).ready(function() {
            const dropZone = $('#drop-zone');
            const fileInput = $('#file-input');

            // Logic Tombol Demo
            $('#btn-demo').click(function(e) {
                e.preventDefault();
                const csvStr = "TANGGAL,OPEN,HIGH,LOW,CLOSE,VOLUME\n2023-11-01,34000,35000,33800,34800,200\n2023-11-02,34800,35500,34500,35200,250\n2023-11-03,35200,36000,35000,35800,300\n2023-11-04,35800,36500,35500,36200,400\n2023-11-05,36200,37500,36000,37100,500";
                const demoFile = new File([csvStr], "Demo_BTC_BULLISH.csv", { type: "text/csv" });
                
                const origHtml = $(this).html();
                $(this).html('<i class="bi bi-hourglass-split"></i> Memuat...');
                
                setTimeout(() => {
                    $(this).html(origHtml);
                    handleFile(demoFile);
                    setTimeout(() => $('#btn-analyze').click(), 400);
                }, 600);
            });
            const previewBox = $('#preview-box');
            const chartPreview = $('#chart-preview');
            const btnCancel = $('#btn-cancel');
            const btnAnalyze = $('#btn-analyze');
            const resultContainer = $('#result-container');
            const aiResponse = $('#ai-response');
            const loadingOverlay = $('#loading-overlay');
            const timeGenerated = $('#time-generated');

            let currentFile = null;

            // Drag and drop event
            dropZone.on('dragover', function(e) {
                e.preventDefault(); dropZone.addClass('dragover');
            }).on('dragleave', function() {
                dropZone.removeClass('dragover');
            }).on('drop', function(e) {
                e.preventDefault(); dropZone.removeClass('dragover');
                if (e.originalEvent.dataTransfer.files.length) {
                    handleFile(e.originalEvent.dataTransfer.files[0]);
                }
            });

            fileInput.on('change', function(e) {
                if (this.files.length) handleFile(this.files[0]);
            });

            function handleFile(file) {
                const isImage = file.type.startsWith('image/');
                const isDoc = file.name.match(/\.(csv|xlsx)$/i);

                if (!isImage && !isDoc) {
                    alert('Harap unggah file gambar (JPG/PNG) atau file histori (CSV/XLSX).'); return;
                }
                if (file.size > 5 * 1024 * 1024) {
                    alert('Ukuran file maksimal 5MB.'); return;
                }
                
                currentFile = file;
                const reader = new FileReader();
                reader.onload = e => {
                    if (isImage) {
                        chartPreview.attr('src', e.target.result).show();
                        $('#doc-badge').hide();
                    } else {
                        chartPreview.hide();
                        $('#doc-badge').remove();
                        chartPreview.after(`<div id="doc-badge" class="badge bg-success p-3 fs-6 w-100 mb-3"><i class="bi bi-file-earmark-excel"></i> Histori Siap: ${file.name}</div>`);
                    }
                    dropZone.slideUp();
                    previewBox.slideDown();
                    resultContainer.slideUp();
                }
                reader.readAsDataURL(file);
            }

            btnCancel.click(() => {
                fileInput.val('');
                currentFile = null;
                previewBox.slideUp();
                dropZone.slideDown();
                resultContainer.slideUp();
            });

            async function compressImage(file, maxWidth = 800, maxHeight = 800, quality = 0.5) {
                return new Promise((resolve) => {
                    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) {
                                if (!blob) { resolve(file); return; }
                                try {
                                    resolve(new File([blob], file.name, { type: 'image/jpeg', lastModified: Date.now() }));
                                } catch (e) {
                                    blob.name = file.name;
                                    resolve(blob);
                                }
                            }, 'image/jpeg', quality);
                        };
                        img.onerror = function() {
                            resolve(file); // Jika error, kembalikan aslinya saja
                        };
                    };
                    reader.onerror = function() { resolve(file); };
                });
            }

            btnAnalyze.click(async function() {
                if (!currentFile) {
                    alert('Harap unggah atau tarik file grafik / excel ke dalam kotak terlebih dahulu!');
                    return;
                }

                try {
                    loadingOverlay.css('display', 'flex');
                    
                    let readyFile = currentFile;
                    if (currentFile.type.startsWith('image/')) {
                        readyFile = await compressImage(currentFile, 800, 800, 0.4);
                    }

                    let formData = new FormData();
                    formData.append('gambar', readyFile);
                    formData.append('timeframe', $('#timeframe-select').val());

                    $.ajax({
                        url: 'api/analyze.php',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(res) {
                            loadingOverlay.hide();
                            
                            if (res.error) {
                                alert(res.error);
                                return;
                            }

                            if (!res.jawaban) {
                                alert("Data kosong dari server.");
                                return;
                            }

                            // Rendering format markdown ke html
                            let rawHtml = marked.parse(res.jawaban);
                            let safeHtml = DOMPurify.sanitize(rawHtml);
                            aiResponse.html(safeHtml);

                            // Initial AI Context for Chatbot
                            window.initialAnalysisText = res.jawaban;
                            window.chatHistory = [];
                            $('#chat-body').html(`
                                <div class="chat-bubble chat-ai">
                                    <div class="markdown-body">
                                        ✨ Halo! Saya adalah AI Trading Assistant. Anda bisa menanyakan alasan di balik prediksi chart yang baru saja saya analisis, atau berkonsultasi seputar trading saat ini.
                                    </div>
                                </div>
                            `);

                            // --- LOGIC ANIMASI CHART CANDLESTICK ---
                            let resUpp = res.jawaban.toUpperCase();
                            let isBuy = resUpp.includes('BELI') || resUpp.includes('BUY');
                            let isSell = resUpp.includes('JUAL') || resUpp.includes('SELL');
                            
                            // Ekstrak Harga menggunakan regex yang lebih universal untuk semua arah trade
                            let entryMatch = res.jawaban.match(/(?:Harga Beli Terbaik|Harga Jual Terbaik|Harga Beli|Posisi Masuk|Entry).*?(?:di)?\s*angka\s*([^\n\r]+)/i);
                            let tpMatch = res.jawaban.match(/(?:Harga Jual Untuk Untung|Harga Beli Kembali Untuk Untung|Jual Untung|Take Profit|Ambil Untung).*?(?:di)?\s*angka\s*([^\n\r]+)/i);
                            let slMatch = res.jawaban.match(/(?:Harga Jual Darurat|Harga Beli Kembali Darurat|Cut Loss|Batas Kerugian).*?(?:di)?\s*angka\s*([^\n\r]+)/i);
                            
                            let entryPrice = entryMatch ? entryMatch[1].replace(/[^0-9.,$A-Za-z- ]/g, '').substring(0, 15) : 'Sekarang';
                            let tpPrice = tpMatch ? tpMatch[1].replace(/[^0-9.,$A-Za-z- ]/g, '').substring(0, 15) : 'Auto';
                            let slPrice = slMatch ? slMatch[1].replace(/[^0-9.,$A-Za-z- ]/g, '').substring(0, 15) : 'Auto';

                            function buildCandleChart(isB, ePrice, tPrice, sPrice) {
                                let width = 500; let height = 300;
                                let svg = `<svg viewBox="0 0 ${width} ${height}" width="100%" height="250px" style="background: rgba(0,0,0,0.3); border-radius:10px; border:1px solid rgba(255,255,255,0.1); margin-top:15px; font-family: monospace;">`;
                                
                                for(let y=50; y<=250; y+=50) {
                                    svg += `<line x1="0" y1="${y}" x2="${width}" y2="${y}" stroke="#333" stroke-width="1" stroke-dasharray="4"/>`;
                                }

                                let startY = isB ? 230 : 60;
                                let endY = isB ? 60 : 230;
                                
                                svg += `<rect x="0" y="0" width="130" height="${height}" fill="rgba(255,255,255,0.03)"/>`;
                                svg += `<text x="10" y="25" fill="#666" font-size="12" font-weight="bold">Masa Lalu</text>`;
                                svg += `<text x="150" y="25" fill="#3b82f6" font-size="12" font-weight="bold">SIMULASI PREDIKSI >></text>`;
                                
                                let currentPriceY = startY;
                                let barW = 8;
                                let spacing = 24;
                                let cx = 25;
                                
                                // History Candles
                                for(let i=0; i<4; i++) {
                                    let open = currentPriceY;
                                    let close = currentPriceY + (Math.random()*20 - 10);
                                    let high = Math.min(open, close) - (Math.random()*15 + 5);
                                    let low = Math.max(open, close) + (Math.random()*15 + 5);
                                    let color = close > open ? '#ef4444' : '#22c55e'; 
                                    svg += `<g style="opacity:0.4;">
                                        <line x1="${cx+barW/2}" y1="${high}" x2="${cx+barW/2}" y2="${low}" stroke="${color}" stroke-width="1.5"/>
                                        <rect x="${cx}" y="${Math.min(open, close)}" width="${barW}" height="${Math.abs(close-open)||2}" fill="${color}"/>
                                    </g>`;
                                    cx += spacing;
                                    currentPriceY = close;
                                }

                                let actualEntryY = currentPriceY;

                                // Jumper Line to start pred
                                svg += `<line x1="${cx}" y1="${actualEntryY}" x2="${width}" y2="${actualEntryY}" stroke="#aaa" stroke-width="1.5" stroke-dasharray="6"/>`;
                                svg += `<rect x="135" y="${actualEntryY - 26}" width="200" height="22" fill="rgba(170,170,170,0.2)" rx="4"/>`;
                                svg += `<text x="145" y="${actualEntryY - 11}" fill="#fff" font-size="13" font-weight="bold">ENTRY: ${ePrice}</text>`;
                                
                                // SL Line
                                let slY = isB ? actualEntryY + 35 : actualEntryY - 35; 
                                if(slY > 10 && slY < height-10) {
                                    svg += `<line x1="0" y1="${slY}" x2="${width}" y2="${slY}" stroke="#ef4444" stroke-width="1" stroke-dasharray="4"/>`;
                                    svg += `<text x="10" y="${slY - 5}" fill="#ef4444" font-size="11">Risiko Bawah: ${sPrice}</text>`;
                                }

                                // Predicted Candles
                                let targetStep = (endY - actualEntryY) / 10;
                                for(let i=0; i<10; i++) {
                                    let open = currentPriceY;
                                    let move = targetStep + (Math.random()*15 - 7.5);
                                    let close = currentPriceY + move;
                                    let high = Math.min(open, close) - (Math.random()*12);
                                    let low = Math.max(open, close) + (Math.random()*12);
                                    let color = close > open ? '#ef4444' : '#22c55e';
                                    
                                    let delay = (i * 0.15) + 0.2;
                                    
                                    svg += `<g class="anim-candle" style="animation-delay: ${delay}s;">
                                        <line x1="${cx+barW/2}" y1="${high}" x2="${cx+barW/2}" y2="${low}" stroke="${color}" stroke-width="2"/>
                                        <rect x="${cx}" y="${Math.min(open, close)}" width="${barW}" height="${Math.abs(close-open)||2}" fill="${color}"/>
                                    </g>`;
                                    cx += spacing;
                                    currentPriceY = close;
                                }

                                // Target Line 
                                svg += `<g class="anim-label" style="animation-delay: 1.8s;">`;
                                svg += `<line x1="${cx-spacing}" y1="${currentPriceY}" x2="${width}" y2="${currentPriceY}" stroke="#eab308" stroke-width="2.5" stroke-dasharray="5"/>`;
                                svg += `<text x="${cx + 10}" y="${currentPriceY - 8}" fill="#eab308" font-size="15" font-weight="bold">TARGET: ${tPrice}</text>`;
                                svg += `</g>`;

                                svg += `</svg>`;
                                return svg;
                            }

                            let targetHTML = '';

                            if (isBuy && !isSell) {
                                targetHTML = `
                                <div class="text-center mt-3">
                                    <h4 class="text-success fw-bold blink-text mb-3">🔥 Sinyal: BUY (Naik) 🚀</h4>
                                    ${buildCandleChart(true, entryPrice, tpPrice, slPrice)}
                                </div>`;
                            } else if (isSell && !isBuy) {
                                targetHTML = `
                                <div class="text-center mt-3">
                                    <h4 class="text-danger fw-bold blink-text mb-3">🩸 Sinyal: SELL / SHORT (Turun) 🔻</h4>
                                    ${buildCandleChart(false, entryPrice, tpPrice, slPrice)}
                                </div>`;
                            } 
                            // Mode Sideways / Campuran
                            else if (resUpp.includes('SIDEWAYS') || (isBuy && isSell)) {
                                targetHTML = `
                                <div class="text-center mt-3">
                                    <h4 class="text-warning fw-bold blink-text mb-3">⚖️ Sinyal: Netral / Sideways ↔️</h4>
                                    <svg viewBox="0 0 400 200" width="100%" height="200px" style="background: rgba(0,0,0,0.2); border-radius:10px; border:1px solid #333;">
                                        <line x1="0" y1="60" x2="400" y2="60" stroke="#ef4444" stroke-width="1" stroke-dasharray="8" />
                                        <line x1="0" y1="140" x2="400" y2="140" stroke="#22c55e" stroke-width="1" stroke-dasharray="8" />
                                        <text x="10" y="55" fill="#ef4444" font-size="12">Resistance (Jual)</text>
                                        <text x="10" y="155" fill="#22c55e" font-size="12">Support (Beli)</text>
                                        <path class="anim-line-up" style="stroke:#eab308; filter:drop-shadow(0 0 8px #eab308);" d="M 20 100 Q 60 70, 100 100 T 180 100 T 260 100 T 340 100 L 380 90" fill="none" stroke-width="6" stroke-linecap="round"/>
                                    </svg>
                                </div>`;
                            }

                            if (targetHTML !== '') {
                                $('#simulation-target').html(targetHTML);
                                $('#simulation-box').slideDown();
                            } else {
                                $('#simulation-box').hide();
                            }
                            // --- AKHIR LOGIC ANIMASI ---

                            let now = new Date();
                            timeGenerated.text("Dianalisis pada: " + now.toLocaleString('id-ID'));

                            resultContainer.slideDown();
                            
                            // Scroll to result
                            $('html, body').animate({
                                scrollTop: resultContainer.offset().top - 50
                            }, 500);
                        },
                        error: function(xhr, status, error) {
                            loadingOverlay.hide();
                            console.error("AJAX Error:", status, error, xhr.responseText);
                            alert('Terjadi kesalahan sistem saat menghubungi Server AI (Code: ' + xhr.status + ').\n\nPesan: ' + (xhr.responseText ? xhr.responseText.substring(0, 50) : error));
                        }
                    });
                } catch (err) {
                    loadingOverlay.hide();
                    alert("Terjadi masalah pada browser Anda saat menyiapkan gambar. " + err.message);
                }
            });

            // --- LOGIC CHATBOT ---
            const chatBody = $('#chat-body');
            const chatInput = $('#chat-input');
            const btnSendChat = $('#btn-send-chat');
            const chatTyping = $('#chat-typing');
            
            window.chatHistory = [];
            window.initialAnalysisText = '';

            function scrollChatToBottom() {
                chatBody.scrollTop(chatBody[0].scrollHeight);
            }

            function appendChatMessage(role, content) {
                if (role === 'user') {
                    chatBody.append(`<div class="chat-bubble chat-user">${$('<div>').text(content).html()}</div>`);
                } else {
                    let safeHtml = DOMPurify.sanitize(marked.parse(content));
                    chatBody.append(`<div class="chat-bubble chat-ai"><div class="markdown-body">${safeHtml}</div></div>`);
                }
                scrollChatToBottom();
            }

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

                chatInput.val('');
                appendChatMessage('user', message);
                chatTyping.css('display', 'inline-block');
                scrollChatToBottom();
                btnSendChat.prop('disabled', true);

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

                        appendChatMessage('ai', res.reply);
                        window.chatHistory.push({role: 'user', content: message});
                        window.chatHistory.push({role: 'ai', content: res.reply});
                    },
                    error: function() {
                        chatTyping.hide();
                        btnSendChat.prop('disabled', false);
                        alert("Gagal menghubungi server chat.");
                    }
                });
            }

            btnSendChat.click(sendChatMessage);
            chatInput.keypress(function(e) {
                if (e.which == 13) sendChatMessage();
            });
        });
    </script>
</body>
</html>
