<!DOCTYPE html>
<html lang="<%= lang %>">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Instagram — Vianexu</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=Syne:wght@700;800&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg:      #080808;
      --surface: #111;
      --border:  #1c1c1c;
      --text:    #e8e8e8;
      --muted:   #555;
      --accent:  #c8f551;
      --accent-dim: #8aaa2a;
      --danger:  #ff4444;
      --radius:  12px;
    }
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: 'Inter', sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; font-size: 14px; }

    /* ── navbar ── */
    .navbar {
      height: 52px; background: var(--surface); border-bottom: 1px solid var(--border);
      display: flex; align-items: center; justify-content: space-between; padding: 0 24px;
    }
    .navbar-brand { font-family: 'Syne', sans-serif; font-weight: 800; font-size: 16px; color: var(--accent); text-decoration: none; }
    .navbar-brand span { font-weight: 400; font-family: 'Inter', sans-serif; font-size: 12px; color: var(--muted); margin-left: 8px; }
    .navbar-right { display: flex; align-items: center; gap: 12px; }
    .ig-badge {
      display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted);
      background: var(--border); padding: 4px 10px; border-radius: 20px;
    }
    .ig-badge .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); }
    .btn-ghost { background: none; border: 1px solid var(--border); color: var(--muted); padding: 6px 14px; border-radius: 8px; cursor: pointer; font-size: 12px; text-decoration: none; transition: border-color .15s, color .15s; }
    .btn-ghost:hover { border-color: var(--text); color: var(--text); }

    /* ── main layout ── */
    .page { max-width: 960px; margin: 0 auto; padding: 48px 24px; }
    .page-title { font-family: 'Syne', sans-serif; font-size: 26px; font-weight: 800; margin-bottom: 6px; }
    .page-sub { color: var(--muted); font-size: 13px; margin-bottom: 40px; }

    /* ── flash ── */
    .flash { padding: 12px 16px; border-radius: var(--radius); margin-bottom: 24px; font-size: 13px; }
    .flash.success { background: #1a2e0a; border: 1px solid var(--accent-dim); color: var(--accent); }
    .flash.error   { background: #2e0a0a; border: 1px solid var(--danger); color: #ff8888; }

    /* ── connect banner ── */
    .connect-banner {
      background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
      padding: 24px; display: flex; align-items: center; justify-content: space-between;
      gap: 16px; margin-bottom: 40px;
    }
    .connect-banner p { color: var(--muted); font-size: 13px; margin-top: 4px; }
    .btn-accent { background: var(--accent); color: #000; border: none; padding: 10px 20px; border-radius: 8px; font-weight: 600; font-size: 13px; cursor: pointer; text-decoration: none; transition: opacity .15s; }
    .btn-accent:hover { opacity: .85; }
    .btn-danger { background: none; border: 1px solid var(--danger); color: var(--danger); padding: 8px 16px; border-radius: 8px; font-size: 12px; cursor: pointer; text-decoration: none; transition: background .15s; }
    .btn-danger:hover { background: rgba(255,68,68,.1); }

    /* ── 3 cards ── */
    .cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
    @media (max-width: 640px) { .cards { grid-template-columns: 1fr; } }

    .card {
      background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
      padding: 28px 24px; cursor: pointer; transition: border-color .2s, transform .15s;
      text-decoration: none; color: inherit; display: block; position: relative; overflow: hidden;
    }
    .card:hover { border-color: #333; transform: translateY(-2px); }
    .card.active { border-color: var(--accent); }
    .card-icon { font-size: 32px; margin-bottom: 16px; }
    .card-title { font-family: 'Syne', sans-serif; font-weight: 700; font-size: 17px; margin-bottom: 6px; }
    .card-desc { color: var(--muted); font-size: 12px; line-height: 1.5; }
    .card-status {
      position: absolute; top: 16px; right: 16px;
      font-size: 10px; font-weight: 600; padding: 3px 8px; border-radius: 20px;
    }
    .card-status.on  { background: rgba(200,245,81,.15); color: var(--accent); }
    .card-status.off { background: rgba(85,85,85,.2); color: var(--muted); }

    /* ── slide panel ── */
    .panel-overlay {
      position: fixed; inset: 0; background: rgba(0,0,0,.6); z-index: 100;
      opacity: 0; pointer-events: none; transition: opacity .25s;
    }
    .panel-overlay.open { opacity: 1; pointer-events: all; }

    .panel {
      position: fixed; top: 0; right: 0; bottom: 0; width: 420px; max-width: 100vw;
      background: var(--surface); border-left: 1px solid var(--border);
      z-index: 101; display: flex; flex-direction: column;
      transform: translateX(100%); transition: transform .3s cubic-bezier(.4,0,.2,1);
    }
    .panel.open { transform: translateX(0); }

    .panel-head {
      padding: 20px 24px; border-bottom: 1px solid var(--border);
      display: flex; align-items: center; justify-content: space-between; flex-shrink: 0;
    }
    .panel-head h2 { font-family: 'Syne', sans-serif; font-size: 16px; font-weight: 700; }
    .panel-close { background: none; border: none; color: var(--muted); cursor: pointer; font-size: 20px; line-height: 1; padding: 4px; }
    .panel-close:hover { color: var(--text); }
    .panel-body { flex: 1; overflow-y: auto; padding: 24px; display: flex; flex-direction: column; gap: 24px; }
    .panel-foot { padding: 16px 24px; border-top: 1px solid var(--border); flex-shrink: 0; }

    /* ── toggle ── */
    .field-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
    .field-label { font-size: 13px; font-weight: 500; }
    .field-sub { font-size: 11px; color: var(--muted); margin-top: 3px; }
    .toggle { position: relative; width: 44px; height: 24px; flex-shrink: 0; }
    .toggle input { opacity: 0; width: 0; height: 0; position: absolute; }
    .toggle-track {
      position: absolute; inset: 0; background: var(--border); border-radius: 24px;
      cursor: pointer; transition: background .2s;
    }
    .toggle-track::after {
      content: ''; position: absolute; left: 3px; top: 3px;
      width: 18px; height: 18px; background: #fff; border-radius: 50%;
      transition: transform .2s;
    }
    .toggle input:checked + .toggle-track { background: var(--accent); }
    .toggle input:checked + .toggle-track::after { transform: translateX(20px); }

    /* ── textarea ── */
    .field-group { display: flex; flex-direction: column; gap: 8px; }
    .field-group label { font-size: 12px; font-weight: 500; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; }
    .field-group textarea {
      background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
      color: var(--text); font-family: 'Inter', sans-serif; font-size: 13px;
      padding: 12px; resize: vertical; min-height: 130px; line-height: 1.55;
      transition: border-color .15s;
    }
    .field-group textarea:focus { outline: none; border-color: #333; }
    .field-group .hint { font-size: 11px; color: var(--muted); line-height: 1.5; }

    .save-btn {
      width: 100%; background: var(--accent); color: #000; border: none;
      padding: 12px; border-radius: 8px; font-weight: 600; font-size: 14px;
      cursor: pointer; transition: opacity .15s;
    }
    .save-btn:hover { opacity: .85; }
    .save-btn:disabled { opacity: .4; cursor: not-allowed; }
    .saved-msg { text-align: center; font-size: 12px; color: var(--accent); margin-top: 8px; height: 16px; }
  </style>
</head>
<body>

<nav class="navbar">
  <a class="navbar-brand" href="/<%= lang %>/dashboard">VIANEXU <span>/ Instagram</span></a>
  <div class="navbar-right">
    <% if (botUser && botUser.ig_username) { %>
      <div class="ig-badge"><div class="dot"></div>@<%= botUser.ig_username %></div>
      <a href="/<%= lang %>/dashboard/ig-disconnect" class="btn-danger">Desconectar</a>
    <% } %>
    <a href="/<%= lang %>/logout" class="btn-ghost">Sair</a>
  </div>
</nav>

<div class="page">

  <% if (locals.flash) { %>
    <% if (flash.success && flash.success.length) { %><div class="flash success"><%= flash.success[0] %></div><% } %>
    <% if (flash.error   && flash.error.length)   { %><div class="flash error"><%= flash.error[0] %></div><% } %>
  <% } %>

  <h1 class="page-title">Instagram</h1>
  <p class="page-sub">Gerencie posts, mensagens automáticas e respostas de comentários.</p>

  <% if (!botUser || !botUser.ig_token) { %>
  <div class="connect-banner">
    <div>
      <strong>Conta não conectada</strong>
      <p>Conecte seu Instagram Business para usar todas as funcionalidades.</p>
    </div>
    <a href="/ig/connect" class="btn-accent">Conectar Instagram</a>
  </div>
  <% } %>

  <div class="cards">

    <!-- Posts -->
    <a class="card" href="/<%= lang %>/dashboard/instagram/creator">
      <div class="card-icon">🎨</div>
      <div class="card-title">Posts</div>
      <p class="card-desc">Crie e publique carrosseis e imagens diretamente no seu Instagram.</p>
    </a>

    <!-- Mensagens -->
    <div class="card" id="card-messages" onclick="openPanel('messages')">
      <% if (botUser && botUser.bot_msg_enabled) { %>
        <div class="card-status on">ON</div>
      <% } else { %>
        <div class="card-status off">OFF</div>
      <% } %>
      <div class="card-icon">💬</div>
      <div class="card-title">Mensagens</div>
      <p class="card-desc">Bot com IA responde mensagens diretas automaticamente.</p>
    </div>

    <!-- Comentários -->
    <div class="card" id="card-comments" onclick="openPanel('comments')">
      <% if (botUser && botUser.bot_cmt_enabled) { %>
        <div class="card-status on">ON</div>
      <% } else { %>
        <div class="card-status off">OFF</div>
      <% } %>
      <div class="card-icon">🗨️</div>
      <div class="card-title">Comentários</div>
      <p class="card-desc">Bot com IA responde comentários nos seus posts automaticamente.</p>
    </div>

  </div>
</div>

<!-- ── Panel overlay ── -->
<div class="panel-overlay" id="overlay" onclick="closePanel()"></div>

<!-- ── Panel: Mensagens ── -->
<div class="panel" id="panel-messages">
  <div class="panel-head">
    <h2>💬 Bot de Mensagens</h2>
    <button class="panel-close" onclick="closePanel()">✕</button>
  </div>
  <div class="panel-body">
    <div class="field-row">
      <div>
        <div class="field-label">Ativar resposta automática</div>
        <div class="field-sub">O bot responderá todas as DMs recebidas</div>
      </div>
      <label class="toggle">
        <input type="checkbox" id="msg-enabled" <%= (botUser && botUser.bot_msg_enabled) ? 'checked' : '' %>>
        <div class="toggle-track"></div>
      </label>
    </div>
    <div class="field-group">
      <label>Personalidade do bot</label>
      <textarea id="msg-persona" placeholder="Ex: Você é uma assistente da @menosansiedade. Responda de forma acolhedora e breve sobre ansiedade e saúde mental..."><%= (botUser && botUser.bot_msg_persona) ? botUser.bot_msg_persona : '' %></textarea>
      <div class="hint">Descreva como o bot deve se comportar. Sem persona definida, usará um padrão humanizado genérico.</div>
    </div>
  </div>
  <div class="panel-foot">
    <button class="save-btn" onclick="saveSettings('messages')">Salvar</button>
    <div class="saved-msg" id="saved-messages"></div>
  </div>
</div>

<!-- ── Panel: Comentários ── -->
<div class="panel" id="panel-comments">
  <div class="panel-head">
    <h2>🗨️ Bot de Comentários</h2>
    <button class="panel-close" onclick="closePanel()">✕</button>
  </div>
  <div class="panel-body">
    <div class="field-row">
      <div>
        <div class="field-label">Ativar resposta automática</div>
        <div class="field-sub">O bot responderá comentários em todos os posts</div>
      </div>
      <label class="toggle">
        <input type="checkbox" id="cmt-enabled" <%= (botUser && botUser.bot_cmt_enabled) ? 'checked' : '' %>>
        <div class="toggle-track"></div>
      </label>
    </div>
    <div class="field-group">
      <label>Personalidade do bot</label>
      <textarea id="cmt-persona" placeholder="Ex: Você é uma assistente da @menosansiedade. Responda comentários de forma simpática e encorajadora..."><%= (botUser && botUser.bot_cmt_persona) ? botUser.bot_cmt_persona : '' %></textarea>
      <div class="hint">Descreva como o bot deve responder comentários. Respostas serão curtas (1-2 linhas).</div>
    </div>
  </div>
  <div class="panel-foot">
    <button class="save-btn" onclick="saveSettings('comments')">Salvar</button>
    <div class="saved-msg" id="saved-comments"></div>
  </div>
</div>

<script>
  let currentPanel = null;

  function openPanel(type) {
    closePanel();
    currentPanel = type;
    document.getElementById('overlay').classList.add('open');
    document.getElementById('panel-' + type).classList.add('open');
    document.getElementById('card-' + type).classList.add('active');
  }

  function closePanel() {
    if (!currentPanel) return;
    document.getElementById('overlay').classList.remove('open');
    document.getElementById('panel-' + currentPanel).classList.remove('open');
    document.getElementById('card-' + currentPanel).classList.remove('active');
    currentPanel = null;
  }

  document.addEventListener('keydown', e => { if (e.key === 'Escape') closePanel(); });

  async function saveSettings(type) {
    const btn = document.querySelector(`#panel-${type} .save-btn`);
    const msg = document.getElementById(`saved-${type}`);
    btn.disabled = true;
    btn.textContent = 'Salvando...';

    const enabled = document.getElementById(type === 'messages' ? 'msg-enabled' : 'cmt-enabled').checked ? '1' : '0';
    const persona = document.getElementById(type === 'messages' ? 'msg-persona' : 'cmt-persona').value;

    try {
      const r = await fetch('/<%- lang %>/dashboard/instagram/bot-settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type, enabled, persona })
      });
      const data = await r.json();
      if (data.success) {
        msg.textContent = '✓ Salvo';
        // Atualiza badge do card
        const statusEl = document.querySelector(`#card-${type} .card-status`);
        statusEl.textContent = enabled === '1' ? 'ON' : 'OFF';
        statusEl.className = 'card-status ' + (enabled === '1' ? 'on' : 'off');
        setTimeout(() => { msg.textContent = ''; }, 2500);
      } else {
        msg.textContent = '✗ Erro ao salvar';
      }
    } catch {
      msg.textContent = '✗ Erro de rede';
    }
    btn.disabled = false;
    btn.textContent = 'Salvar';
  }
</script>
</body>
</html>
