<!DOCTYPE html>
<html lang="<%= lang %>">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Google Business — 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;
      --danger:  #ff4444;
      --radius:  12px;
      --g-blue:  #4285F4;
      --g-green: #34A853;
      --g-yellow:#FBBC05;
      --g-red:   #EA4335;
    }
    *, *::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 {
      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; }
    .g-badge {
      display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted);
      background: var(--border); padding: 4px 10px; border-radius: 20px;
    }
    .g-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--g-blue); }
    .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); }
    .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; display: inline-block; }
    .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); }
    .btn-sm { padding: 7px 14px; font-size: 12px; border-radius: 8px; border: 1px solid var(--border); background: none; color: var(--text); cursor: pointer; transition: .15s; }
    .btn-sm:hover { border-color: #444; }

    .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 { padding: 12px 16px; border-radius: var(--radius); margin-bottom: 24px; font-size: 13px; }
    .flash.success { background: #1a2e0a; border: 1px solid #8aaa2a; color: var(--accent); }
    .flash.error   { background: #2e0a0a; border: 1px solid var(--danger); color: #ff8888; }

    /* Connect banner */
    .connect-banner {
      background: linear-gradient(135deg, #080d1a 0%, #070a10 100%);
      border: 1px solid rgba(66,133,244,.25); border-radius: var(--radius);
      padding: 28px 32px; display: flex; align-items: center; justify-content: space-between;
      gap: 16px; margin-bottom: 40px; position: relative; overflow: hidden;
    }
    .connect-banner::before {
      content: ''; position: absolute; top: 0; left: 0; right: 0; height: 2px;
      background: linear-gradient(90deg, var(--g-blue), var(--g-green), var(--g-yellow), var(--g-red));
    }
    .connect-banner p { color: var(--muted); font-size: 13px; margin-top: 6px; }
    .connect-banner strong { font-size: 15px; }

    /* Google G icon */
    .g-icon { display: inline-flex; margin-right: 4px; vertical-align: middle; }

    /* Cards grid */
    .cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-bottom: 40px; }
    @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: #2a2a2a; transform: translateY(-2px); }
    .card.active { border-color: var(--g-blue); }
    .card-icon { font-size: 28px; margin-bottom: 16px; }
    .card-title { font-family: 'Syne', sans-serif; font-weight: 700; font-size: 16px; margin-bottom: 6px; }
    .card-desc { color: var(--muted); font-size: 12px; line-height: 1.5; }

    /* Reviews section */
    .section-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
    .section-title { font-family: 'Syne', sans-serif; font-size: 17px; font-weight: 700; }
    .section-sub { color: var(--muted); font-size: 12px; margin-top: 4px; }

    .review-list { display: flex; flex-direction: column; gap: 12px; }
    .review-card {
      background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
      padding: 20px 24px; transition: border-color .2s;
    }
    .review-card:hover { border-color: #2a2a2a; }
    .review-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 10px; }
    .review-author { font-weight: 600; font-size: 14px; }
    .review-date { font-size: 11px; color: var(--muted); margin-top: 3px; }
    .stars { color: var(--g-yellow); font-size: 13px; letter-spacing: 1px; }
    .review-text { font-size: 13px; color: #ccc; line-height: 1.6; margin-bottom: 14px; }
    .review-reply {
      background: rgba(66,133,244,.06); border: 1px solid rgba(66,133,244,.15);
      border-radius: 8px; padding: 12px 16px; margin-bottom: 14px;
    }
    .review-reply-label { font-size: 10px; letter-spacing: 2px; text-transform: uppercase; color: var(--g-blue); margin-bottom: 6px; }
    .review-reply p { font-size: 12px; color: #aaa; line-height: 1.55; }
    .review-actions { display: flex; gap: 8px; align-items: center; }
    .reply-input {
      width: 100%; background: #0d0d0d; border: 1px solid var(--border); color: var(--text);
      border-radius: 8px; padding: 10px 14px; font-family: 'Inter', sans-serif;
      font-size: 13px; resize: vertical; min-height: 80px; transition: border-color .15s; margin-bottom: 8px;
    }
    .reply-input:focus { outline: none; border-color: var(--g-blue); }
    .reply-form { display: none; margin-top: 12px; }
    .reply-form.open { display: block; }

    /* Stars rating */
    .rating-1 .stars::after { content: '★☆☆☆☆'; }
    .rating-2 .stars::after { content: '★★☆☆☆'; }
    .rating-3 .stars::after { content: '★★★☆☆'; }
    .rating-4 .stars::after { content: '★★★★☆'; }
    .rating-5 .stars::after { content: '★★★★★'; }

    /* Empty + loading states */
    .empty { text-align: center; padding: 60px 0; color: var(--muted); }
    .empty svg { opacity: .3; margin-bottom: 16px; }
    .spinner { display: inline-block; width: 20px; height: 20px; border: 2px solid var(--border); border-top-color: var(--g-blue); border-radius: 50%; animation: spin .7s linear infinite; }
    @keyframes spin { to { transform: rotate(360deg); } }

    /* AI suggest */
    .btn-ai { background: rgba(66,133,244,.12); border: 1px solid rgba(66,133,244,.25); color: var(--g-blue); padding: 6px 12px; border-radius: 6px; font-size: 11px; cursor: pointer; transition: .15s; }
    .btn-ai:hover { background: rgba(66,133,244,.2); }
    .btn-reply { background: var(--g-blue); color: #fff; border: none; padding: 8px 16px; border-radius: 8px; font-size: 12px; font-weight: 600; cursor: pointer; transition: opacity .15s; }
    .btn-reply:hover { opacity: .85; }
    .btn-reply:disabled { opacity: .4; cursor: not-allowed; }
  </style>
</head>
<body>

<nav class="navbar">
  <a class="navbar-brand" href="/<%= lang %>/dashboard">VIANEXU <span>/ Google Business</span></a>
  <div class="navbar-right">
    <% if (gbUser && gbUser.google_biz_name) { %>
      <div class="g-badge"><div class="g-dot"></div><%= gbUser.google_biz_name %></div>
      <form method="POST" action="/google/disconnect" style="display:inline">
        <button type="submit" class="btn-danger">Desconectar</button>
      </form>
    <% } %>
    <a href="/<%= lang %>/dashboard" class="btn-ghost">← Painel</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">Google Business</h1>
  <p class="page-sub">Gerencie reviews, posts e presença no Google Maps.</p>

  <% if (!gbUser || !gbUser.google_token) { %>
  <div class="connect-banner">
    <div>
      <strong>Conecte o Google Business</strong>
      <p>Autorize o acesso para responder reviews e publicar posts no Google.</p>
    </div>
    <a href="/google/connect" class="btn-accent">
      <svg class="g-icon" width="16" height="16" viewBox="0 0 24 24"><path d="M22 12.2c0-.7-.1-1.4-.2-2H12v3.8h5.6c-.2 1.3-1 2.4-2.1 3.1v2.6h3.4c2-1.8 3.1-4.5 3.1-7.5z" fill="#4285F4"/><path d="M12 23c2.7 0 5-.9 6.9-2.4l-3.4-2.6c-.9.6-2.1 1-3.5 1-2.7 0-5-1.8-5.8-4.3H2.7v2.7C4.6 20.9 8.1 23 12 23z" fill="#34A853"/><path d="M6.2 14.7c-.2-.6-.3-1.2-.3-1.9s.1-1.3.3-1.9V8.2H2.7C2 9.6 1.5 11.3 1.5 13s.5 3.4 1.2 4.8l3.5-3.1z" fill="#FBBC05"/><path d="M12 5.8c1.5 0 2.9.5 3.9 1.5l2.9-2.9C17 2.9 14.7 2 12 2 8.1 2 4.6 4.1 2.7 7.2l3.5 2.7C7 7.6 9.3 5.8 12 5.8z" fill="#EA4335"/></svg>
      Conectar Google
    </a>
  </div>
  <% } else { %>

  <!-- Cards -->
  <div class="cards">
    <div class="card" onclick="showTab('reviews')">
      <div class="card-icon">⭐</div>
      <div class="card-title">Reviews</div>
      <p class="card-desc">Leia e responda avaliações do Google Maps com IA.</p>
    </div>
    <div class="card" style="opacity:.5;cursor:default">
      <div class="card-icon">📢</div>
      <div class="card-title">Google Posts</div>
      <p class="card-desc">Publique ofertas e novidades no perfil do Google. <em style="font-size:11px">(em breve)</em></p>
    </div>
    <div class="card" style="opacity:.5;cursor:default">
      <div class="card-icon">📊</div>
      <div class="card-title">Insights</div>
      <p class="card-desc">Visualizações, cliques e chamadas do perfil. <em style="font-size:11px">(em breve)</em></p>
    </div>
  </div>

  <!-- Reviews tab -->
  <div id="tab-reviews">
    <div class="section-head">
      <div>
        <div class="section-title">Reviews recentes</div>
        <div class="section-sub"><%= gbUser.google_biz_name %></div>
      </div>
      <button class="btn-sm" onclick="loadReviews()">↻ Atualizar</button>
    </div>
    <div class="review-list" id="review-list">
      <div class="empty"><div class="spinner"></div><p style="margin-top:16px">A carregar reviews...</p></div>
    </div>
  </div>

  <% } %>
</div>

<script>
const LANG = '<%= lang %>';

function starStr(rating) {
  const map = { ONE:1, TWO:2, THREE:3, FOUR:4, FIVE:5 };
  const n = map[rating] || 0;
  return '★'.repeat(n) + '☆'.repeat(5-n);
}

function timeAgo(dateStr) {
  if (!dateStr) return '';
  const diff = Date.now() - new Date(dateStr).getTime();
  const d = Math.floor(diff/86400000);
  if (d === 0) return 'hoje';
  if (d === 1) return 'ontem';
  if (d < 30)  return `há ${d} dias`;
  if (d < 365) return `há ${Math.floor(d/30)} meses`;
  return `há ${Math.floor(d/365)} anos`;
}

function renderReviews(reviews) {
  const list = document.getElementById('review-list');
  if (!reviews || reviews.length === 0) {
    list.innerHTML = '<div class="empty"><p>Nenhuma review encontrada.</p></div>';
    return;
  }
  list.innerHTML = reviews.map(r => {
    const reviewId = r.reviewId || r.name?.split('/').pop();
    const hasReply = r.reviewReply?.comment;
    return `
    <div class="review-card" id="review-${reviewId}">
      <div class="review-head">
        <div>
          <div class="review-author">${r.reviewer?.displayName || 'Anónimo'}</div>
          <div class="review-date">${timeAgo(r.createTime)}</div>
        </div>
        <div class="stars">${starStr(r.starRating)}</div>
      </div>
      ${r.comment ? `<p class="review-text">${escHtml(r.comment)}</p>` : '<p class="review-text" style="color:var(--muted);font-style:italic">Sem comentário.</p>'}
      ${hasReply ? `
        <div class="review-reply">
          <div class="review-reply-label">Resposta do proprietário</div>
          <p>${escHtml(r.reviewReply.comment)}</p>
        </div>` : ''}
      <div class="review-actions">
        <button class="btn-ai" onclick="suggestReply('${reviewId}', this)">✦ Sugerir resposta com IA</button>
        ${!hasReply ? `<button class="btn-sm" onclick="toggleReplyForm('${reviewId}')">Responder</button>` : `<button class="btn-sm" onclick="toggleReplyForm('${reviewId}')">Editar resposta</button>`}
      </div>
      <div class="reply-form" id="reply-form-${reviewId}">
        <textarea class="reply-input" id="reply-text-${reviewId}" placeholder="Escreva a sua resposta...">${hasReply ? escHtml(r.reviewReply.comment) : ''}</textarea>
        <div style="display:flex;gap:8px">
          <button class="btn-reply" onclick="submitReply('${reviewId}')">Publicar resposta</button>
          <button class="btn-sm" onclick="toggleReplyForm('${reviewId}')">Cancelar</button>
        </div>
      </div>
    </div>`;
  }).join('');
}

function escHtml(s) {
  return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

async function loadReviews() {
  document.getElementById('review-list').innerHTML = '<div class="empty"><div class="spinner"></div><p style="margin-top:16px">A carregar reviews...</p></div>';
  try {
    const r = await fetch('/google/api/reviews');
    const data = await r.json();
    if (data.error) {
      document.getElementById('review-list').innerHTML = `<div class="empty"><p>Erro: ${data.error}</p></div>`;
      return;
    }
    renderReviews(data.reviews || []);
  } catch(e) {
    document.getElementById('review-list').innerHTML = `<div class="empty"><p>Erro de rede.</p></div>`;
  }
}

function toggleReplyForm(reviewId) {
  const form = document.getElementById('reply-form-' + reviewId);
  form.classList.toggle('open');
  if (form.classList.contains('open')) {
    document.getElementById('reply-text-' + reviewId).focus();
  }
}

async function suggestReply(reviewId, btn) {
  const card = document.getElementById('review-' + reviewId);
  const comment = card.querySelector('.review-text')?.textContent?.trim() || '';
  const stars    = card.querySelector('.stars')?.textContent?.trim() || '';
  btn.textContent = '...';
  btn.disabled = true;
  try {
    const r = await fetch('/api/ai-reply', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ comment, stars, type: 'google_review' })
    });
    const data = await r.json();
    const textarea = document.getElementById('reply-text-' + reviewId);
    if (data.reply) {
      textarea.value = data.reply;
      document.getElementById('reply-form-' + reviewId).classList.add('open');
      textarea.focus();
    }
  } catch {}
  btn.textContent = '✦ Sugerir resposta com IA';
  btn.disabled = false;
}

async function submitReply(reviewId) {
  const comment = document.getElementById('reply-text-' + reviewId).value.trim();
  if (!comment) return;
  const btn = document.querySelector(`#review-${reviewId} .btn-reply`);
  btn.disabled = true; btn.textContent = 'A publicar...';
  try {
    const r = await fetch(`/google/api/reviews/${reviewId}/reply`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ comment })
    });
    const data = await r.json();
    if (data.comment !== undefined || data.name) {
      loadReviews();
    } else {
      alert('Erro: ' + JSON.stringify(data));
      btn.disabled = false; btn.textContent = 'Publicar resposta';
    }
  } catch {
    btn.disabled = false; btn.textContent = 'Publicar resposta';
  }
}

function showTab(tab) {
  // for future tabs
}

<% if (gbUser && gbUser.google_token) { %>
loadReviews();
<% } %>
</script>
</body>
</html>
