<?php
require_once __DIR__ . '/inc/template.php';
require_once __DIR__ . '/inc/zones.php'; // pour admin_connecte()

page_active('minute-sante');
page_title('La Minute Santé, vidéos conseils');
page_desc('Les vidéos « Minute Santé » de Hérald Loygue : conseils de médecine chinoise, Tuina, alimentation, méridiens et bien-être. Triez par thème.');

$est_admin = function_exists('admin_connecte') && admin_connecte();

// Récupération des vidéos publiées (+ brouillons si admin)
$sql = "SELECT * FROM minutes_sante WHERE statut='publie'";
if ($est_admin) $sql = "SELECT * FROM minutes_sante";
$sql .= " ORDER BY theme, position, id";
$videos = db()->query($sql)->fetchAll(PDO::FETCH_ASSOC);

// Liste des thèmes présents (pour le filtre)
$themes = [];
foreach ($videos as $v) { $t = $v['theme'] ?: 'Divers'; $themes[$t] = ($themes[$t] ?? 0) + 1; }
ksort($themes);

$tok = function_exists('csrf_token') ? csrf_token() : '';

ob_start();
?>
<section class="page-hero">
  <div class="grain"></div>
  <div class="wrap">
    <?= fil_ariane([['La Minute Santé', null]]) ?>
    <div class="kick tag">Vidéos conseils</div>
    <?php zone_texte('hero.minutesante.titre', '<h1 class="cor">La Minute Santé</h1>'); ?>
    <?php zone_texte('hero.minutesante.lead', '<p class="lead">De courtes vidéos où je partage des conseils de médecine chinoise, des gestes d\'automassage, et des repères d\'alimentation et de bien-être à appliquer au quotidien.</p>'); ?>
  </div>
</section>

<?php section_ouvrir('minute-sante.1','wrap ms-section'); ?>

  <?php if ($est_admin): ?>
  <div class="ms-admin">
    <button type="button" class="btn btn-blue" id="msAddToggle">＋ Ajouter une vidéo</button>
    <div class="ms-admin-form" id="msAddForm" style="display:none">
      <div class="ms-af-row">
        <label>Lien de la vidéo Facebook
          <input type="text" id="msLien" placeholder="https://www.facebook.com/herald.loygue/videos/123456789/">
        </label>
      </div>
      <div class="ms-af-row ms-af-2">
        <label>Titre
          <input type="text" id="msTitre" placeholder="Ex. : Le Gingembre">
        </label>
        <label>Thème
          <input type="text" id="msTheme" list="msThemesList" placeholder="Ex. : Alimentation">
          <datalist id="msThemesList">
            <?php foreach (array_keys($themes) as $t): ?><option value="<?= e($t) ?>"></option><?php endforeach; ?>
          </datalist>
        </label>
      </div>
      <div class="ms-af-actions">
        <button type="button" class="btn btn-blue" id="msSave">Ajouter</button>
        <span id="msMsg" class="ms-msg"></span>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Filtre par thème -->
  <div class="ms-filters" id="msFilters">
    <button type="button" class="ms-chip is-active" data-theme="*">Toutes <span><?= count($videos) ?></span></button>
    <?php foreach ($themes as $t => $n): ?>
      <button type="button" class="ms-chip" data-theme="<?= e($t) ?>"><?= e($t) ?> <span><?= (int)$n ?></span></button>
    <?php endforeach; ?>
  </div>

  <div class="ms-grid" id="msGrid">
    <?php foreach ($videos as $v):
      $vid = $v['fb_video_id'];
      $theme = $v['theme'] ?: 'Divers';
      $titre = $v['titre'] ?: 'Minute Santé';
      $href = 'https://www.facebook.com/herald.loygue/videos/' . $vid . '/';
      $embed = 'https://www.facebook.com/plugins/video.php?href=' . rawurlencode($href) . '&show_text=false&width=320&height=400';
    ?>
    <div class="ms-card" data-theme="<?= e($theme) ?>">
      <div class="ms-player" data-embed="<?= htmlspecialchars($embed, ENT_QUOTES) ?>">
        <button type="button" class="ms-play" aria-label="Lire : <?= e($titre) ?>">
          <span class="ms-play-ico">&#9658;</span>
        </button>
      </div>
      <div class="ms-meta">
        <div class="ms-theme"><?= e($theme) ?></div>
        <div class="ms-titre cor"><?= e($titre) ?></div>
      </div>
      <?php if ($est_admin): ?>
        <button type="button" class="ms-del" data-id="<?= (int)$v['id'] ?>" title="Supprimer">&times;</button>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
  </div>

  <p class="ms-note">Les vidéos sont hébergées sur Facebook. Cliquez sur une vignette pour lancer la lecture.</p>
<?php section_fermer(); ?>

<style>
.ms-section{padding-bottom:4rem}
.ms-filters{display:flex;flex-wrap:wrap;gap:.6rem;margin:1.5rem 0 2rem}
.ms-chip{border:1px solid var(--line,#ddd6c8);background:#fff;border-radius:30px;padding:.45rem 1rem;font-size:.88rem;cursor:pointer;color:var(--ink2,#6b6256);transition:all .18s;display:inline-flex;align-items:center;gap:.4rem}
.ms-chip span{font-size:.78rem;opacity:.6}
.ms-chip:hover{border-color:var(--gold,#c19a6b)}
.ms-chip.is-active{background:var(--gold,#c19a6b);border-color:var(--gold,#c19a6b);color:#fff}
.ms-chip.is-active span{opacity:.85}
.ms-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:1.4rem}
@media(max-width:1000px){.ms-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:560px){.ms-grid{grid-template-columns:1fr}}
.ms-card{position:relative;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 4px 16px rgba(16,23,26,.07);display:flex;flex-direction:column}
.ms-player{position:relative;width:100%;aspect-ratio:4/3;background:#10171a;display:flex;align-items:center;justify-content:center}
.ms-player iframe{position:absolute;inset:0;width:100%;height:100%;border:0}
.ms-play{background:none;border:none;cursor:pointer;width:100%;height:100%;display:flex;align-items:center;justify-content:center;transition:background .2s}
.ms-play:hover{background:rgba(193,154,107,.18)}
.ms-play-ico{display:flex;align-items:center;justify-content:center;width:54px;height:54px;border-radius:50%;background:var(--gold,#c19a6b);color:#fff;font-size:1.3rem;padding-left:4px;box-shadow:0 4px 14px rgba(0,0,0,.3)}
.ms-meta{padding:.8rem .9rem 1rem}
.ms-theme{font-size:.72rem;letter-spacing:.08em;text-transform:uppercase;color:var(--gold,#c19a6b);margin-bottom:.25rem}
.ms-titre{font-size:1rem;line-height:1.3;color:var(--ink,#2a2620)}
.ms-del.is-armed{width:auto;border-radius:14px;padding:0 .6rem;font-size:.72rem;font-weight:600;background:#b42828}
.ms-note{margin-top:2rem;text-align:center;color:var(--ink2,#6b6256);font-size:.9rem}
.ms-del{position:absolute;top:.5rem;right:.5rem;z-index:3;width:28px;height:28px;border-radius:50%;border:none;background:rgba(180,40,40,.85);color:#fff;font-size:1.1rem;line-height:1;cursor:pointer}
.ms-admin{background:var(--bg,#f5f1e8);border:1px dashed var(--gold,#c19a6b);border-radius:12px;padding:1.2rem 1.4rem;margin-bottom:1rem}
.ms-admin-form{margin-top:1rem}
.ms-af-row{margin-bottom:.8rem}
.ms-af-2{display:grid;grid-template-columns:1fr 1fr;gap:1rem}
.ms-admin label{display:block;font-size:.85rem;color:var(--ink2,#6b6256)}
.ms-admin input{width:100%;padding:.55rem;border:1px solid var(--line,#ddd6c8);border-radius:6px;margin-top:.3rem;font-size:.9rem}
.ms-af-actions{display:flex;align-items:center;gap:1rem}
.ms-msg{font-size:.85rem}
.ms-msg.ok{color:#2e7d32}.ms-msg.err{color:#c0392b}
</style>

<script>
(function(){
  // Lecture au clic
  function bindPlay(p){
    var btn = p.querySelector('.ms-play'); if(!btn) return;
    btn.addEventListener('click', function(){
      var f = document.createElement('iframe');
      f.src = p.getAttribute('data-embed');
      f.setAttribute('scrolling','no'); f.setAttribute('frameborder','0');
      f.setAttribute('allowfullscreen','true');
      f.setAttribute('allow','autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share');
      p.innerHTML=''; p.appendChild(f);
    });
  }
  document.querySelectorAll('.ms-player').forEach(bindPlay);

  // Filtre par thème
  var grid = document.getElementById('msGrid');
  document.querySelectorAll('.ms-chip').forEach(function(chip){
    chip.addEventListener('click', function(){
      document.querySelectorAll('.ms-chip').forEach(function(c){c.classList.remove('is-active');});
      chip.classList.add('is-active');
      var t = chip.getAttribute('data-theme');
      grid.querySelectorAll('.ms-card').forEach(function(card){
        card.style.display = (t==='*' || card.getAttribute('data-theme')===t) ? '' : 'none';
      });
    });
  });

  // Admin : ajout / suppression
  var tok = <?= json_encode($tok) ?>;
  var toggle = document.getElementById('msAddToggle');
  if(toggle){
    toggle.addEventListener('click', function(){
      var f=document.getElementById('msAddForm');
      f.style.display = f.style.display==='none' ? 'block' : 'none';
    });
    document.getElementById('msSave').addEventListener('click', function(){
      var msg=document.getElementById('msMsg'); msg.className='ms-msg'; msg.textContent='Envoi…';
      var fd=new FormData();
      fd.append('csrf',tok); fd.append('action','add');
      fd.append('lien',document.getElementById('msLien').value);
      fd.append('titre',document.getElementById('msTitre').value);
      fd.append('theme',document.getElementById('msTheme').value);
      fetch('/admin/minute_action.php',{method:'POST',body:fd,credentials:'same-origin'})
        .then(r=>r.json()).then(function(res){
          if(res.ok){ msg.className='ms-msg ok'; msg.textContent='Ajoutée ! Rechargement…'; setTimeout(function(){location.reload();},700); }
          else { msg.className='ms-msg err'; msg.textContent=res.err||'Erreur.'; }
        }).catch(function(){ msg.className='ms-msg err'; msg.textContent='Erreur réseau.'; });
    });
  }
  document.querySelectorAll('.ms-del').forEach(function(b){
    var armed=false, timer=null;
    function disarm(){ armed=false; b.classList.remove('is-armed'); b.innerHTML='&times;'; b.title='Supprimer'; if(timer){clearTimeout(timer);timer=null;} }
    b.addEventListener('click', function(e){
      e.stopPropagation();
      if(!armed){
        // 1er clic : on arme le bouton, il faut recliquer pour confirmer
        armed=true; b.classList.add('is-armed'); b.innerHTML='Confirmer&nbsp;?'; b.title='Cliquez à nouveau pour supprimer';
        timer=setTimeout(disarm,3000);
        return;
      }
      // 2e clic dans les 3 s : suppression réelle
      disarm();
      var fd=new FormData(); fd.append('csrf',tok); fd.append('action','delete'); fd.append('id',b.getAttribute('data-id'));
      fetch('/admin/minute_action.php',{method:'POST',body:fd,credentials:'same-origin'})
        .then(r=>r.json()).then(function(res){ if(res.ok) b.closest('.ms-card').remove(); });
    });
  });
})();
</script>
<?php
render_page(ob_get_clean());
