<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Dashboard - Sentiment Scraper</title>
  <link rel="stylesheet" href="/css/style.css">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <div class="dashboard-container">
    <div class="header">
      <div>
        <h1>Sentiment Scraper</h1>
        <p style="margin:0">Welcome back, <strong><%= username %></strong></p>
      </div>
      <div class="flex">
        <button onclick="document.getElementById('pwdModal').style.display='flex'" class="btn btn-outline" style="width:auto">Change Password</button>
        <a href="/logout" class="btn btn-outline" style="width:auto">Logout</a>
      </div>
    </div>

    <div class="grid">
      <!-- Form Input -->
      <div class="card">
        <h2>Run New Scraping</h2>
        <form id="scrapeForm" onsubmit="runScraper(event)">
          <div class="form-group">
            <label>X.com Auth Token <span style="color:var(--danger)">*</span> <a href="#" onclick="document.getElementById('tokenGuideModal').style.display='flex'" style="font-size:12px; color:var(--accent); text-decoration:none; margin-left:8px;">(Cara dapatkan Token?)</a></label>
            <input type="text" id="s_token" required placeholder="Paste auth_token cookie here">
          </div>
          <div class="form-group">
            <label>Keyword / Topic <span style="color:var(--danger)">*</span></label>
            <input type="text" id="s_keyword" required placeholder="e.g. Pemilu, Covid19">
          </div>
          <div class="grid" style="gap: 16px; grid-template-columns: 1fr 1fr; margin-bottom: 16px;">
            <div class="form-group" style="margin-bottom: 0;">
              <label>Target Tweets</label>
              <input type="number" id="s_limit" required placeholder="e.g. 100" min="10" max="1000" value="100">
            </div>
            <div class="form-group" style="margin-bottom: 0;">
              <label>Tanggal Mulai <span style="font-size:12px; font-weight:normal; color:var(--text-secondary);">(Opsional)</span></label>
              <input type="date" id="s_since">
            </div>
            <div class="form-group" style="margin-bottom: 0; grid-column: 2;">
              <label>Tanggal Akhir <span style="font-size:12px; font-weight:normal; color:var(--text-secondary);">(Opsional)</span></label>
              <input type="date" id="s_until">
            </div>
          </div>
          <button type="submit" class="btn" id="btnScrape">Start Scraping</button>
        </form>

        <div id="loader" class="loader"></div>
        <div id="scrapeStatus" class="text-center mt-4" style="color:var(--text-secondary); display:none;">
          Scraping in progress... this may take a few minutes.
        </div>
      </div>

      <!-- Result Summary -->
      <div class="card">
        <h2>Results</h2>
        <div id="resultEmpty" style="color:var(--text-secondary)">
          No results yet. Run the scraper to see data here.
        </div>
        <div id="resultContent" style="display:none;">
          <div class="grid" style="grid-template-columns: 1fr 1fr 1fr; margin-bottom: 20px;">
            <div class="card" style="text-align:center; padding: 12px; background:rgba(16,185,129,0.1); border-color:#10b981;">
              <h3 style="color:#10b981; margin-bottom:4px;" id="r_pos">0</h3>
              <p style="margin:0; font-size:12px;">POSITIF</p>
            </div>
            <div class="card" style="text-align:center; padding: 12px; background:rgba(239,68,68,0.1); border-color:#ef4444;">
              <h3 style="color:#ef4444; margin-bottom:4px;" id="r_neg">0</h3>
              <p style="margin:0; font-size:12px;">NEGATIF</p>
            </div>
            <div class="card" style="text-align:center; padding: 12px; background:rgba(148,163,184,0.1); border-color:#94a3b8;">
              <h3 style="color:#94a3b8; margin-bottom:4px;" id="r_neu">0</h3>
              <p style="margin:0; font-size:12px;">NETRAL</p>
            </div>
          </div>
          
          <!-- Chart -->
          <div style="margin-bottom: 24px; padding: 16px; background:var(--bg-primary); border-radius:8px; border: 1px solid var(--border);">
            <canvas id="sentimentChart" style="max-height: 250px;"></canvas>
          </div>
          
          <!-- Preview Table -->
          <h3 style="font-size:14px; margin-bottom:8px; color:var(--text-secondary);">Preview (Top Tweets)</h3>
          <div style="overflow-x: auto; margin-bottom: 20px; background:var(--bg-primary); border-radius:8px; border: 1px solid var(--border);">
            <table style="font-size:12px; margin-bottom:0;">
              <thead>
                <tr>
                  <th style="padding:10px;">User</th>
                  <th style="padding:10px;">Tweet</th>
                  <th style="padding:10px; text-align:center;">Sentimen</th>
                </tr>
              </thead>
              <tbody id="previewTableBody">
                <!-- Injected via JS -->
              </tbody>
            </table>
          </div>

          <a id="btnDownload" href="#" class="btn btn-outline" style="text-align:center; display:block; margin-bottom:12px;">Download Full Data (.xlsx)</a>
          <p style="font-size:12px; margin:0;" id="r_time"></p>
        </div>
      </div>
    </div>
  </div>

  <!-- Change Password Modal -->
  <div id="pwdModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); z-index:100; align-items:center; justify-content:center;">
    <div class="auth-card" style="margin: auto; margin-top: 10vh;">
      <h2>Change Password</h2>
      <div id="pwdAlert" class="alert" style="display:none;"></div>
      <form id="pwdForm" onsubmit="changePassword(event)">
        <div class="form-group">
          <label>Current Password</label>
          <input type="password" id="p_current" required>
        </div>
        <div class="form-group">
          <label>New Password</label>
          <input type="password" id="p_new" required>
        </div>
        <div class="form-group">
          <label>Confirm New Password</label>
          <input type="password" id="p_confirm" required>
        </div>
        <div class="flex mt-4">
          <button type="button" class="btn btn-outline" onclick="document.getElementById('pwdModal').style.display='none'">Cancel</button>
          <button type="submit" class="btn">Update Password</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Token Guide Modal -->
  <div id="tokenGuideModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); z-index:100; align-items:center; justify-content:center; padding: 20px;">
    <div class="auth-card" style="margin: auto; max-width: 500px; max-height: 80vh; overflow-y: auto;">
      <h2>Cara Dapatkan Auth Token X</h2>
      
      <h3 style="font-size:14px; margin-top:16px; margin-bottom:8px; color:var(--accent);">💻 Di PC / Laptop</h3>
      <ol style="font-size:14px; padding-left: 20px; color:var(--text-secondary); line-height:1.6;">
        <li>Buka tab baru dan login ke <strong>x.com</strong>.</li>
        <li>Tekan <strong>F12</strong> untuk membuka <em>Developer Tools</em>.</li>
        <li>Pilih tab <strong>Application</strong> (Chrome/Edge) atau <strong>Storage</strong> (Firefox).</li>
        <li>Di menu kiri, buka <strong>Cookies</strong> > <code>https://x.com</code>.</li>
        <li>Cari baris bernama <strong>auth_token</strong>.</li>
        <li>Salin (Copy) kode di kolom <em>Value</em> lalu tempelkan ke form.</li>
      </ol>

      <h3 style="font-size:14px; margin-top:16px; margin-bottom:8px; color:var(--accent);">📱 Di HP / Android</h3>
      <ol style="font-size:14px; padding-left: 20px; color:var(--text-secondary); line-height:1.6;">
        <li>Install aplikasi <strong>Kiwi Browser</strong> dari Play Store (mendukung Developer Tools).</li>
        <li>Buka Kiwi Browser dan login ke <strong>x.com</strong>.</li>
        <li>Klik ikon <strong>titik tiga</strong> (kanan atas), pilih <strong>Developer Tools</strong>.</li>
        <li>Buka tab <strong>Application</strong> > <strong>Cookies</strong> > <code>https://x.com</code>.</li>
        <li>Cari <strong>auth_token</strong> dan salin <em>Value</em>-nya.</li>
      </ol>

      <div class="flex mt-4" style="justify-content: flex-end;">
        <button type="button" class="btn btn-outline" onclick="document.getElementById('tokenGuideModal').style.display='none'" style="width: auto;">Tutup Panduan</button>
      </div>
    </div>
  </div>

  <script>
    async function changePassword(e) {
      e.preventDefault();
      const current_password = document.getElementById('p_current').value;
      const new_password = document.getElementById('p_new').value;
      const confirm_new_password = document.getElementById('p_confirm').value;
      
      try {
        const res = await fetch('/dashboard/change-password', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ current_password, new_password, confirm_new_password })
        });
        const data = await res.json();
        const alert = document.getElementById('pwdAlert');
        if (res.ok) {
          alert.innerText = 'Password changed successfully!';
          alert.className = 'alert alert-success';
          alert.style.display = 'block';
          setTimeout(() => {
            document.getElementById('pwdModal').style.display = 'none';
            document.getElementById('pwdForm').reset();
            alert.style.display = 'none';
          }, 1500);
        } else {
          alert.innerText = data.error;
          alert.className = 'alert alert-error';
          alert.style.display = 'block';
        }
      } catch (err) {
        console.error(err);
      }
    }

    async function runScraper(e) {
      e.preventDefault();
      const token = document.getElementById('s_token').value;
      const keyword = document.getElementById('s_keyword').value;
      const limit = document.getElementById('s_limit').value;
      const since = document.getElementById('s_since').value;
      const until = document.getElementById('s_until').value;

      document.getElementById('btnScrape').disabled = true;
      document.getElementById('loader').style.display = 'block';
      document.getElementById('scrapeStatus').style.display = 'block';
      document.getElementById('resultContent').style.display = 'none';
      document.getElementById('resultEmpty').style.display = 'block';

      try {
        const res = await fetch('/api/scrape', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ token, keyword, limit: parseInt(limit), since, until })
        });
        
        const data = await res.json();
        
        if (res.ok) {
          document.getElementById('resultEmpty').style.display = 'none';
          document.getElementById('resultContent').style.display = 'block';
          
          document.getElementById('r_pos').innerText = data.stats.pos + ' (' + data.stats.pctPos + ')';
          document.getElementById('r_neg').innerText = data.stats.neg + ' (' + data.stats.pctNeg + ')';
          document.getElementById('r_neu').innerText = data.stats.neu + ' (' + data.stats.pctNeu + ')';
          
          // Render Chart
          if (window.myChart) window.myChart.destroy();
          const ctx = document.getElementById('sentimentChart').getContext('2d');
          window.myChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
              labels: ['Positif', 'Negatif', 'Netral'],
              datasets: [{
                data: [data.stats.pos, data.stats.neg, data.stats.neu],
                backgroundColor: ['#10b981', '#ef4444', '#94a3b8'],
                borderWidth: 0
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: {
                legend: { position: 'right', labels: { color: '#94a3b8', font: {family: 'Inter'} } }
              }
            }
          });

          // Render Table
          const tbody = document.getElementById('previewTableBody');
          tbody.innerHTML = '';
          if (data.preview && data.preview.length > 0) {
            data.preview.forEach(r => {
              let color = '#94a3b8';
              if (r.sentimen === 'POSITIF') color = '#10b981';
              if (r.sentimen === 'NEGATIF') color = '#ef4444';
              
              const row = document.createElement('tr');
              row.innerHTML = `
                <td style="padding:10px; font-weight:600; color:var(--text-primary);">@${r.user}</td>
                <td style="padding:10px; color:var(--text-secondary); line-height:1.5;">${r.teks.length > 100 ? r.teks.substring(0,100)+'...' : r.teks}</td>
                <td style="padding:10px; text-align:center;"><span class="badge" style="background:transparent; color:${color}; border:1px solid ${color};">${r.sentimen}</span></td>
              `;
              tbody.appendChild(row);
            });
          }

          document.getElementById('btnDownload').href = data.downloadUrl;
          document.getElementById('r_time').innerText = 'Scraped at: ' + new Date().toLocaleString();
        } else {
          alert('Scraping failed: ' + (data.error || 'Unknown error'));
        }
      } catch (err) {
        console.error(err);
        alert('Server error occurred.');
      } finally {
        document.getElementById('btnScrape').disabled = false;
        document.getElementById('loader').style.display = 'none';
        document.getElementById('scrapeStatus').style.display = 'none';
      }
    }
  </script>
</body>
</html>
