<?php
session_start();
if(!isset($_SESSION['user_id'])){ header('Location: login.php'); exit; }
?>
<!DOCTYPE html>
<html lang="fr" data-theme="system">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Streambox – Signalements & Ajouts</title>
  <meta name="description" content="Signaler un bug ou demander l’ajout d’un film/série sur Streambox." />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
  <style>
    /* === LIQUID GLASS THEME === */
    :root{ 
        --bg:#0f172a; --glass:rgba(30, 41, 59, 0.65); --glass-border:rgba(255,255,255,0.08); 
        --pri:#6366f1; --pri-2:#818cf8; --txt:#f1f5f9; --muted:#94a3b8; 
        --ok:#10b981; --warn:#f59e0b; --danger:#ef4444; 
        --radius:16px; --shadow:0 8px 32px rgba(0,0,0,0.2);
        --section-gap:64px; --block-gap:20px; --line:1.6;
    }

    *{box-sizing:border-box}
    html,body{
        margin:0;padding:0;
        background:var(--bg); 
        background-image: 
            radial-gradient(circle at 0% 0%, rgba(99, 102, 241, 0.15), transparent 40%), 
            radial-gradient(circle at 100% 100%, rgba(168, 85, 247, 0.15), transparent 40%);
        background-attachment: fixed;
        color:var(--txt); 
        font-family:Inter, system-ui, -apple-system, sans-serif;
    }
    body{line-height:var(--line)}
    a{color:var(--pri);text-decoration:none}
    img{max-width:100%;height:auto;vertical-align:middle}
    .container{max-width:1100px;margin:0 auto;padding:0 20px}
    h1{font-size:clamp(26px,4.8vw,40px);line-height:1.15;margin:0 0 8px;font-weight:800;letter-spacing:-.02em}
    .subtitle{color:var(--muted);margin:0 0 6px}

    /* ALERT MESSAGE STYLE */
    .alert-message {
        background: rgba(255, 71, 87, 0.15);
        border: 1px solid var(--danger);
        color: var(--danger);
        padding: 16px;
        border-radius: var(--radius);
        margin-bottom: 30px;
        text-align: center;
        font-weight: 700;
        line-height: 1.5;
        box-shadow: 0 4px 15px rgba(255, 71, 87, 0.1);
    }

    /* HEADER */
    header{position:sticky;top:0;z-index:60;background:rgba(15, 23, 42, 0.8);backdrop-filter:blur(12px); border-bottom: 1px solid var(--glass-border);}
    .nav{display:flex;align-items:center;justify-content:space-between;padding:14px 0}
    .brand{display:flex;align-items:center;gap:10px;font-weight:800;color:inherit}
    .brand img{width:34px;height:34px;border-radius:10px;object-fit:cover;box-shadow:var(--shadow)}
    .brand{text-decoration:none}
    .nav-actions{display:flex;align-items:center;gap:12px}
    .nav-links{display:flex;gap:14px;align-items:center}
    .nav-links a{font-weight:600;color:var(--txt);opacity:.9}
    .nav-links a:hover{color:var(--pri);}
    .btn{display:inline-flex;align-items:center;gap:10px;padding:12px 16px;border-radius:12px;border:1px solid transparent;cursor:pointer;font-weight:700}
    .btn-primary{background:linear-gradient(135deg,var(--pri),var(--pri-2));color:#fff;box-shadow:0 4px 15px rgba(99, 102, 241, 0.4);}
    .btn-primary:hover{transform:translateY(-2px); box-shadow:0 8px 25px rgba(99, 102, 241, 0.5);}
    .btn-ghost{background:rgba(255,255,255,0.05);border-color:var(--glass-border);color:var(--txt)}
    .toggle{padding:10px 12px;border-radius:12px;border:1px solid var(--border);background:transparent}

    /* Hamburger mobile */
    .hamburger{display:none; width:42px; height:42px; border:1px solid var(--glass-border); border-radius:12px; background:transparent; align-items:center; justify-content:center}
    .hamburger span{display:block; width:20px; height:2px; background:var(--txt); position:relative}
    .hamburger span::before,.hamburger span::after{content:""; position:absolute; left:0; width:100%; height:2px; background:var(--txt)}
    .hamburger span::before{top:-6px} .hamburger span::after{top:6px}
    .menu-panel{display:none; position:absolute; top:100%; left:0; right:0; background:rgba(15, 23, 42, 0.95); backdrop-filter:blur(20px); border-top:1px solid var(--glass-border); box-shadow:var(--shadow)}
    .menu-panel a{display:block; padding:14px 20px; border-bottom:1px solid var(--border); color:var(--txt); font-weight:600}
    .menu-open .menu-panel{display:block}
    @media (max-width:820px){
      .nav-links{display:none}
      .hamburger{display:inline-flex}
    }

    /* LAYOUT */
    .section{padding:calc(var(--section-gap) - 24px) 0 var(--section-gap); position:relative; z-index: 1;}
    .section::before{content:""; position:absolute; left:0; right:0; top:0; height:1px; background:linear-gradient(90deg, transparent, var(--glass-border), transparent);}
    .grid{display:grid;gap:var(--block-gap)}
    @media (min-width:900px){ .grid-2{grid-template-columns:repeat(2,1fr)} }

    /* CARDS + FORM */
    .card{background:var(--glass); backdrop-filter:blur(16px); -webkit-backdrop-filter:blur(16px); border:1px solid var(--glass-border); border-radius:var(--radius); padding:24px; box-shadow:var(--shadow); animation: slideUp 0.6s cubic-bezier(0.16, 1, 0.3, 1);}
    label{font-weight:700;font-size:.95rem}
    .field{width:100%;padding:12px;border-radius:10px;border:1px solid var(--glass-border);background:rgba(15, 23, 42, 0.6);color:var(--txt);margin:6px 0 16px; transition: border-color 0.2s;}
    .field:focus{border-color:var(--pri); outline:none;}
    textarea.field{min-height:110px;resize:vertical}
    .step-card{margin-top:14px; scroll-margin-top: 100px;} /* chaque étape apparaît dans sa propre carte */

    /* SUGGESTIONS TMDB */
    .field-wrap{position:relative}
    .suggestions{
      position:absolute; left:0; right:0; top:100%;
      background:rgba(30, 41, 59, 0.95); backdrop-filter:blur(10px);
      border:1px solid var(--glass-border); border-radius:10px; margin-top:6px;
      max-height:260px; overflow:auto; z-index:20; box-shadow:var(--shadow)
    }
    .sug-item{display:flex;align-items:center;gap:10px;padding:8px 10px;border-bottom:1px solid var(--glass-border);cursor:pointer}
    .sug-item:last-child{border-bottom:none}
    .sug-item:hover{background:rgba(255,255,255,0.05)}
    .sug-img{width:40px;height:60px;object-fit:cover;border-radius:6px;border:1px solid var(--glass-border);background:#111}
    .platform-value{color:var(--pri);font-weight:800;margin:-4px 0 10px;display:block}

    .hidden{display:none}

    /* FOOTER */
    footer{padding:40px 0;color:var(--muted);border-top:1px solid var(--glass-border)}

    /* === Animation apparitions === */
    @keyframes pop-reveal {
      from { opacity:0; transform: translateY(10px) scale(0.98); }
      to   { opacity:1; transform: translateY(0) scale(1); }
    }
    @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
    .animate-in {
      animation: pop-reveal .32s cubic-bezier(.2,.6,.2,1) var(--delay,0ms) both;
      will-change: transform, opacity;
    }
    @media (prefers-reduced-motion: reduce){
      .animate-in { animation: none; }
    }

    /* Empêche le zoom automatique sur mobile lors de la saisie */
    @media (max-width: 768px) {
      input, select, textarea, .field {
        font-size: 16px !important;
      }
    }
  </style>

</head>
<body>

  <header>
    <div class="container nav">
      <a href="index.html" class="brand" aria-label="Aller en haut">
        <img src="logo.png" alt="Logo Streambox" />
        <span>Streambox</span>
      </a>

      <div class="nav-actions">
        <nav class="nav-links" aria-label="Navigation principale">
          <a href="index.html">Accueil</a>
          <a href="dashboard.php">Espace Client</a>
          <a href="logout.php" style="opacity: 0.7;">Déconnexion</a>
        </nav>
        <button id="themeToggle" class="toggle" aria-label="Basculer le thème">🌓</button>
        <button id="hamburger" class="hamburger" aria-label="Ouvrir le menu" aria-expanded="false" aria-controls="menu-panel"><span></span></button>
      </div>
    </div>
    <div id="menu-panel" class="menu-panel container" role="navigation" aria-label="Menu mobile">
          <a href="index.html">Accueil</a>
          <a href="dashboard.php">Espace Client</a>
          <a href="logout.php">Déconnexion</a>
    </div>
  </header>

  <main class="container section">

    <h1>📮 Signalement / Demande d’ajout</h1>
    <p class="subtitle">Choisissez une catégorie, puis précisez votre demande.</p>

    <div class="card">
      <div class="grid grid-2">
        <div>
          <label for="pseudo">Pseudo du compte</label>
          <input class="field" id="pseudo" value="<?= htmlspecialchars($_SESSION['username']) ?>" disabled style="opacity:0.7; cursor:not-allowed">
        </div>
        <div>
          <label for="email">Adresse e-mail</label>
          <input class="field" id="email" type="email" value="<?= htmlspecialchars($_SESSION['email']) ?>" disabled style="opacity:0.7; cursor:not-allowed">
        </div>
      </div>
      <div style="margin-top:4px">
        <label for="main-category">Catégorie</label>
        <select class="field" id="main-category" onchange="onCategoryChange()">
          <option value="">— Choisir —</option>
          <option value="bug">Signalement de bugs</option>
          <option value="ajout">Demande d’ajout</option>
        </select>
      </div>
    </div>

    <div id="step-bug-chooser" class="card step-card hidden">
      <label for="bug-type">Type de bug</label>
      <select class="field" id="bug-type" onchange="onBugTypeChange()">
        <option value="">— Choisir —</option>
        <option value="Bug chaine TV">Bug chaîne TV</option>
        <option value="Bug Film">Bug Film</option>
        <option value="Bug Série">Bug Série</option>
      </select>
    </div>

    <form id="form-bug-chaine" class="card step-card hidden" onsubmit="event.preventDefault(); submitForm();">
      <h3 style="margin:0 0 6px">Signalement — Chaîne TV</h3>
      <div class="grid grid-2">
        <div>
          <label for="chaine">Chaîne</label>
          <select class="field" id="chaine">
            <option value="">— Sélectionner —</option>
            <option>TF1</option><option>France 2</option><option>France 3</option><option>France 4</option><option>France 5</option><option>M6</option><option>Arte</option><option>T18 (Nouvelle chaine)</option><option>W9</option><option>TMC</option><option>TFX</option><option>Syfy</option><option>BFM TV</option><option>LCI</option><option>TF1 Séries Films</option><option>6ter</option><option>Teva</option><option>RTL9</option><option>France Info</option><option>Cnews</option><option>Chérie 25</option><option>LCP - Assemblée nationale</option><option>Canal+</option><option>CANAL + CINEMA</option><option>CANAL+ GRAND ECRAN</option><option>CANAL + SERIES</option><option>CINE+ CLUB</option><option>CINE EMOTION</option><option>CINE PREMIER</option><option>CINE FRISSON</option><option>CINE FAMIZ</option><option>CINE CLASSIC</option><option>Canal+  Foot</option><option>Canal+ Foot (Secours)</option><option>Canal+ Sport 360</option><option>Canal+ Sport</option><option>Canal+ Premier League</option><option>Canal+ Golf</option><option>Canal + Infosport</option><option>Canal+ UHD 4K</option><option>RMC Sport 1</option><option>RMC SPORT 1 (Secours)</option><option>RMC Sport 2</option><option>RMC Sport 3</option><option>RMC Sport 4</option><option>RMC Sport 5</option><option>RMC Sport 6</option><option>Bein Sports 1</option><option>Bein Sports 2</option><option>Bein Sports 3</option><option>Bein Sport Max 4</option><option>Bein Sports Max 5</option><option>Bein Sport Max 6</option><option>Bein Sports Max 7</option><option>Sport en France</option><option>LIGUE 1 PLUS N°1</option><option>LIGUE 1 PLUS N°2</option><option>LIGUE 1 PLUS N°3</option><option>LIGUE 1 PLUS N°4</option><option>EUROSPORT 1</option><option>EUROSPORT 2</option><option>L'équipe</option><option>L'équipe Live 1</option><option>L'équipe Live 2</option><option>Automoto</option><option>Equidia Live</option><option>Chasse & Pêche</option><option>Seasons</option><option>RMC Découverte</option><option>MTV Hits</option><option>Cstar</option><option>M6 Music</option><option>RMC Story</option><option>Meezo TV</option><option>PARAMOUNT +</option><option>CANAL+ KIDS</option><option>Cartoon Network</option><option>Boomerang</option><option>Piwi+</option><option>Nickelodeon</option><option>Teletoon +</option><option>Tiji</option><option>Gulli</option><option>Canal J</option><option>Nickelodeon Junior</option><option>Nickelodeon Teen</option>
          </select>
        </div>
        <div>
          <label for="bug-chaine-type">Type de bug / demande</label>
          <select class="field" id="bug-chaine-type">
            <option>Programme en boucle</option><option>Qualité basse</option><option>Bug image / son</option><option>Demande redémarrage chaine</option>
          </select>
        </div>
      </div>
      <button class="btn btn-primary" type="submit">Envoyer</button>
    </form>

    <form id="form-bug-film" class="card step-card hidden" onsubmit="event.preventDefault(); submitForm();">
      <h3 style="margin:0 0 6px">Signalement — Film</h3>
      <div class="field-wrap">
        <label>Nom du film</label>
        <input class="field" id="film-nom" autocomplete="off"
               oninput="searchTMDB('film', this.value, 'film-nom', 'film-annee', 'tmdb-film-suggestions-bug', undefined, 'film-tmdbid', 'film-poster')">
        <input type="hidden" id="film-tmdbid"><input type="hidden" id="film-poster">
        <div id="tmdb-film-suggestions-bug" class="suggestions"></div>
      </div>
      <label>Année</label><input class="field" id="film-annee" autocomplete="off">
      <label>Description du bug</label><textarea class="field" id="film-bug"></textarea>
      <button class="btn btn-primary" type="submit">Envoyer</button>
    </form>

    <form id="form-bug-serie" class="card step-card hidden" onsubmit="event.preventDefault(); submitForm();">
      <h3 style="margin:0 0 6px">Signalement — Série</h3>
      <div class="field-wrap">
        <label>Nom de la série</label>
        <input class="field" id="serie-nom" autocomplete="off"
               oninput="searchTMDB('serie', this.value, 'serie-nom', 'serie-annee', 'tmdb-serie-suggestions-bug', 'serie-platform', 'serie-tmdbid', 'serie-poster')">
        <input type="hidden" id="serie-tmdbid"><input type="hidden" id="serie-poster">
        <div id="tmdb-serie-suggestions-bug" class="suggestions"></div>
      </div>
      <span id="serie-platform" class="platform-value"></span>
      <div class="grid grid-2">
        <div><label>Année</label><input class="field" id="serie-annee"></div>
        <div><label>Saison</label><input class="field" id="serie-saison"></div>
      </div>
      <div class="grid grid-2">
        <div><label>Épisode</label><input class="field" id="serie-episode"></div>
        <div><label>Description du bug</label><textarea class="field" id="serie-bug"></textarea></div>
      </div>
      <button class="btn btn-primary" type="submit">Envoyer</button>
    </form>

    <div id="step-ajout-chooser" class="card step-card hidden">
      <label for="ajout-type">Type d’ajout</label>
      <select class="field" id="ajout-type" onchange="onAjoutTypeChange()">
        <option value="">— Choisir —</option>
        <option value="film">Ajout Film</option>
        <option value="serie">Ajout Série</option>
      </select>
    </div>

    <form id="form-ajout-film" class="card step-card hidden" onsubmit="event.preventDefault(); submitForm();">
      <h3 style="margin:0 0 6px">Demande d’ajout — Film</h3>
      <div class="field-wrap">
        <label>Nom du film</label>
        <input class="field" id="ajout-film-titre" autocomplete="off"
               oninput="searchTMDB('film', this.value, 'ajout-film-titre', 'ajout-film-annee', 'tmdb-film-suggestions', undefined, 'ajout-film-tmdbid', 'ajout-film-poster')">
        <input type="hidden" id="ajout-film-tmdbid"><input type="hidden" id="ajout-film-poster">
        <div id="tmdb-film-suggestions" class="suggestions"></div>
      </div>
      <label>Année de sortie</label><input class="field" id="ajout-film-annee" autocomplete="off">
      <button class="btn btn-primary" type="submit">Envoyer</button>
    </form>

    <form id="form-ajout-serie" class="card step-card hidden" onsubmit="event.preventDefault(); submitForm();">
      <h3 style="margin:0 0 6px">Demande d’ajout — Série</h3>
      <div class="field-wrap">
        <label>Nom de la série</label>
        <input class="field" id="ajout-serie-titre" autocomplete="off"
               oninput="searchTMDB('serie', this.value, 'ajout-serie-titre', 'ajout-serie-annee', 'tmdb-serie-suggestions', 'ajout-serie-platform', 'ajout-serie-tmdbid', 'ajout-serie-poster')">
        <input type="hidden" id="ajout-serie-tmdbid"><input type="hidden" id="ajout-serie-poster">
        <div id="tmdb-serie-suggestions" class="suggestions"></div>
      </div>
      <span id="ajout-serie-platform" class="platform-value"></span>
      <div class="grid grid-2">
        <div><label>Numéro de la saison</label><input class="field" id="ajout-serie-saison" autocomplete="off"></div>
        <div><label>Année de sortie</label><input class="field" id="ajout-serie-annee" autocomplete="off"></div>
      </div>
      <button class="btn btn-primary" type="submit">Envoyer</button>
    </form>

  </main>

  <footer>
    <div class="container" style="text-align: center; color: var(--muted); font-size: 0.9em; padding: 20px 0;">
        <p style="margin: 0;">© <span id="y"></span> Streambox | <a href="index.html#faq">Conditions</a> · <a href="index.html#faq">Confidentialité</a></p>
        <p style="margin-top: 10px;">Pour nous contacter : streamboxtv@protonmail.com</p>
    </div>
  </footer>

  <script>
    // Year
    document.getElementById('y').textContent=new Date().getFullYear();

    // THEME
    const htmlEl=document.documentElement, key='streambox-theme';
    const saved=localStorage.getItem(key); if(saved){ htmlEl.setAttribute('data-theme', saved); }
    const themeBtn=document.getElementById('themeToggle');
    const cycle={'system':'light','light':'dark','dark':'system'};
    const labels={'system':'🌓','light':'🌞','dark':'🌙'};
    function updateIcon(){ if(themeBtn) themeBtn.textContent = labels[htmlEl.getAttribute('data-theme')] || '🌓'; }
    updateIcon();
    themeBtn?.addEventListener('click', ()=>{
      const cur=htmlEl.getAttribute('data-theme')||'system';
      const next=cycle[cur]; htmlEl.setAttribute('data-theme', next); localStorage.setItem(key,next); updateIcon();
    });

    // MENU MOBILE
    const burger=document.getElementById('hamburger');
    const panel=document.getElementById('menu-panel');
    function setExpanded(v){ burger?.setAttribute('aria-expanded', v?'true':'false'); }
    burger?.addEventListener('click', ()=>{
      const open=document.body.classList.toggle('menu-open');
      setExpanded(open);
      if(open){ panel.scrollTop=0; }
    });
    window.addEventListener('scroll',()=>{ if(document.body.classList.contains('menu-open')){ document.body.classList.remove('menu-open'); setExpanded(false);} });

    // ===== TMDB =====
    const TMDB_API_KEY='306c7c7c062d4015a2ea69eee179b37c';
    const TMDB_IMG='https://image.tmdb.org/t/p/w500';

    function searchTMDB(type, query, fieldTitleId, fieldYearId, suggestionsId, platformSpanId, tmdbIdField, posterField){
      const sug=document.getElementById(suggestionsId);
      if(platformSpanId) document.getElementById(platformSpanId).textContent='';
      if(!query || query.trim().length<2){ sug.innerHTML=''; return; }
      const endpoint = type==='film' ? 'movie' : 'tv';
      fetch(`https://api.themoviedb.org/3/search/${endpoint}?api_key=${TMDB_API_KEY}&query=${encodeURIComponent(query)}&language=fr-FR`)
        .then(r=>r.json()).then(data=>{
          sug.innerHTML='';
          (data.results||[]).slice(0,10).forEach(item=>{
            const title = type==='film' ? (item.title||'') : (item.name||'');
            const year = (item.release_date||item.first_air_date||'').slice(0,4);
            const poster = item.poster_path ? (TMDB_IMG+item.poster_path) : 'https://via.placeholder.com/40x60?text=?';
            const tmdbid = item.id;
            const div=document.createElement('div'); div.className='sug-item';
            div.innerHTML=`<img class="sug-img" src="${poster}" alt="">
                           <div><div style="font-weight:700">${title}</div><div class="subtitle" style="margin:0">${year||''}</div></div>`;
            div.onclick=()=>{
              document.getElementById(fieldTitleId).value=title;
              if(fieldYearId) document.getElementById(fieldYearId).value=year||'';
              if(tmdbIdField) document.getElementById(tmdbIdField).value=tmdbid;
              if(posterField) document.getElementById(posterField).value=poster;
              sug.innerHTML='';
              if(type==='serie' && platformSpanId){ fetchProviders(tmdbid, platformSpanId); }
            };
            sug.appendChild(div);
          });
        });
    }

    function fetchProviders(tvId, spanId){
      fetch(`https://api.themoviedb.org/3/tv/${tvId}/watch/providers?api_key=${TMDB_API_KEY}`)
        .then(r=>r.json()).then(data=>{
          let providers=[];
          if(data.results?.FR?.flatrate){ providers=data.results.FR.flatrate.map(p=>p.provider_name); }
          if(!providers.length && data.results?.US?.flatrate){ providers=data.results.US.flatrate.map(p=>p.provider_name); }
          const span=document.getElementById(spanId);
          span.textContent = providers.length? 'Plateforme : '+providers.join(', ') : '';
          span.setAttribute('data-providers', providers.join(', '));
        });
    }

    // ===== Étapes progressives =====
    const els={
      stepBugChooser: document.getElementById('step-bug-chooser'),
      stepAjoutChooser: document.getElementById('step-ajout-chooser'),
      formBugChaine: document.getElementById('form-bug-chaine'),
      formBugFilm: document.getElementById('form-bug-film'),
      formBugSerie: document.getElementById('form-bug-serie'),
      formAjoutFilm: document.getElementById('form-ajout-film'),
      formAjoutSerie: document.getElementById('form-ajout-serie'),
    };

    function hideAll(...nodes){
      nodes.forEach(n=>{
        n.classList.add('hidden');
        n.classList.remove('animate-in'); // reset si caché pendant l’anim
        n.style.removeProperty('--delay');
      });
    }

    // ⚡ Nouvelle fonction show() avec animation
    function show(el, delay=0){
      el.classList.remove('hidden');
      // Reflow pour pouvoir rejouer l’animation
      void el.offsetWidth;
      el.style.setProperty('--delay', `${delay}ms`);
      el.classList.add('animate-in');
      el.addEventListener('animationend', ()=>{
        el.classList.remove('animate-in');
        el.style.removeProperty('--delay');
      }, { once:true });
    }

    function scrollToNode(node){
      setTimeout(()=>{
        node.scrollIntoView({behavior: 'smooth', block: 'start'});
      }, 100);
    }

    function clearFields(scope){
      scope.querySelectorAll('input[type="text"], input[type="hidden"], textarea').forEach(i=>i.value='');
      scope.querySelectorAll('.suggestions').forEach(s=>s.innerHTML='');
      scope.querySelectorAll('.platform-value').forEach(p=>{p.textContent=''; p.removeAttribute('data-providers');});
      const selects=scope.querySelectorAll('select'); selects.forEach(s=>{ if(s.id!=='main-category') s.selectedIndex=0; });
    }

    function onCategoryChange(){
      // reset tout
      hideAll(els.stepBugChooser, els.stepAjoutChooser, els.formBugChaine, els.formBugFilm, els.formBugSerie, els.formAjoutFilm, els.formAjoutSerie);
      clearFields(els.formBugChaine); clearFields(els.formBugFilm); clearFields(els.formBugSerie);
      clearFields(els.formAjoutFilm); clearFields(els.formAjoutSerie);
      document.getElementById('bug-type').selectedIndex=0;
      document.getElementById('ajout-type').selectedIndex=0;

      const v=document.getElementById('main-category').value;
      if(v==='bug'){ show(els.stepBugChooser); scrollToNode(els.stepBugChooser); }
      if(v==='ajout'){ show(els.stepAjoutChooser); scrollToNode(els.stepAjoutChooser); }
    }

    function onBugTypeChange(){
      hideAll(els.formBugChaine, els.formBugFilm, els.formBugSerie);
      clearFields(els.formBugChaine); clearFields(els.formBugFilm); clearFields(els.formBugSerie);
      const t=document.getElementById('bug-type').value;
      if(t==='Bug chaine TV') { show(els.formBugChaine); scrollToNode(els.formBugChaine); }
      if(t==='Bug Film') { show(els.formBugFilm); scrollToNode(els.formBugFilm); }
      if(t==='Bug Série') { show(els.formBugSerie); scrollToNode(els.formBugSerie); }
    }

    function onAjoutTypeChange(){
      hideAll(els.formAjoutFilm, els.formAjoutSerie);
      clearFields(els.formAjoutFilm); clearFields(els.formAjoutSerie);
      const t=document.getElementById('ajout-type').value;
      if(t==='film') { show(els.formAjoutFilm); scrollToNode(els.formAjoutFilm); }
      if(t==='serie') { show(els.formAjoutSerie); scrollToNode(els.formAjoutSerie); }
    }

    // ===== Envoi =====
    function submitForm(){
      // Données session (visuel pour le webhook)
      const pseudo = document.getElementById('pseudo').value;
      const email = document.getElementById('email').value;

      const category = document.getElementById('main-category').value;

      let title="", color=0x5b8cff, imageUrl="", tmdbLink="", tmdbId="";
      let dbCategory="", dbTitle="", dbDetails={};

      // Ajout du mail dans la description envoyée au webhook
      let desc = `**Pseudo :** ${pseudo}\n**Email :** ${email}\n\n`;

      if(category==='bug'){
        title='🚩 Nouveau signalement de bug Streambox'; color=0xF44336;
        const bugType=document.getElementById('bug-type').value;
        desc += `**Type :** ${bugType}\n`;
        
        if(bugType==='Bug chaine TV'){
          dbCategory = 'chaine';
          dbTitle = document.getElementById('chaine').value;
          dbDetails = { probleme: document.getElementById('bug-chaine-type').value };
          desc += `Chaîne : ${dbTitle}\nProblème : ${dbDetails.probleme}`;

        }else if(bugType==='Bug Film'){
          dbCategory = 'film';
          tmdbId=document.getElementById('film-tmdbid').value;
          imageUrl=document.getElementById('film-poster').value;
          dbTitle = document.getElementById('film-nom').value;
          dbDetails = { annee: document.getElementById('film-annee').value, bug: document.getElementById('film-bug').value };
          tmdbLink=tmdbId?`https://www.themoviedb.org/movie/${tmdbId}`:'';
          desc += `Film : ${dbTitle}\nAnnée : ${dbDetails.annee}\nProblème : ${dbDetails.bug}`;

        }else if(bugType==='Bug Série'){
          dbCategory = 'serie';
          tmdbId=document.getElementById('serie-tmdbid').value;
          imageUrl=document.getElementById('serie-poster').value;
          dbTitle = document.getElementById('serie-nom').value;
          const platform = document.getElementById('serie-platform').getAttribute('data-providers')||'';
          dbDetails = { 
            annee: document.getElementById('serie-annee').value,
            saison: document.getElementById('serie-saison').value,
            episode: document.getElementById('serie-episode').value,
            bug: document.getElementById('serie-bug').value,
            platform: platform
          };
          tmdbLink=tmdbId?`https://www.themoviedb.org/tv/${tmdbId}`:'';
          desc += `Série : ${dbTitle}\nAnnée : ${dbDetails.annee}${platform?`\nPlateforme : ${platform}`:''}\nSaison : ${dbDetails.saison}\nÉpisode : ${dbDetails.episode}\nProblème : ${dbDetails.bug}`;
        } else { alert('Choisis un type de bug.'); return; }
      }
      else if(category==='ajout'){
        const t=document.getElementById('ajout-type').value;
        if(t==='film'){
          dbCategory = 'film';
          title='📥 Demande d’ajout • Film'; color=0x2196F3;
          tmdbId=document.getElementById('ajout-film-tmdbid').value;
          imageUrl=document.getElementById('ajout-film-poster').value;
          dbTitle = document.getElementById('ajout-film-titre').value;
          dbDetails = { annee: document.getElementById('ajout-film-annee').value };
          tmdbLink=tmdbId?`https://www.themoviedb.org/movie/${tmdbId}`:'';
          desc += `Titre : ${dbTitle}\nAnnée : ${dbDetails.annee}`;

        }else if(t==='serie'){
          dbCategory = 'serie';
          title='📥 Demande d’ajout • Série'; color=0x2196F3;
          tmdbId=document.getElementById('ajout-serie-tmdbid').value;
          imageUrl=document.getElementById('ajout-serie-poster').value;
          dbTitle = document.getElementById('ajout-serie-titre').value;
          const platform = document.getElementById('ajout-serie-platform').getAttribute('data-providers')||'';
          dbDetails = { 
            saison: document.getElementById('ajout-serie-saison').value,
            annee: document.getElementById('ajout-serie-annee').value,
            platform: platform
          };
          tmdbLink=tmdbId?`https://www.themoviedb.org/tv/${tmdbId}`:'';
          desc += `Titre : ${dbTitle}${platform?`\nPlateforme : ${platform}`:''}\nSaison : ${dbDetails.saison}\nAnnée : ${dbDetails.annee}`;
        } else { alert('Choisis Film ou Série.'); return; }
      } else { alert('Choisis une catégorie.'); return; }

      if(tmdbLink) desc += `\n[Voir sur TMDB](${tmdbLink})`;

      // Construction de l'objet pour l'API PHP
      const payload = {
        type: category,
        category: dbCategory,
        title: dbTitle,
        details: dbDetails,
        tmdbId: tmdbId,
        poster: imageUrl,
        embeds: [{
            title:title, description:desc, color:color,
            thumbnail: imageUrl ? {url:imageUrl} : undefined,
            footer:{text:'Streambox'}, timestamp:new Date().toISOString()
        }]
      };

      // Envoi vers notre script PHP local au lieu de Discord directement
      fetch('api_submit.php', {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify(payload)
      })
      .then(r => r.json())
      .then(data => {
        if(data.success){
            alert('Demande enregistrée et envoyée avec succès !');
            window.location.href = 'dashboard.php'; // Redirection vers le dashboard
        } else {
            alert('Erreur lors de l\'enregistrement : ' + (data.message || 'Erreur inconnue'));
        }
      })
      .catch(err => {
        alert('Erreur réseau.');
        console.error(err);
      });
    }
  </script>
</body>
</html>
