<?php /* views/pages/dicas.php — Página de Dicas (cards + modal vídeo) — dinâmica via banco */ ?>

<?php
require_once __DIR__ . '/../../app/db.php';
require_once __DIR__ . '/../../app/dicas_helpers.php';

// Carrega dicas ATIVAS do banco
$DICAS = [];
try {
    $stmt = db()->prepare("
        SELECT id, title, description, youtube_id, date_mode, custom_date, materials, created_at
        FROM public.custom_dicas
        WHERE active = true
        ORDER BY sort_order ASC, created_at DESC
    ");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows as $r) {
        $materials = is_string($r['materials']) ? json_decode($r['materials'], true) : $r['materials'];
        if (!is_array($materials)) $materials = [];

        $DICAS[] = [
            'id'        => (string)$r['id'],
            'title'     => $r['title'],
            'desc'      => $r['description'],
            'data'      => dicas_resolve_date($r['date_mode'], $r['custom_date'], $r['created_at']),
            'thumb'     => dicas_youtube_thumb_url($r['youtube_id']),
            'video'     => dicas_youtube_embed_url($r['youtube_id']),
            'materiais' => $materials,
        ];
    }
} catch (Throwable $e) {
    error_log('dicas.php: ' . $e->getMessage());
    $DICAS = [];
}
?>
<style>
:root{
  --ink:#0f172a;
  --muted:#64748b;
  --line:#e5e7eb;
  --card:#ffffff;
  --soft:#f8fafc;
  --shadow:0 8px 24px rgba(15,23,42,.06);
  --accent:#2563eb;
}
.page-wrap{max-width:1080px;margin:0 auto;padding:24px 16px;color:var(--ink)}

.hero{
  background:var(--card); border:1px solid var(--line); border-radius:16px;
  padding:20px; box-shadow:var(--shadow); margin-bottom:20px;
}
.hero h1{font-size:1.45rem;margin:0 0 6px;font-weight:800}
.hero p{margin:0;color:var(--muted)}

.empty-state{
  background:var(--card); border:1px solid var(--line); border-radius:16px;
  padding:60px 20px; text-align:center; box-shadow:var(--shadow);
}
.empty-state .emoji{font-size:3rem;margin-bottom:12px;display:block}
.empty-state h3{margin:0 0 8px;font-size:1.15rem;color:var(--ink)}
.empty-state p{margin:0;color:var(--muted)}

.grid{display:grid;gap:18px;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));}

.card{
  background:var(--card); border:1px solid var(--line); border-radius:12px;
  box-shadow:var(--shadow); overflow:hidden; cursor:pointer;
  transition:all .2s ease; display:flex; flex-direction:column;
}
.card:hover{transform:translateY(-4px);box-shadow:0 16px 48px rgba(15,23,42,.14);border-color:#cbd5e1;}

.card-thumb{
  position:relative; width:100%; height:180px;
  background:linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  overflow:hidden;
}
.card-thumb img{width:100%;height:100%;object-fit:cover;object-position:center;transition:transform .3s ease;}
.card:hover .card-thumb img{transform:scale(1.05);}

.card-thumb::after{
  content:"▶"; position:absolute; bottom:12px; right:12px;
  width:40px; height:40px; background:rgba(255,255,255,.95); border-radius:50%;
  display:flex; align-items:center; justify-content:center;
  font-size:14px; color:var(--accent); box-shadow:0 4px 12px rgba(0,0,0,.15); padding-left:3px;
}

.card-body{padding:16px;display:flex;flex-direction:column;gap:8px;flex:1;}
.card-meta{display:flex;align-items:center;gap:8px;font-size:.8rem;color:var(--muted);font-weight:500;}
.card-meta svg{width:14px;height:14px;opacity:.7;}
.card-body h3{margin:0;font-size:1.05rem;font-weight:700;line-height:1.4;color:var(--ink);}
.card-body p{margin:0;color:var(--muted);font-size:.9rem;line-height:1.5;flex:1;}

/* Modal */
.modal{
  position:fixed;inset:0;display:none;align-items:center;justify-content:center;
  background:rgba(2,6,23,.35);z-index:80;padding:20px;backdrop-filter:blur(4px);
}
.modal.is-open{display:flex}

.modal-card{
  width:100%; max-width:820px;
  background:var(--card); border:1px solid var(--line);
  border-radius:16px; box-shadow:0 24px 80px rgba(15,23,42,.16);
  padding:18px; position:relative;
  animation:modalIn .25s ease;
}
@keyframes modalIn{from{opacity:0;transform:scale(.96)}to{opacity:1;transform:scale(1)}}

.close{
  position:absolute; top:12px; right:12px;
  font-size:22px; font-weight:bold; cursor:pointer; color:var(--muted);
  width:32px; height:32px; display:flex; align-items:center; justify-content:center;
  border-radius:8px; transition:all .15s; z-index:2;
}
.close:hover{color:var(--ink);background:var(--soft);}

.video-wrapper{
  position:relative; width:100%; padding-bottom:56.25%;
  margin-bottom:16px; border-radius:12px; overflow:hidden; background:#000;
}
.video-wrapper iframe{position:absolute;inset:0;width:100%;height:100%;border:0;}

.mats{background:var(--soft);padding:16px;border-radius:12px;}
.mats h4{margin:0 0 10px;font-size:1rem;font-weight:800;color:var(--ink);}
.mats ul{margin:0;padding-left:18px;color:var(--ink)}
.mats li{margin:6px 0;color:var(--ink)}
.mats a{color:var(--accent);text-decoration:none;font-weight:600}
.mats a:hover{text-decoration:underline}

@media(max-width:640px){.grid{grid-template-columns:1fr}.card-thumb{height:200px}}
</style>

<div class="page-wrap">

  <div class="hero">
    <h1>Dicas</h1>
    <p>Guia com estratégias, táticas e boas práticas para você extrair o máximo da plataforma.</p>
  </div>

  <?php if (empty($DICAS)): ?>
    <div class="empty-state">
      <span class="emoji">💡</span>
      <h3>Nenhuma dica disponível ainda</h3>
      <p>Em breve compartilharemos novas dicas e estratégias por aqui!</p>
    </div>
  <?php else: ?>
    <div class="grid">
      <?php foreach($DICAS as $d): ?>
        <div class="card" data-open="<?= htmlspecialchars($d['id']) ?>">
          <div class="card-thumb">
            <img src="<?= htmlspecialchars($d['thumb']) ?>" alt="<?= htmlspecialchars($d['title']) ?>" loading="lazy">
          </div>
          <div class="card-body">
            <?php if (!empty($d['data'])): ?>
            <div class="card-meta">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
              </svg>
              <span><?= htmlspecialchars($d['data']) ?></span>
            </div>
            <?php endif; ?>
            <h3><?= htmlspecialchars($d['title']) ?></h3>
            <p><?= htmlspecialchars($d['desc']) ?></p>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>

</div>

<!-- Modais (1 por dica) -->
<?php foreach($DICAS as $d): ?>
<div class="modal" id="modal-<?= htmlspecialchars($d['id']) ?>" data-video="<?= htmlspecialchars($d['video']) ?>">
  <div class="modal-card">
    <div class="close" data-close>&times;</div>

    <!-- Vídeo (iframe sem src — JS preenche ao abrir) -->
    <div class="video-wrapper">
      <iframe
        allowfullscreen
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        referrerpolicy="strict-origin-when-cross-origin"></iframe>
    </div>

    <?php if(!empty($d['materiais'])): ?>
      <div class="mats">
        <h4>Materiais citados no vídeo:</h4>
        <ul>
        <?php foreach($d['materiais'] as $m): ?>
          <li><a href="<?= htmlspecialchars($m['url']) ?>" target="_blank" rel="noopener noreferrer"><?= htmlspecialchars($m['nome']) ?></a></li>
        <?php endforeach; ?>
        </ul>
      </div>
    <?php endif; ?>

  </div>
</div>
<?php endforeach; ?>

<script>
(function(){
  const $$ = (s, el=document) => Array.from(el.querySelectorAll(s));

  // Helper: pega o iframe do modal e seta/limpa o src
  function loadVideo(modal) {
    const iframe = modal.querySelector('iframe');
    const url = modal.dataset.video;
    if (iframe && url) {
      iframe.setAttribute('src', url);
    }
  }
  function stopVideo(modal) {
    const iframe = modal.querySelector('iframe');
    if (iframe) {
      iframe.removeAttribute('src');  // remove o atributo inteiro (não bota string vazia!)
    }
  }

  // Abrir modal
  $$('.card').forEach(card => {
    card.addEventListener('click', () => {
      const id = card.dataset.open;
      const modal = document.querySelector('#modal-' + CSS.escape(id));
      if (modal) {
        modal.classList.add('is-open');
        loadVideo(modal);
      }
    });
  });

  // Fechar modal (clique fora ou no X)
  $$('.modal').forEach(modal => {
    modal.addEventListener('click', e => {
      if (e.target.classList.contains('modal') || e.target.dataset.close !== undefined) {
        modal.classList.remove('is-open');
        stopVideo(modal);
      }
    });
  });

  // ESC fecha
  document.addEventListener('keydown', e => {
    if (e.key === 'Escape') {
      $$('.modal.is-open').forEach(m => {
        m.classList.remove('is-open');
        stopVideo(m);
      });
    }
  });
})();
</script>