
const { useState, useEffect } = React;
const niveauxParMatiere = { maths: 0, chimie: 13, physique:5, geographie:1,biologie:15,geographie:8,zoologie:6,svt:12,Economie:3, Chimie :3,Anglais:10,BaccSvt:17,Vitamine:4,geologie:9,sciences_sociales:21, sport:7};
const classes = ["9eme", "NSIV","NS3","Sciences","NSI","Linguistique","Sport"];
const matieres = {"9eme": ["biologie","physique","sciences_sociales"], "NSIV": ["chimie","svt","Economie","BaccSvt","Vitamine"], "NS3":["chimie"],"Sciences":["geographie","zoologie","botanique","geologie"],"NSI":["Chimie"],"Linguistique":["Anglais"],"Sport":["sport"]};
const getUserProgress = () => {return JSON.parse(localStorage.getItem("userProgress") || "{}");};

 const Loader = () => (
    <div style={{
      display: "flex",
      flexDirection: "column",
      alignItems: "center",
      justifyContent: "center",
      minHeight: "200px"
    }}>
      <div className="spinner"></div>
      <p style={{ marginTop: "10px", fontSize: "1em", color: "#555" }}>Chargement du quiz...</p>
      <style>
        {`
          .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #004080;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
          }
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
        `}
      </style>
    </div>
  );
function sauvegarderProgression(userId, classe, matiere, niveau) {
  fetch("api/saveProgress.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ userId, classe, matiere, niveau })
  })
  .then(res => res.json())
  .then(data => {
    if (data.success) {
      console.log("✅ Progression enregistrée");
    } else {
      console.error("⚠️ Erreur de sauvegarde :", data.message);
    }
  })
  .catch(console.error);
}
function CookieBanner() {
  const [showBanner, setShowBanner] = React.useState(false);
  React.useEffect(() => {
    const consent = window.cookieUtils.get("cookieConsent");
    if (!consent) setShowBanner(true);
  }, []);


  function acceptCookies() {
    window.cookieUtils.set("cookieConsent", "accepted", 365);
    setShowBanner(false);
  }
 
  function refuseCookies() {
    window.cookieUtils.set("cookieConsent", "refused", 365);
    setShowBanner(false);
  }

  if (!showBanner) return null;
  return React.createElement(
    "div",
    {
      style: {
        position: "fixed",
        bottom: "0",
        left: "0",
        width: "100%",
        backgroundColor: "#1e1e1e",
        color: "white",
        padding: "1rem",
        zIndex: 1000,
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        gap: "0.5rem",
        boxShadow: "0 -2px 10px rgba(0,0,0,0.3)",
        fontSize: "1rem"
      }
    },
    React.createElement("div", {
      style: {
        maxWidth: "90%",
        textAlign: "center"
      }
    }, "Nous utilisons des cookies pour améliorer votre expérience. et pour diffuser des publicités. Acceptez-vous ?"),
    React.createElement("div", {
      style: {
        display: "flex",
        gap: "1rem",
        flexWrap: "wrap",
        justifyContent: "center"
      }
    },
      React.createElement("button", {
        onClick: acceptCookies,
        style: {
          backgroundColor: "#4caf50",
          color: "white",
          border: "none",
          borderRadius: "5px",
          padding: "0.5rem 1.2rem",
          cursor: "pointer"
        }
      }, "Accepter"),
      React.createElement("button", {
        onClick: refuseCookies,
        style: {
          backgroundColor: "#f44336",
          color: "white",
          border: "none",
          borderRadius: "5px",
          padding: "0.5rem 1.2rem",
          cursor: "pointer"
        }
      }, "Refuser")
    )
  );
}
const MonetagRewardAd = ({ onRewarded }) => {
  React.useEffect(() => {const script = document.createElement('script');
    script.src = 'https://groleegni.net/401/8727837';
    script.async = true;

    try {
      (document.body || document.documentElement).appendChild(script);
    } catch (e) {
      console.error("Erreur lors de l'ajout du script Monetag :", e);
    }

   
    // Simulation durée pub puis récompense (ajuste si API dispo)
    const timer = setTimeout(() => {
     
      onRewarded();
    }, 5000);

    return () => {
      clearTimeout(timer);
      if (script.parentNode) {
        script.parentNode.removeChild(script);
      }
    };
  }, [onRewarded]);

  return (
    <div style={{ padding: '1rem', background: '#000c', color: '#fff', textAlign: 'center' }}>
        <Loader/>
      <span> en cours...</span>
    </div>
  );
};
const ShareButton = ({ url = window.location.href, text = "Essaie ce super quiz !" }) => {
  const [message, setMessage] = React.useState("");
  const share = async () => {
    if (navigator.share) {
      try {
        await navigator.share({ title: "Quiz éducatif", text, url });
        setMessage("✅ Partagé avec succès !");
      } catch (err) {
        setMessage("❌ Échec du partage.");
      }
    } else {
      try {
        await navigator.clipboard.writeText(url);
        setMessage("✅ Lien copié dans le presse-papiers !");
      } catch (e) {
        setMessage("❌ Impossible de copier le lien.");
      }
    }

    setTimeout(() => setMessage(""), 3000);
  };
  return (
    <div style={{ margin: "1rem", textAlign: "center" }}>
      <button onClick={share} style={{ padding: "10px 20px", borderRadius: "8px", background: "#2196f3", color: "#fff", border: "none", cursor: "pointer" }}>
        📤 Partager le quiz
      </button>
      {message && <p style={{ marginTop: "0.5rem", color: "#fff" }}>{message}</p>}
    </div>
  );
};
const AdsterraBanner = () => {
  React.useEffect(() => {
      const script = document.createElement('script');
      script.src = '//pl25317511.profitableratecpm.com/3a/47/d3/3a47d34d1ef582ce3780ed350b61f84d.js';
      script.async = true;
      try {
      (document.body || document.documentElement).appendChild(script);
    } catch (e) {
      console.error("Erreur lors de l'ajout du script Monetag :", e);
    }
   
  }, []);
  
  return (
    <div style={{position:"fixed", bottom:0, width:"100%", background:"#eee", textAlign:"center", padding:"5px"}}>
      {/* Ici iframe ou script Adsterra */}
      <small>Bannière Adsterra</small>
      <div id="container-8ebe117cbe76e981980d358cf943eec6"></div>
    </div>
  );
};
const OnClickARewardedVideo = ({ onRewarded, onCancel }) => {
  const [canCancel, setCanCancel] = React.useState(false);

  React.useEffect(() => {
    // Injecter le script OnClickA
    const script = document.createElement("script");
    script.src = "https://js.onclckmn.com/static/onclicka.js";
    script.async = true;
    script.setAttribute("data-admpid", "276511");
    document.body.appendChild(script);
       
    
    // Autoriser annulation après 15 sec
    const cancelTimer = setTimeout(() => {
      setCanCancel(true);
    }, 15000);

    const finishTimer = setTimeout(() => {
      
      onRewarded();
    }, 15000);

    // Nettoyer au démontage
    return () => {
      clearTimeout(cancelTimer);
      clearTimeout(finishTimer);
      document.body.removeChild(script);
    };
  }, []);

  return (
    <div
      style={{
        position: "fixed",
        top: 0, left: 0, right: 0, bottom: 0,
        background: "#000c",
        color: "#fff",
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
        zIndex: 10000,
      }}
    > 
        <Loader/>
      <span> en cours...</span>
   
      <p>🎬 en cours...</p>
      {canCancel && <button onClick={onCancel}>Annuler (après 15 sec)</button>}
    </div>
  );
};

function About() {
  const [principes, setPrincipes] = useState(null);
useEffect(() => {
    fetch("/principes_jeu.json")
      .then(res => res.json())
      .then(data => setPrincipes(data));
  }, []);
  if (!principes) return <>
      <Loader/>
  </>;
    return (
    <div className="about-section" style={{ padding: 20, maxWidth: 800, margin: "0 auto" }}>
      <h2>{principes.title}</h2>
      <p><strong>Dernière mise à jour :</strong> {principes.lastUpdate}</p>
      {principes.sections.map((section, i) => (
        <div key={i} style={{ marginBottom: 20 }}>
          <h3>{section.heading}</h3>
          <ul>
            {section.content.map((item, j) => (
              <li key={j}>{item}</li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  );
}
const Updat_bagde = async ()=>{
        const ph=JSON.parse(localStorage.getItem("quizUser")); 
       const c=JSON.parse(localStorage.getItem("badges"));
    if (c && ph) {
    const xhr = new XMLHttpRequest(); xhr.open("POST", "api/updateUserProgress.php", true);
     xhr.setRequestHeader("Content-Type", "application/json");xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log("Réponse du serveur :", xhr.responseText);
    }
  };
  xhr.send(JSON.stringify({or:c.or, phone:ph.phone, agent:c.argent,bronze:c.bronze, diamant:c.diamant}));
}
}
const User_if = async ({pseudo, phone, password})=>{
     const xhr = new XMLHttpRequest();
     xhr.open("POST", "api/registerUser.php", true);
     xhr.setRequestHeader("Content-Type", "application/json");
      xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log("Réponse du serveur :", xhr.responseText);
    }
  };
  xhr.send(JSON.stringify({username:pseudo, phone:phone
,pass:password
}));
}
 const Udat_user = async ({phone,password})=>{
   const  reponse = await fetch("api/user_htjggfs.php",{
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({phone: phone, pass:password})
    });
   if(reponse.ok==true &&reponse.status==200){
       const inf = await reponse.json();
       return inf;
   }else{
       return false;
   }
 }
const Quiz = ({ questions, onFinish }) => {
  const [shuffledQuestions, setShuffledQuestions] = React.useState([]);
  const [index, setIndex] = React.useState(0);
  const [score, setScore] = React.useState(0);
  const [selected, setSelected] = React.useState(null);
  const [showFeedback, setShowFeedback] = React.useState(false);
  const [timeLeft, setTimeLeft] = React.useState(30);
  const [animate, setAnimate] = React.useState(true);
  const [fillInputs, setFillInputs] = React.useState([]);
  const [assocAnswers, setAssocAnswers] = React.useState({});

  
  const current = questions[index];
  const correctSound = React.useRef(null);
  const wrongSound = React.useRef(null);
  const beepSound = new Audio("image/sispens.mp3");

  React.useEffect(() => {
    correctSound.current = new Audio("image/bon.mp3");
    wrongSound.current = new Audio("image/erreur.wav");
  }, []);

  const shuffleArray = (arr) =>
    arr.map(a => ({ sort: Math.random(), value: a }))
       .sort((a, b) => a.sort - b.sort)
       .map(a => a.value);

  React.useEffect(() => {
    const shuffled = shuffleArray(questions).map(q => {
      const type = q.type || "choice";
      if (type === "choice" || !q.type) {
        const rep = q.reponse || q.choices || q.options;
        const shuffledRep = shuffleArray(rep);
        return {
          ...q,
          type: "choice",
          reponse: shuffledRep,
          answer: typeof q.answer === "string" ? shuffledRep.indexOf(q.answer) : q.answer
        };
      }
      return q;
    });
    setShuffledQuestions(shuffled);
  }, [questions]);

  const question = shuffledQuestions[index];

  React.useEffect(() => {
    if (!question || selected !== null || question.type === "association") return;
    const timer = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev <= 8 && prev > 1) beepSound.play().catch(() => {});
        if (prev === 1) {
          clearInterval(timer);
          handleAnswer(null);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    return () => clearInterval(timer);
  }, [index, selected, question]);

  const handleAnswer = (i) => {
    if (selected !== null) return;
    const isCorrect = i !== null && i === question.answer;
    setSelected(i);
    setShowFeedback(true);

    if (isCorrect) {
      correctSound.current?.play();
      setScore(s => s + 1);
    } else {
      wrongSound.current?.play();
    }

    setTimeout(() => nextQuestion(isCorrect), 5000);
  };

  const handleFillSubmit = () => {
    const isCorrect = JSON.stringify(fillInputs.map(t => t.trim().toLowerCase())) ===
                      JSON.stringify(question.answers.map(t => t.trim().toLowerCase()));
    setSelected(true);
    setShowFeedback(true);
    if (isCorrect) {
      correctSound.current?.play();
      setScore(s => s + 1);
    } else {
      wrongSound.current?.play();
    }
    setTimeout(() => nextQuestion(isCorrect), 8000);
  };
const RenderFeedback = () => {
  if (!showFeedback) return null;

  const type = question.type || "choice";
  const feedback = question.feedback || "";

  switch (type) {
    case "choice":
      return <p className="feedback">💡 {feedback || "Cette réponse était informative."}</p>;

    case "fill":
      return (
        <div className="feedback fill-feedback">
          <p>📝 Réponse attendue : {question.answers.join(" / ")}</p>
          {feedback && typeof feedback === "string" && <p>💬 {feedback}</p>}
        </div>
      );

    case "association":
      return (
        <div className="feedback assoc-feedback">
          <h4>✔️ Bonnes correspondances :</h4>
          <ul>
            {Object.entries(question.answers).map(([label, correct]) => (
              <li key={label}>
                <strong>{label}.</strong> {correct}
                {question.feedback?.[label] && (
                  <p className="assoc-comment">💬 {question.feedback[label]}</p>
                )}
              </li>
            ))}
          </ul>
        </div>
      );

    default:
      return <p className="feedback">💬 {typeof feedback === "string" ? feedback : "Aucune explication fournie."}</p>;
  }
};


  const handleAssociationSubmit = () => {
    const correct = question.pairs.every(p => assocAnswers[p.label] === question.answers[p.label]);
    setSelected(true);
    setShowFeedback(true);
    if (correct) {
      correctSound.current?.play();
      setScore(s => s + 1);
    } else {
      wrongSound.current?.play();
    }
    setTimeout(() => nextQuestion(correct), 15000);
  };

  const nextQuestion = (wasCorrect) => {
    const finalScore = score + (wasCorrect ? 1 : 0);
    if (index + 1 < shuffledQuestions.length) {
      setAnimate(false);
      setTimeout(() => {
        setIndex(i => i + 1);
        setSelected(null);
        setShowFeedback(false);
        setTimeLeft(30);
        setFillInputs([]);
        setAssocAnswers({});
        setAnimate(true);
      }, 50);
    } else {
      onFinish(finalScore, shuffledQuestions.length);
    }
  };

  if (!question) return <div>Chargement…</div>;

  return (
    <div className="quiz">
      <div className="chrono-circle">
        <svg width="60" height="60">
          <circle cx="30" cy="30" r="26" stroke="#ccc" strokeWidth="4" fill="none" />
          <circle
            cx="30" cy="30"
            r="26"
            stroke={timeLeft <= 7 ? "#ff3333" : "#1d75c9"}
            strokeWidth="4"
            fill="none"
            strokeDasharray={2 * Math.PI * 26}
            strokeDashoffset={(1 - timeLeft / 30) * 2 * Math.PI * 26}
            transform="rotate(-90 30 30)"
            style={{ transition: 'stroke-dashoffset 1s linear, stroke 0.3s ease' }}
          />
          <text x="30" y="35" textAnchor="middle" fontSize="14" fill="#333">{timeLeft}s</text>
        </svg>
      </div>

      <p className="score-live">🧠 Score actuel : {score} / {questions.length}</p>
      <p className="progress">Question {index + 1} / {shuffledQuestions.length}</p>

      <div className={`quiz-question ${
  animate
    ? question.type === "fill"
      ? "slide-in-fill"
      : question.type === "association"
        ? "flip-in-association"
        : "fade-in-choice"
    : ""
}`}>
        <h3 dangerouslySetInnerHTML={{ __html: question.question }} />

        {question.type === "choice" && (
          <div className="options">
            {question.reponse.map((opt, i) => {
              let btnClass = "option-btn";
              if (selected !== null) {
                if (i === question.answer) btnClass += " correct";
                else if (i === selected) btnClass += " wrong";
              }
              return (
                <button
                  key={i}
                  disabled={selected !== null}
                  className={btnClass}
                  onClick={() => handleAnswer(i)}
                  dangerouslySetInnerHTML={{ __html: opt }}
                />
              );
            })}
          </div>
        )}

        {question.type === "fill" && (
          <div>
            <p dangerouslySetInnerHTML={{ __html: question.text }} />
            {question.answers.map((_, i) => (
              <input
                key={i}
                type="text"
                value={fillInputs[i] || ""}
                onChange={(e) => {
                  const newInputs = [...fillInputs];
                  newInputs[i] = e.target.value;
                  setFillInputs(newInputs);
                }}
                placeholder={`Réponse ${i + 1}`}
              />
            ))}
            <button onClick={handleFillSubmit} disabled={selected !== null}>Valider</button>
          </div>
        )}

        {question.type === "association" && (
          <div>
            {question.pairs.map((pair) => (
              <div key={pair.label} className="association-row">
                <strong>{pair.label}. {pair.text}</strong>
                <select
                  disabled={selected !== null}
                  value={assocAnswers[pair.label] || ""}
                  onChange={(e) => setAssocAnswers({ ...assocAnswers, [pair.label]: e.target.value })}
                >
                  <option value="">-- Choisir --</option>
                  {question.options.map((opt, i) => (
                    <option key={i} value={opt}>{opt}</option>
                  ))}
                </select>
              </div>
            ))}
            <button onClick={handleAssociationSubmit} disabled={selected !== null}>Valider les associations</button>
          </div>
        )}

      {RenderFeedback()
      }
      

      </div>
    
   </div>
  );
}
const App = () => {
  const [currentTab, setCurrentTab] = useState("quiz");
  const [classe, setClasse] = useState(null);
  const [matiere, setMatiere] = useState(null);
 const [showExtraNiveaux, setShowExtraNiveaux] = useState(false);
  const [niveauActif, setNiveauActif] = useState(null);
  const [questions, setQuestions] = useState(null);
  const [loading, setLoading] = useState(false);
  const [showDashboard, setshowDashboard] = useState(false);
  const [onComplete, setonComplete] = useState(false);
  const [userData, setUserData] = useState(() => JSON.parse(localStorage.getItem("userData")) || {});
  const [modal, setModal] = useState(null);
  const [isReplay, setIsReplay] = useState(false);
  const [userProfile, setUserProfile] = React.useState(null);
  const [showOnClickA, setShowOnClickA] = useState(false);
  const [showMonetag, setShowMonetag] = useState(false);
  const [pendingNiveau, setPendingNiveau] = useState(null); // niveau à lancer après pub
  const [replayAfterAd, setReplayAfterAd] = useState(false);
  const [showMiniQuiz, setShowMiniQuiz] = useState(true);

React.useEffect(() => {
  const saved = localStorage.getItem("userProfile");
  if (saved) {
    setUserProfile(JSON.parse(saved));
  }}, []);
  const handleSelectClasse = (c) => {
    setClasse(c);
    setMatiere(null);
    setNiveauActif(null);
  };
  const handleSelectMatiere = (m) => {
    setMatiere(m);
    setNiveauActif(null);
  };

const handleStartNiveau = (n) => {
  const key = `${classe}_${matiere}_niveau${n}`;
  const niveauData = userData[key] || { completed: false, attempts: 0 };
  if (niveauData.completed) {
    // niveau déjà fait => proposer rejouer avec pub ou points
    return setModal({
      title: "Rejouer ce niveau ?",
      content: "Ce niveau est terminé. Pour rejouer, choisissez une option :",
      actions: [
        { label: "🎥 Regarder pub OnClickA", onClick: () => {
            setPendingNiveau(key);
            setReplayAfterAd(true);
            setShowOnClickA(true);
            setModal(null);
          }
        },
        { label: "🎥 Regarder pub Monetag", onClick: () => {
            setPendingNiveau(key);
            setReplayAfterAd(true);
            setShowMonetag(true);
            setModal(null);
          }
        },
        { label: "💰 Dépenser 20 points", onClick: () => spendPoints(key) },
        { label: "Annuler", onClick: () => setModal(null) }
      ]
    });
  }
  // Niveau jamais fait => lancement normal (optionnel pub Monetag avant)
  setPendingNiveau(key);
  setReplayAfterAd(false);
  setShowMonetag(true); // ou setShowOnClickA(true);
};

  const allowReplay = (key) => {
    setModal(null);
    startNiveau(key, true);
  };
  const spendPoints = (key) => {
    const points = parseInt(localStorage.getItem("totalPoints") || "0");
    if (points >= 20) {
      localStorage.setItem("totalPoints", points - 30);
      allowReplay(key);
    } else {
      setModal({
        title: "Pas assez de points",
        content: "Vous avez besoin de 30 points pour rejouer ce niveau.",
        actions: [{ label: "Fermer", onClick: () => setModal(null) }]
      });}};
 let lastNiveau=null;
  const startNiveau = (key, replay) => {
     if(!localStorage.getItem("lastNiveauKey")){
 localStorage.setItem("lastNiveauKey", JSON.stringify({})) }
     lastNiveau=JSON.parse(localStorage.getItem("lastNiveauKey"));
       const info=(key.split("_"));
            if(info[1]=="chimie" && info[0]=="NSIV"){
           lastNiveau.chimieNSIV=key
       }else if(info[1]=="biologie" && info[0]=="9eme"){
           lastNiveau.bio9eme=key;
       }
      localStorage.setItem("lastNiveauKey",JSON.stringify(lastNiveau));
    setIsReplay(replay);
     setLoading(true);
    fetch(`json/${key}.json`)
      .then(res => res.json())
      .then(data => {
        setQuestions(data.questions);
        setNiveauActif(key);
      })
      .catch(() => {
        setModal({
          title: "Erreur",
          content: "Impossible de charger les questions.",
          actions: [{ label: "Fermer", onClick: () => setModal(null) }]
        });
      })
      .finally(() => setLoading(false));
  };
  if(! localStorage.getItem("badges")){
       localStorage.setItem("badges",JSON.stringify({argent:0, or:0,bronze:0, diamant:0}));}

const handleFinish = (score, total) => {
  const key = niveauActif; // exemple: "NSIV_Chimie_niveau3"
  const prevData = userData[key] || { attempts: 0, completed: false };
  const newData = {
    ...userData,
    [key]: {
      completed: true,
      attempts: prevData.attempts + 1
    }
  };
  setUserData(newData);
  localStorage.setItem("userData", JSON.stringify(newData));

  // 🔍 Extraire classe, matière, niveau depuis la clé
  const [classe, matiere, niveauStr] = key.split("_");
  const niveau = parseInt(niveauStr.replace("niveau", ""));

  // 🔒 ID utilisateur (localStorage ou global context)
    const User =localStorage.getItem("quizUser") || null ;
   if(User){
        const user = JSON.parse(localStorage.getItem("quizUser"));
        
  
  if (user?.id) {
    fetch("api/saveProgressUser.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        userId: user.id,
        classe,
        matiere,
        niveau
      })
    })
    .then(res => res.json())
    .then(data => {
      if (!data.success) console.error("Erreur MySQL:", data.message);
    })
    .catch(console.error);
  }
}
  // 🏅 Attribution de badge
  if (!isReplay && prevData.attempts === 0) {
    const cbadges = JSON.parse(localStorage.getItem("badges"));
    let earnBagdes = null;
    let badge = null;
    let gbadge = 0;
    const pourcentage = (score / total) * 100;

    if (pourcentage === 100) {
      badge = "💎 Diamant";
      gbadge = parseInt(cbadges.diamant || 0);
      cbadges.diamant = gbadge + 1;
      earnBagdes = 1;
    } else if (pourcentage >= 80 && pourcentage > 70) {
      badge = "🥇 Or";
      gbadge = parseInt(cbadges.or || 0);
      cbadges.or = gbadge + 1;
      earnBagdes = 1;
    } else if (pourcentage >= 60 && pourcentage > 50) {
      badge = "🥈 Argent";
      gbadge = parseInt(cbadges.argent || 0);
      cbadges.argent = gbadge + 1;
      earnBagdes = 1;
    } else if (pourcentage >= 50 && pourcentage < 60) {
      badge = "🥉 Bronze";
      gbadge = parseInt(cbadges.bronze || 0);
      cbadges.bronze = gbadge + 1;
      earnBagdes = 1;
    }

    if (badge) {
      localStorage.setItem("badges", JSON.stringify(cbadges));
      Updat_bagde();

      setModal({
        title: "🎉 Félicitations !",
        content: `Vous avez obtenu ${earnBagdes} badges ${badge}`,
        actions: [{ label: "Fermer", onClick: () => setModal(null) }]
      });
    }
  }

  // ➕ Mise à jour des points
  const points = parseInt(localStorage.getItem("totalPoints") || "0") + score;
  localStorage.setItem("totalPoints", points);

  // Nettoyage final
  setQuestions(null);
  setNiveauActif();
  setIsReplay(false);
};
const niveaux = matiere ? [...Array(niveauxParMatiere[matiere]).keys()].map(i => {
    const key = `${classe}_${matiere}_niveau${i + 1}`;
    const done = userData[key]?.completed;
    const attempts = userData[key]?.attempts || 0;
    const previousKey = `${classe}_${matiere}_niveau${i}`;
    const previousDone = i === 0 || userData[previousKey]?.completed;
    let label = `Niveau ${i + 1}`;
    let locked = !previousDone;
 return (
      <button
        key={i}
        className={`niveau-btn ${locked ? "locked" : done ? "completed" : ""}`}
        onClick={() => !locked && handleStartNiveau(i + 1)}
        disabled={locked}
      >
        {locked ? "🔒" : done ? "✅ " : ""}{label}
      </button>
    );
  }) : null
const Header = () => (
  <header style={{
    background: "#004080",
    color: "#fff",
    padding: "15px 30px",
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between"
  }}>
    <h1 style={{ fontSize: "1.5em", margin: 0 }}>
      HT School Haiti
    </h1>
    <nav>
      <a href="/" style={{ color: "#fff", marginRight: "15px", textDecoration: "none" }}>Accueil</a>
      <a href="/#quiz" style={{ color: "#fff", marginRight: "15px", textDecoration: "none" }}>Quiz</a>
      <a href="/contact.html" style={{ color: "#fff", textDecoration: "none" }}>Contact</a>
    </nav>
  </header>
);
  const QuestionsNiveau = ({ matiere, niveau, onNextLevel }) => {
    const [questions, setQuestions] = useState([]);
    const [currentIndex, setCurrentIndex] = useState(0);
    const [selectedAnswer, setSelectedAnswer] = useState(null);
    const [isCorrect, setIsCorrect] = useState(null);
    const [flashClass, setFlashClass] = useState("");

    const goodSound = React.useRef(null);
  const badSound = React.useRef(null);

    const shuffleArray = (arr) =>
      arr
        .map((a) => ({ sort: Math.random(), value: a }))
        .sort((a, b) => a.sort - b.sort)
        .map((a) => a.value);

    useEffect(() => {
      const fileName = `/capitale/${matiere}_${niveau}.json`;
      fetch(fileName)
        .then((res) => res.json())
        .then((data) => {
          const mixed = shuffleArray(data).map(q => ({
            ...q,
            reponse: shuffleArray(q.reponse)
          }));
          setQuestions(mixed);
        })
        .catch((err) => console.error(err));
    }, [matiere, niveau]);

    if (questions.length === 0) {
      return <Loader />;
    }

    const currentQuestion = questions[currentIndex];

    const handleChoice = (choice) => {
      const correct = choice === currentQuestion.answer;
      setSelectedAnswer(choice);
      setIsCorrect(correct);

      if (correct) {
        goodSound.current.play();
        setFlashClass("flash-green");
      } else {
        badSound.current.play();
        setFlashClass("flash-red");
      }

      setTimeout(() => setFlashClass(""), 500);

      setTimeout(() => {
        if (currentIndex < questions.length - 1) {
          setSelectedAnswer(null);
          setIsCorrect(null);
          setCurrentIndex((prev) => prev + 1);
        }
      }, 2000);
    };

    const isLastQuestion = currentIndex === questions.length - 1 && selectedAnswer;

    return (
      <div
        className={flashClass}
        style={{
          margin: "40px auto",
          maxWidth: "600px",
          padding: "20px",
          background: "#fff",
          borderRadius: "15px",
          transition: "background 0.5s",
          fontSize:"18px",
          
        }}
      >
        <audio ref={goodSound} src="/image/bon.mp3" preload="auto" />
        <audio ref={badSound} src="/image/erreur.wav" preload="auto" />

        <style>{`
          .flash-green { background: #c8f7c5 !important; }
          .flash-red { background: #f8d7da !important; }
          .loader {
            border: 8px solid #f3f3f3;
            border-top: 8px solid #004080;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
          }
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
        `}</style>

        <h3 style={{ textAlign: "center" }}>📘 Questionnaires</h3>
     
        <p><strong>Q{currentIndex + 1} :</strong> {currentQuestion.question}</p>

        <div style={{ display: "flex", flexWrap: "wrap", gap: "10px", marginTop: "10px"}}>
          {currentQuestion.reponse.map((choice, i) => (
            <button
              key={i}
              onClick={() => handleChoice(choice)}
              disabled={!!selectedAnswer}
              style={{
                padding: "10px 20px",
                cursor: selectedAnswer ? "not-allowed" : "pointer",
                background: selectedAnswer === choice
                  ? choice === currentQuestion.answer ? "#4CAF50" : "#F44336"
                  : "#eee",
                color: selectedAnswer === choice ? "#fff" : "#000",
                border: "none",
                borderRadius: "5px",
                flex: "1 1 45%",
              }}
            >
              {choice}
            </button>
          ))}
        </div>

        {selectedAnswer && (
          <p style={{ marginTop: "15px" }}>
            {isCorrect ? "✅ Bonne réponse !" : `❌ Mauvaise réponse. Réponse : ${currentQuestion.answer}`}
          </p>
        )}

        {isLastQuestion && (
          <button
            style={{
              marginTop: "20px",
              padding: "10px 25px",
              background: "#004080",
              color: "#fff",
              border: "none",
              borderRadius: "5px",
            }}
            onClick={onNextLevel}
          >
            ➡️ Niveau suivant
          </button>
        )}
      </div>
    );
  };

 


const img ="../image/fond1.png";

  
const Accueil = ({ onExploreAll, showMiniQuiz }) => (
  <section style={{ padding: "20px", maxWidth: "800px", margin: "auto" }}>
   
    {showMiniQuiz && <QuestionsNiveau matiere={"culture"} niveau="niveau1" onNextLevel={() => {
    setNiveauActif(2);
  }} />}
  </section>
);



const IntroductionQuiz = ({ classe, matiere }) => {
  const textes = {
   // math: `Bienvenue au quiz de Mathématiques pour la classe de ${classe}. Ce quiz vous aidera à consolider vos acquis en arithmétique, géométrie et algèbre.`,
    chimie: `Bienvenue au quiz de Chimie – classe de ${classe}. Vous allez tester vos connaissances sur les molécules, réactions chimiques, et plus encore.`,
    biologie: `Bienvenue au quiz de Biologie pour ${classe}. Préparez-vous à répondre à des questions sur le corps humain, les cellules, et les écosystèmes.`,
    zoologie: `Bienvenue au quiz de Biologie pour ${classe}. Préparez-vous à répondre à des questions sur les batraciens, les mammifères,les reptiles etc .`,
     svt: `Bienvenue dans le quiz de svt – ${classe}. préparer vous à répondre à des questions sur la structure cellulaire,la microbiologie, embryologie, la reproduction et la génétique.`,
    geographie: `Bienvenue au quiz de Géographie pour la classe de ${classe}. Vous allez explorer les continents, les pays, les capitales et la géographie locale.`,
  };
  const texte = textes[matiere] || `Bienvenue dans le quiz de ${matiere} – ${classe}.`;

  return (
    <div className="intro-quiz">
      <h3>📘 Introduction</h3>
      <p style={{ fontSize: "1.1em" }}>{texte}</p>
      <p style={{ marginTop: "8px" }}>
        🧠 Chaque niveau comporte entre <strong>7 et 10 questions</strong>. Vous devez obtenir <strong>80%</strong> pour débloquer le niveau suivant.
      </p>
      <p><strong>Bonne chance ! 🚀</strong></p>
    </div>
  );
};
const MatiereBanner = ({ matiere, onClick }) => (
  <div
    onClick={onClick}
    style={{
      background: "#fff",
      border: "1px solid #ddd",
      borderRadius: "8px",
      boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
      padding: "20px",
      margin: "10px",
      flex: "1 1 200px",
      cursor: "pointer",
      textAlign: "center",
      transition: "transform 0.2s",
    }}
    onMouseEnter={e => e.currentTarget.style.transform = "scale(1.05)"}
    onMouseLeave={e => e.currentTarget.style.transform = "scale(1)"}
  >
    <h3 style={{ margin: 0 }}>{matiere}</h3>
  </div>
);
const ClasseBanner = ({ classe, onClick }) => (
  <div
    onClick={onClick}
    style={{
      flex: "0 0 auto",
      minWidth: "180px",
      margin: "10px",
      background: "#fff",
      border: "1px solid #ddd",
      borderRadius: "8px",
      boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
      textAlign: "center",
      padding: "20px",
      cursor: "pointer",
    }}
  >
    <h3>{classe}</h3>
  </div>
);
return (
  <div>
    <header className="bg-blue-900 text-white flex items-center justify-between px-4 py-3 shadow-md">
  <h1 className="text-lg font-bold">HTSchool</h1>
  <nav className="flex space-x-4">
    <button
      onClick={() => {
        setCurrentTab("quiz");
        setshowDashboard(false);
      }}
      className={`hover:underline ${currentTab === "quiz" && !showDashboard ? "font-bold underline" : ""}`}
    >
      Quiz
    </button>
    <button
      onClick={() => setCurrentTab("duel")}
      className={`hover:underline ${currentTab === "duel" ? "font-bold underline" : ""}`}
    >
      ⚔️ Duel
    </button>
    <button
      onClick={() => {
        setCurrentTab("quiz");
        setshowDashboard(true);
      }}
      className={`hover:underline ${currentTab === "quiz" && showDashboard ? "font-bold underline" : ""}`}
    >
      Profil
    </button>
    <button
      onClick={() => setCurrentTab("about")}
      className={`hover:underline ${currentTab === "about" ? "font-bold underline" : ""}`}
    >
      À propos
    </button>
  </nav>
</header>
<p>
    <img src={img}  style={{width: "100%"}}/>
  Nos quiz sont adaptés à votre niveau d’études. Chaque niveau terminé vous permet de gagner des points convertibles en gourdes.
</p>



    {/* === CONTENU PRINCIPAL === */}
    <main style={{ minHeight: "80vh" }}>
      <div data-banner-id="6078594"></div>
      {currentTab === "duel" && <DuelApp />}
      {currentTab === "about" && <About />}
      {currentTab === "contact" && <Contact />}
        
      {!classe && !matiere && !niveauActif && !showDashboard && currentTab === "quiz" && (
            
           <>  
        <Accueil
          onExploreAll={() => {
            setClasse(null);
            setMatiere(null);
            setNiveauActif(null);
            setShowMiniQuiz(false);
            setshowDashboard(false);
            setCurrentTab("quiz");
          }}
          showMiniQuiz={showMiniQuiz}
        />
      </> 
      )}

      {currentTab === "quiz" &&
        (showDashboard ? (
          <Dashboard
            userData={userData}
            classe={classe}
            matiere={matiere}
            setModal={setModal}
          />
        ) : (
          <>
            {!classe && (
              <><p>Voudriez vous répondre à des questionnaires de chimie, biologie, anglais, sport etc, alors explorer cette section.</p>
                <div
                  style={{
                    display: "flex",
                    overflowX: "auto",
                    padding: "10px",
                  }}
                >
                  {classes.map((c) => (
                    <ClasseBanner
                      key={c}
                      classe={c}
                      onClick={() => handleSelectClasse(c)}
                    />
                  ))}
                </div>
              </>
            )}

            {classe && !matiere && (
              <>
                <h2>📘 Matières</h2>
                <div
                  style={{
                    display: "flex",
                    flexWrap: "wrap",
                    justifyContent: "center",
                    gap: "20px",
                  }}
                >
                  {(matieres[classe] || []).map((m) => (
                    <MatiereBanner
                      key={m}
                      matiere={m}
                      onClick={() => handleSelectMatiere(m)}
                    />
                  ))}
                </div>
                <button onClick={() => setClasse(null)}>🔙 Retour</button>
              </>
            )}

            {classe && matiere && !niveauActif && (
              <>
                <h2>
                  📚 {matiere} – {classe}
                </h2>
                <IntroductionQuiz classe={classe} matiere={matiere} />

                <div className="niveaux-container">
                  {niveaux.slice(0, 3)}
                  <div
                    className={`extra-niveaux ${
                      showExtraNiveaux ? "open" : ""
                    }`}
                    style={{
                      maxHeight: showExtraNiveaux ? "1000px" : "0px",
                    }}
                  >
                    {niveaux.slice(3)}
                  </div>
                  {niveaux.length > 3 && (
                    <button
                      className="toggle-niveaux-btn"
                      onClick={() =>
                        setShowExtraNiveaux(!showExtraNiveaux)
                      }
                    >
                      {showExtraNiveaux
                        ? "🔽 Masquer les niveaux"
                        : "🔼 Afficher tous les niveaux"}
                    </button>
                  )}
                </div>

                <button onClick={() => setMatiere(null)}>🔙 Retour</button>
              </>
            )}

            {/* === PUBS RÉCOMPENSÉES === */}
            {showOnClickA && (
              <OnClickARewardedVideo
                onRewarded={() => {
                  setShowOnClickA(false);
                  if (pendingNiveau)
                    startNiveau(pendingNiveau, replayAfterAd);
                  setPendingNiveau(null);
                }}
                onCancel={() => {
                  setShowOnClickA(false);
                  setPendingNiveau(null);
                  setModal({
                    title: "Pub annulée",
                    content:
                      "Vous devez regarder la vidéo complète pour débloquer ce niveau.",
                    actions: [
                      { label: "OK", onClick: () => setModal(null) },
                    ],
                  });
                }}
              />
            )}

            {showMonetag && (
              <MonetagRewardAd
                onRewarded={() => {
                  setShowMonetag(false);
                  if (pendingNiveau)
                    startNiveau(pendingNiveau, replayAfterAd);
                  setPendingNiveau(null);
                }}
              />
            )}

            {/* === QUIZ === */}
            {questions && niveauActif && (
              <Quiz questions={questions} onFinish={handleFinish} />
            )}
          </>
        ))}

      {modal && (
        <div className="modal">
          <h3>{modal.title}</h3>
          <p>{modal.content}</p>
          <div>
            {modal.actions.map((a, i) => (
              <button key={i} onClick={a.onClick}>
                {a.label}
              </button>
            ))}
          </div>
        </div>
      )}
    </main>
   
    <footer className="bg-gray-100 border-t border-gray-300 text-center text-sm text-gray-700 py-6 px-4">
  <p>&copy; 2025 HT School Haiti — Tous droits réservés.</p>
  <p>
    Développé par <a href="test.php" className="text-black hover:underline">Ing. Hanco Pierre</a>
  </p>
  <div className="mt-2 space-x-4">
    <a href="/privacy-policy.html" className="hover:underline">Politique de confidentialité</a>
    <span>|</span>
    <a href="/terms.html" className="hover:underline">Conditions d’utilisation</a>
    <span>|</span>
    <a href="/contact.html" className="hover:underline">Contact</a>
  </div>
</footer>

  </div>
);


};
function UserForm({ onSubmit }) {
  const [pseudo, setPseudo] = useState("");
  const [phone, setPhone] = useState("");
  const [isLogin, setIsLogin] = useState(true);
  const [isyou, setIsyou] = useState(null);
  const [password, setPassword] = useState("");
  const [showForm, setShowForm] = useState(true);


  useEffect(() => {
    const savedUser =localStorage.getItem("quizUser");
    
    if (savedUser) {
      setShowForm(false);
      onSubmit?.(JSON.parse(savedUser)); // Utilisateur déjà enregistré
    }
  }, []);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!pseudo || !phone || !password) {
      alert("Tous les champs sont requis.");
      return;
    }
    localStorage.setItem("quizUser", JSON.stringify({pseudo, phone}));
    onSubmit?.({pseudo, phone});
    if(!isLogin){
        User_if({pseudo, phone, password });
    }
    setShowForm(false);
  };
  const handleSubmitcon = (e) => {
    e.preventDefault();
    if (!phone || !password) {
      alert("Tous les champs sont requis.");
      return null;
    }
   
    if(isLogin){
       Udat_user({phone,password}).then((data)=>{
           if(data!=0 && data !=1 ){
                localStorage.setItem("quizUser", JSON.stringify({pseudo}));
                 onSubmit?.({phone});
                 setShowForm(false);
           }else{
                  setIsyou("mot passe ou Téléphone incorrect");
                   setShowForm(true);
                 
               
           }
       })
    }
   
  };

 if (!showForm) return null;

if(!isLogin){
   return (
    <div className="user-form" style={{ padding: 20, maxWidth: 400, margin: "0 auto" }}>
      <h2>📝 Créer un compte joueur</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <label>Pseudo :</label>
          <input type="text" value={pseudo} onChange={(e) => setPseudo(e.target.value)} placeholder="Pseudo" />
        </div>
        <div>
          <label>Téléphone :</label>
          <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} />
        </div>
        <div>
          <label>Mot de passe :</label>
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
        </div>
        <button type="submit">{isLogin ? "Se connecter" : "Créer un compte"}</button>
       
      </form>
        <p style={{ marginTop: 10 }}>
        {isLogin ? "Pas encore de compte ?" : "Déjà inscrit ?"}{" "}
        <button type="button" onClick={() => setIsLogin(!isLogin)} style={{ background: "none", border: "none", color: "#007bff", cursor: "pointer" }}>
          {isLogin ? "Créer un compte" : "Se connecter"}
        </button>
      </p>
    </div>); 
    }
  else if  (isLogin){ 
  return (
        <div className="user-form" style={{ padding: 20, maxWidth: 400, margin: "0 auto" }}>
      <h2>📝 Connexion </h2>
      <form onSubmit={handleSubmitcon}>
         <div>
          <label>Téléphone :</label>
          <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="Téléphone" focus="focus" />
        </div>
        <div>
          <label>Mot de passe :</label>
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="mot de passe"/>
        </div>
        
        <button type="submit">{isLogin ? "Se connecter" : "Créer un compte"}</button>
              </form>
        <p style={{ marginTop: 10 }}>
        {isLogin ? "Pas encore de compte ?" : "Déjà inscrit ?"}{" "} <br/>
        <button type="button" onClick={() => setIsLogin(!isLogin)} style={{ background: "none", border: "none", color: "#007bff", cursor: "pointer" }}>
          {isLogin ? "Créer un compte" : "Se connecter"}
        </button>
        
      </p>
      <p style={{"color":"red"}}> {isyou !=null ? isyou : ""} </p>
    </div> 
        ); 
    
}

}
 const Dashboard = ({ userData, classe, matiere,setModal }) => {
  const [badges, setBadges] = React.useState(0);
  const [points, setPoints] = React.useState(0);
  const [user, setUser] = useState(() => { const saved = localStorage.getItem("quizUser"); return saved ? JSON.parse(saved) : null;});
  const [loadingWithdrawal, setLoadingWithdrawal] = useState(false);
const b = JSON.parse(localStorage.getItem("badges") || "0");
 const pts = parseInt(localStorage.getItem("totalPoints") || "0");
  React.useEffect(() => {
   const  c = parseInt(b.argent)+parseInt(b.bronze) +parseInt(b.or)+parseInt(b.diamant);
   if (typeof c === "number" && !isNaN(c)) { setBadges(c);
    }else{
setBadges(0)
    }
    setPoints(pts)
  }, []);
const gourdesbagdes = parseInt(b.diamant)*5 + parseInt(b.or) + parseInt(b.argent)/4 +  parseInt(b.bronze)/8+ pts/32;
 
function getGourdes() {
if (typeof gourdesbagdes === "number" && !isNaN(gourdesbagdes)) {
    Updat_bagde();
  return  Math.round(gourdesbagdes * 100) / 100;
}else{return 0}
}
  
async function sendWithdrawalRequest(c, setModal) {
  try {
      setLoadingWithdrawal(true);
    const response = await fetch("api/requestWithdrawal.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(c)
    });

    const data = await response.json();
 setLoadingWithdrawal(false);
    if (data.success) {
        
      setModal({
        title: "✅ Demande envoyée",
        content: data.message || "Votre demande de retrait a été soumise avec succès.",
        actions: [{ label: "OK", onClick: () => setModal(null) }]
      });
    } else {
      setModal({
        title: "❌ Échec",
        content: data.message || "Une erreur est survenue lors de la soumission.",
        actions: [{ label: "Fermer", onClick: () => setModal(null) }]
      });
    }
  } catch (error) {
    console.error("Erreur lors de la requête :", error);
    setModal({
      title: "❌ Erreur réseau",
      content: "Impossible de contacter le serveur. Veuillez réessayer plus tard.",
      actions: [{ label: "Fermer", onClick: () => setModal(null) }]
    });
  }
}

const handleRequestWithdrawal = () => {
  const username = localStorage.getItem("username");
    if (!username ||  gourdesbagdes < 2500) {
    setModal({
      title: "❗ Retrait impossible",
      content: "Vous devez avoir au moins 2500 Gdes pour demander un retrait.",
      actions: [{ label: "OK", onClick: () => setModal(null) }]
    });
    return;
  }else{
      setLoadingWithdrawal(true);
  const requestData = {
    username,
    amount: Math.floor(gourdesbagdes*0.8),
    phone: localStorage.getItem("phone") || "non renseigné"
  };

  sendWithdrawalRequest(requestData, setModal);
  
  }
};
const ProgressionParMatiere = () => {
  return (
  <div>
    <h3>📈 Progression par matière ({classe})</h3>

    {(matieres[classe] || []).map((matiere) => {
      const total = niveauxParMatiere[matiere] || 0;
      if (total === 0) return null;

      let completed = 0;

      const lastData = JSON.parse(localStorage.getItem("lastNiveauKey")) || {};

      // Ajout de la progression finale uniquement si existante dans lastNiveauKey
      if (classe === "NSIV" && matiere === "chimie" && lastData.chimieNSIV) {
        completed = parseInt(lastData.chimieNSIV.slice(-1)) || 0;
      } else if (classe === "9eme" && matiere === "biologie" && lastData.bio9eme) {
        completed = parseInt(lastData.bio9eme.slice(-1)) || 0;
      } else {
        for (let i = 1; i <= total; i++) {
          const key = `${classe}_${matiere}_niveau${i}`;
          if (userData[key]?.completed) completed++;
        }
      }

      const pourcentage = total > 0 ? (completed / total) * 100 : 0;

      return (
        <div key={matiere} style={{ marginBottom: "1rem" }}>
          <strong>{matiere} :</strong> {completed}/{total} niveaux complétés
          <div style={{
            background: "#eee",
            height: "10px",
            borderRadius: "10px",
            marginTop: "5px",
            overflow: "hidden"
          }}>
            <div style={{
              width: `${pourcentage}%`,
              background: "#4caf50",
              height: "100%",
              transition: "width 0.3s ease"
            }} />
          </div>
        </div>
      );
    })}
  </div>
);

};

  
if (!user) {
  return (
    <UserForm onSubmit={(data) => {
      localStorage.setItem("quizUser", JSON.stringify(data));
      setUser(data);
    }} />
  );
}

  return (
    <div className="dashboard">
      <h2>🎓 Tableau de bord</h2>
      <ShareButton text="Nous sommes ravis de vous inviter à prendre part à notre quiz éducatif captivant. Que vous soyez élève, enseignant ou simplement désireux d'élargir vos connaissances, ce quiz est fait pour vous !

Mettez à l'épreuve vos compétences dans diverses disciplines, notamment :

Traduction Créole-Anglais
Chimie
Sciences de la Vie et de la Terre (SVT)
Accumulez des points en répondant correctement aux questions et relevez le défi d'apprendre de nouvelles choses." />
      <p className="badges-section">Total de points : <strong>{points}</strong></p>
      <p className="badges-section">Badges spéciaux obtenus : <strong>{badges}</strong></p>
      
      <div className="badges-section">
          <h3>Mes badges spéciaux</h3>
       <ul className="badges-list">
           <div> 
               <li className="badge"><span>💎</span><br/>{b.diamant}</li> </div>
           <div><li className="badge">  <span>🥇</span><br/>{b.or}</li></div>
           <div><li className="badge"> <span>🥈</span><br/>{b.argent}</li></div>
           <div><li className="badge"> <span>🥉</span><br/>{b.bronze}</li></div>
       </ul>
       </div>
          <div className="badges-section ">
              <h3>Portefeuille</h3>
          <div className="badges-list gdes" >
           <span>{getGourdes()} GOURDES</span>
           {gourdesbagdes>2500 ? (
           <button onClick={handleRequestWithdrawal}  disabled={loadingWithdrawal}>
  {loadingWithdrawal ? "⏳ Traitement…" : "💸 Demander un retrait"}
</button>
         ):( <button className="pranl" disabled={true}> Retrait || 2500 Gourdes</button>)}
          </div>
          </div>
          <div  className="badges-section ">
              <ProgressionParMatiere />
          </div>
           
       </div>
           
        );
};
function PrivacyPolicy() {
  const [accepted, setAccepted] = useState(false);

  useEffect(() => {
    const hasAccepted = localStorage.getItem("privacyAccepted") === "true";
    if (hasAccepted) {
      setAccepted(true);
      //onAccept?.(); // Sécurité au cas où onAccept est undefined
    }
  }, []);

  const handleAccept = () => {
    localStorage.setItem("privacyAccepted", "true");
    setAccepted(true);
    onAccept?.();
  };

  return (
    <div className="privacy-policy" style={{ padding: 20, maxWidth: 800, margin: "0 auto" }}>
      <h2>📜 Politique de Confidentialité</h2>
      <p><strong>Dernière mise à jour :</strong> 04/06/2025</p>

      <p>Votre confidentialité est importante pour nous. Cette application collecte :</p>
      <ul>
        <li>Nom d’utilisateur (pseudo)</li>
        <li>Numéro de téléphone</li>
        <li>Progression dans les quiz</li>
        <li>Récompenses, badges et scores</li>
        <li>Historique</li>
      </ul>

      <p>Les données sont utilisées uniquement pour suivre vos progrès et attribuer vos récompenses. Aucune donnée n’est vendue ou partagée à des tiers.</p>

      <p>En jouant à notre jeux, automatiquement, vous acceptez  cette politique.</p>
      <p>Nous nous reservons le droit de modifier cette politique.</p>

      <div style={{ marginTop: 20 }}>
        <label>
          <input
            type="checkbox"
            checked={accepted}
            onChange={handleAccept}
            disabled={accepted}
          />
          {" "}J’ai lu et j’accepte la politique de confidentialité
        </label>
      </div>
    </div>
  );
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(React.createElement(App));
const cookieRoot = ReactDOM.createRoot(document.getElementById("cookie-root"));
cookieRoot.render(React.createElement(CookieBanner));
  
function DuelApp() {
  const [config, setConfig] = React.useState({});
  const [matiere, setMatiere] = React.useState("");
  const [questions, setQuestions] = React.useState([]);
  const [currentIndex, setCurrentIndex] = React.useState(0);
  const [player, setPlayer] = React.useState("");
  const [roomId, setRoomId] = React.useState("");
  const [score, setScore] = React.useState(0);
  const [quizStarted, setQuizStarted] = React.useState(false);
  const [timer, setTimer] = React.useState(10);
  const [feedback, setFeedback] = React.useState(""); // "correct" | "wrong"
  const [ended, setEnded] = React.useState(false);
  const [finalScores, setFinalScores] = React.useState({});

  const current = questions[currentIndex];

  React.useEffect(() => {
    fetch("config.json")
      .then((res) => res.json())
      .then((data) => setConfig(data));
  }, []);

  const createRoom = () => {
    const id = Math.random().toString(36).substr(2, 6).toUpperCase();
    setRoomId(id);
    setPlayer("player1");
    alert(`Code à partager : ${id}`);
  };

  const joinRoom = () => {
    const code = prompt("Code room :");
    if (code) {
      firebase.database().ref(`rooms/${code}`).once("value", (snap) => {
        if (snap.exists()) {
          setRoomId(code);
          setPlayer("player2");
        } else {
          alert("Room inexistante");
        }
      });
    }
  };

  const handleMatiereChange = (e) => {
    const mat = e.target.value;
    setMatiere(mat);
    const total = config[mat];
    if (!total) return alert("Pas de niveau dispo.");
    const niv = Math.floor(Math.random() * total) + 1;
    const fichier = `capitale/${mat}_${niv}.json`;

    fetch(fichier)
      .then((res) => res.json())
      .then((data) => {
        setQuestions(data);
        setQuizStarted(true);
        const ref = firebase.database().ref(`rooms/${roomId}`);
        if (player === "player1") {
          ref.set({
            matiere: mat,
            niveau: niv,
            questions: data,
            scores: { player1: 0, player2: 0 },
            index: 0,
          });
        }
      });
  };

//   React.useEffect(() => {
//     if (!roomId) return;
//     const ref = firebase.database().ref(`rooms/${roomId}`);
//     ref.on("value", (snap) => {
//       const data = snap.val();
//       if (data) {
//         if (data.questions) setQuestions(data.questions);
//         if (data.index !== undefined) setCurrentIndex(data.index);
//         if (data.scores && player) {
//           setScore(data.scores[player]);
//           setFinalScores(data.scores);
//         }
//       }
//     });
//     return () => ref.off();
//   }, [roomId, player]);
React.useEffect(() => {
  if (!roomId) return;

  const ref = firebase.database().ref(`rooms/${roomId}`);
  ref.on("value", (snap) => {
    const data = snap.val();
    if (data) {
      if (data.questions && data.questions.length) {
        setQuestions(data.questions);
        setQuizStarted(true); // 👈 Ajout essentiel pour joueur 2
      }
      if (data.index !== undefined) setCurrentIndex(data.index);
      if (data.scores && player) {
        setScore(data.scores[player]);
        setFinalScores(data.scores);
      }
    }
  });

  return () => ref.off();
}, [roomId, player]);


  // Chrono par question
  React.useEffect(() => {
    if (!quizStarted || ended) return;
    setTimer(10);
    const interval = setInterval(() => {
      setTimer((t) => {
        if (t <= 1) {
          clearInterval(interval);
          handleAnswer(null);
        }
        return t - 1;
      });
    }, 1000);
    return () => clearInterval(interval);
  }, [currentIndex, quizStarted]);

  const handleAnswer = (rep) => {
    if (!current || ended) return;

    const isCorrect = rep && current.answer.includes(rep);
    setFeedback(isCorrect ? "correct" : "wrong");

    const ref = firebase.database().ref(`rooms/${roomId}`);
    if (isCorrect) {
      ref.child("scores").child(player).transaction((val) => (val || 0) + 1);
    }

    setTimeout(() => {
      setFeedback("");
      if (player === "player1" && currentIndex + 1 < questions.length) {
        ref.child("index").set(currentIndex + 1);
      }

      if (currentIndex + 1 >= questions.length) {
        setEnded(true);
        setQuizStarted(false);
        setTimeout(() => {
          firebase.database().ref(`rooms/${roomId}`).remove();
        }, 4000);
      }
    }, 1000);
  };

  const renderEnd = () => {
    if (!ended) return null;
    const s1 = finalScores.player1 || 0;
    const s2 = finalScores.player2 || 0;
    let result;
    if (s1 === s2) result = "Égalité !";
    else if ((player === "player1" && s1 > s2) || (player === "player2" && s2 > s1)) {
      result = "🎉 Tu as gagné !";
    } else {
      result = "😢 Tu as perdu.";
    }
    return (
      <div style={{ textAlign: "center", padding: 20 }}>
        <h2>Résultat final</h2>
        <p>Player 1 : {s1} | Player 2 : {s2}</p>
        <h3>{result}</h3>
        <button onClick={() => window.location.reload()}>Rejouer</button>
      </div>
    );
  };

  if (!roomId) {
    return (
      <div>
        <h2>Duel Multijoueur</h2>
        <button onClick={createRoom}>Créer une room</button>
        <button onClick={joinRoom}>Rejoindre une room</button>
      </div>
    );
  }

  if (!quizStarted && player === "player1" && !ended) {
    return (
      <div>
        <h3>Choisis une matière</h3>
        <select onChange={handleMatiereChange} value={matiere}>
          <option value="">-- Choisir --</option>
          {Object.keys(config).map((m) => (
            <option key={m} value={m}>{m}</option>
          ))}
        </select>
      </div>
    );
  }

  if (!quizStarted && !ended) {
    return <p>En attente de questions…</p>;
  }
const getAdversaire = () => (player === "player1" ? "player2" : "player1");

  return (
    <div>
      <h2>{player === "player1" ? "🧑 Joueur 1" : "🧑 Joueur 2"} | Room: {roomId}</h2>
      <p>Question {currentIndex + 1} / {questions.length}</p>
      <p><strong>Temps restant : {timer}s</strong></p>
      <p>{current?.question}</p>
      {current?.reponse.map((r, i) => (
        <button
          key={i}
          onClick={() => handleAnswer(r)}
          style={{
            margin: 5,
            padding: "8px 12px",
            backgroundColor: feedback === "correct" && current.answer.includes(r) ? "green"
              : feedback === "wrong" && r === current.reponse[i] ? "red"
              : "#eee",
            color: feedback ? "#fff" : "#000",
            transition: "0.3s",
            borderRadius: "8px",
            border: "none"
          }}
          disabled={!!feedback}
        >
          {r}
        </button>
      ))}
      <div style={{ display: "flex", justifyContent: "center", gap: "30px", marginTop: "10px" }}>
  <div style={{ background: "#f0f0f0", padding: "10px", borderRadius: "10px" }}>
    🧑 Ton score : <strong>{score}</strong>
  </div>
  <div style={{ background: "#f0f0f0", padding: "10px", borderRadius: "10px" }}>
    👤 Score adversaire : <strong>{finalScores[getAdversaire()] || 0}</strong>
  </div>
</div>

      {renderEnd()}
    </div>
  );
}


