<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="UTF-8" />
  <title>Losowe Pytania</title>
  <style>
    body { font-family: Arial, sans-serif; max-width: 800px; margin: 30px auto; }
    .question { font-size: 1.2em; font-weight: bold; white-space: normal; word-wrap: break-word; min-height: 1.5em; }
    .answer p { margin: 10px 0; }
    button { margin: 10px 5px; padding: 10px 15px; font-size: 1em; }
    textarea, input, select { width: 100%; margin: 5px 0; padding: 5px; box-sizing: border-box; }
    textarea#newQuestion { resize: vertical; overflow-y: hidden; }
    .progress-container { background: #eee; border-radius: 10px; overflow: hidden; margin: 10px 0; height: 20px; }
    .progress-bar { height: 100%; background: #4caf50; width: 0%; transition: width 0.3s ease; }
  </style>
</head>
<body>
  <h1>Losowe Pytania</h1>

  <div id="counter" style="font-weight: bold; margin: 10px 0;"></div>
  <div class="progress-container"><div id="questionProgress" class="progress-bar"></div></div>

  <div id="questionContainer" class="question"></div>
  <div id="answerContainer" class="answer"></div>
  <div class="progress-container"><div id="answerProgress" class="progress-bar"></div></div>

  <button onclick="showNextParagraph()">? Pokaz kolejny akapit</button>
  <button onclick="previousQuestion()">? Poprzednie pytanie</button>
  <button onclick="nextQuestion()">? Nastepne pytanie</button>
  <button onclick="resetLosowania()">?? Resetuj losowanie</button>

  <hr>
  <h2>Dodaj / Edytuj pytanie</h2>

  <label>Wyszukaj pytanie:</label>
  <input type="text" id="searchInput" placeholder="Wpisz fragment pytania" oninput="refreshSelect()" />

  <label>Wybierz pytanie do edycji:</label>
  <select id="questionSelect" onchange="loadQuestionForEdit()">
    <option value="">-- nowe pytanie --</option>
  </select>

  <label>Tresc pytania:</label>
  <textarea id="newQuestion" rows="2" placeholder="Tresc pytania"></textarea>

  <label>Odpowiedz (paragrafy oddzielone pusta linia):</label>
  <textarea id="newAnswer" rows="5" placeholder="Odpowiedz (paragrafy oddzielone pusta linia)"></textarea>

  <button onclick="saveQuestion()">?? Zapisz</button>
  <button onclick="deleteQuestion()">?? Usun</button>

  <hr>
  <button onclick="exportQuestions()">?? Eksportuj pytania</button>
  <button onclick="document.getElementById('fileInput').click()">?? Importuj pytania</button>
  <input type="file" id="fileInput" accept=".json" style="display:none" onchange="importQuestions(event)">

  <script>
    let questions = loadFromLocalStorage();
    let unusedQuestions = [...questions];
    let currentAnswer = [];
    let currentIndex = 0;
    let questionHistory = [];

    function clearEditForm() {
      document.getElementById("newQuestion").value = "";
      document.getElementById("newAnswer").value = "";
      document.getElementById("questionSelect").value = "";
      autoResizeTextarea(document.getElementById("newQuestion"));
    }

    function loadFromLocalStorage() {
      const saved = localStorage.getItem("questionData");
      return saved ? JSON.parse(saved) : [
        {
          question: "1.1.1 Co to jest HTML?",
          answer: [
            "HTML to jezyk znaczników.",
            "Sluzy do strukturyzowania tresci stron internetowych.",
            "Jest fundamentem kazdej strony WWW."
          ]
        }
      ];
    }

    function saveToLocalStorage() {
      localStorage.setItem("questionData", JSON.stringify(questions));
    }

    function shuffle(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
    }

    function updateQuestionProgress() {
      const shown = questions.length - unusedQuestions.length;
      const percent = Math.round((shown / questions.length) * 100);
      document.getElementById("counter").innerText = `${shown} / ${questions.length}`;
      document.getElementById("questionProgress").style.width = percent + "%";
    }

    function updateAnswerProgress() {
      const percent = currentAnswer.length === 0 ? 0 : Math.round((currentIndex / currentAnswer.length) * 100);
      document.getElementById("answerProgress").style.width = percent + "%";
    }

    function showQuestion() {
      if (unusedQuestions.length === 0) {
        document.getElementById("questionContainer").innerText = "Koniec pytan!";
        document.getElementById("answerContainer").innerHTML = "";
        currentAnswer = [];
        currentIndex = 0;
        updateQuestionProgress();
        updateAnswerProgress();
        clearEditForm();
        return;
      }

      shuffle(unusedQuestions);
      const q = unusedQuestions.pop();

      questionHistory.push(q);

      currentAnswer = [...q.answer];
      currentIndex = 0;

      document.getElementById("questionContainer").innerText = q.question;
      document.getElementById("answerContainer").innerHTML = "";
      updateQuestionProgress();
      updateAnswerProgress();

      const index = questions.findIndex(item => item.question === q.question);
      document.getElementById("questionSelect").value = index !== -1 ? index : "";

      clearEditForm();
    }

    function showNextParagraph() {
      if (currentIndex < currentAnswer.length) {
        const p = document.createElement("p");
        p.innerText = currentAnswer[currentIndex];
        document.getElementById("answerContainer").appendChild(p);
        currentIndex++;
        updateAnswerProgress();
      }
    }

    function nextQuestion() {
      showQuestion();
    }

    function previousQuestion() {
      if (questionHistory.length < 2) {
        alert("Brak poprzedniego pytania.");
        return;
      }

      questionHistory.pop();
      const prev = questionHistory[questionHistory.length - 1];

      currentAnswer = [...prev.answer];
      currentIndex = 0;

      document.getElementById("questionContainer").innerText = prev.question;
      document.getElementById("answerContainer").innerHTML = "";
      updateAnswerProgress();

      const index = questions.findIndex(item => item.question === prev.question);
      document.getElementById("questionSelect").value = index !== -1 ? index : "";

      clearEditForm();
    }

    function resetLosowania() {
      if (!confirm("Czy na pewno chcesz zresetowac losowanie i rozpoczac od poczatku?")) return;

      unusedQuestions = [...questions];
      questionHistory = [];
      updateQuestionProgress();
      updateAnswerProgress();
      showQuestion();
    }

    function refreshSelect() {
      const select = document.getElementById("questionSelect");
      const filter = document.getElementById("searchInput").value.toLowerCase();

      select.innerHTML = '<option value="">-- nowe pytanie --</option>';

      const filtered = questions
        .map((q, i) => ({ index: i, question: q.question }))
        .filter(item => item.question.toLowerCase().includes(filter))
        .sort((a, b) => a.question.localeCompare(b.question, undefined, { numeric: true }));

      for (const item of filtered) {
        const option = document.createElement("option");
        option.value = item.index;
        option.text = item.question.slice(0, 80);
        select.appendChild(option);
      }
    }

    function loadQuestionForEdit() {
      const index = document.getElementById("questionSelect").value;
      if (index === "") {
        clearEditForm();
        return;
      }

      const q = questions[index];
      document.getElementById("newQuestion").value = q.question;
      document.getElementById("newAnswer").value = q.answer.join("\n\n");
      autoResizeTextarea(document.getElementById("newQuestion"));
    }

    function saveQuestion() {
      const qText = document.getElementById("newQuestion").value.trim();
      const aText = document.getElementById("newAnswer").value.trim();
      const index = document.getElementById("questionSelect").value;

      if (!qText || !aText) {
        alert("Wprowadz tresc pytania i odpowiedzi.");
        return;
      }

      const paragraphs = aText.split(/\n\s*\n/).map(p => p.trim()).filter(p => p.length > 0);
      const qObj = { question: qText, answer: paragraphs };

      if (index === "") {
        questions.push(qObj);
        unusedQuestions.push(qObj);
      } else {
        questions[index] = qObj;
      }

      saveToLocalStorage();
      refreshSelect();
      clearEditForm();
      alert("Zapisano pytanie.");
    }

    function deleteQuestion() {
      const index = document.getElementById("questionSelect").value;
      if (index === "") return;

      if (confirm("Czy na pewno usunac to pytanie?")) {
        questions.splice(index, 1);
        saveToLocalStorage();
        refreshSelect();
        unusedQuestions = [...questions];
        clearEditForm();
        showQuestion();
      }
    }

    function exportQuestions() {
      const dataStr = JSON.stringify(questions, null, 2);
      const blob = new Blob([dataStr], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "pytania.json";
      a.click();
      URL.revokeObjectURL(url);
    }

    function importQuestions(event) {
      const file = event.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = function(e) {
        try {
          const data = JSON.parse(e.target.result);
          if (!Array.isArray(data) || !data.every(q => q.question && Array.isArray(q.answer))) {
            alert("Nieprawidlowy format danych!");
            return;
          }

          if (!confirm("Import zastapi wszystkie aktualne pytania. Kontynuowac?")) return;

          questions = data;
          unusedQuestions = [...questions];
          saveToLocalStorage();
          refreshSelect();
          showQuestion();
        } catch (err) {
          alert("Blad podczas importu: " + err.message);
        }
      };
      reader.readAsText(file);
    }

    const questionTextarea = document.getElementById("newQuestion");
    function autoResizeTextarea(el) {
      el.style.height = "auto";
      el.style.height = el.scrollHeight + "px";
    }
    questionTextarea.addEventListener("input", () => {
      autoResizeTextarea(questionTextarea);
    });

    autoResizeTextarea(questionTextarea);
    refreshSelect();
    showQuestion();
  </script>
</body>
</html>