<script>
  import { onMount } from 'svelte';

  let username = '';
  let password = '';
  let dirtyWords = [];
  let selectedWords = '';
  let isLoggingIn = false;
  let loginMessage = '';
  let schools = [];
  let selectedSchool = '';
  let schoolSearchText = '';
  let showSchoolDropdown = false;
  let showForgotPasswordModal = false;
  let isAdmin = false;

  async function loadDirtyWords() {
    try {
      const response = await fetch('/dirtyWords.xml');
      const xmlText = await response.text();
      const parser = new DOMParser();
      const xmlDoc = parser.parseFromString(xmlText, "text/xml");
      const wordElements = xmlDoc.getElementsByTagName("Word");
      
      dirtyWords = [];
      for (let i = 0; i < wordElements.length; i++) {
        dirtyWords.push(wordElements[i].textContent);
      }
      
      shuffleWords();
    } catch (error) {
      console.error('Error loading dirty words:', error);
    }
  }

  async function loadSchools() {
    try {
      const response = await fetch('/sulik.json');
      const data = await response.json();
      schools = data;
    } catch (error) {
      console.error('Error loading schools:', error);
    }
  }

  function shuffleWords() {
    if (dirtyWords.length === 0) return;
    
    const shuffled = [...dirtyWords].sort(() => 0.5 - Math.random());
    const selected = shuffled.slice(0, 3);
    selectedWords = selected.map(word => word.toLowerCase()).join(' ');
  }

  async function handleLogin() {
    isLoggingIn = true;
    loginMessage = "Kérlek, várj, amíg a 3 kiszivárgott adatbázissal egyeztetjük az adataid...";
    
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    try {
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
          username, 
          password,
          selectedSchool: schools.find(s => s.nev === schoolSearchText)
        })
      });

      const data = await response.json();

      if (data.success) {
        if (data.redirect) {
          window.location.href = data.redirect;
          return;
        }

        if (data.content) {
          if (data.content.css) {
            const styleElement = document.createElement('style');
            styleElement.textContent = data.content.css;
            document.head.appendChild(styleElement);
          }

          const tempDiv = document.createElement('div');
          tempDiv.innerHTML = data.content.html;
          
          if (data.type === 'admin') {
            isAdmin = true;
            document.querySelector('main').innerHTML = data.content.html;
            const backButton = document.getElementById('backToLogin');
            if (backButton) {
              backButton.addEventListener('click', () => {
                isAdmin = false;
                isLoggingIn = false;
                loginMessage = '';
                username = '';
                password = '';
              });
            }
          } else {
            document.body.appendChild(tempDiv.firstElementChild);
          }

          if (data.content.js) {
            const scriptElement = document.createElement('script');
            scriptElement.textContent = data.content.js;
            document.body.appendChild(scriptElement);
          }

          isLoggingIn = false;
          loginMessage = '';
          if (data.type !== 'admin') {
            username = '';
            password = '';
          }
        }
      } else {
        loginMessage = "Nem találtuk ezt a felhasználónév és jelszó párt semelyik kiszivárgott adatbázisban";
        isLoggingIn = false;
      }
    } catch (error) {
      loginMessage = "Hiba történt a bejelentkezés során. Próbáld újra később.";
      isLoggingIn = false;
    }
  }

  function handleForgotPassword() {
    showForgotPasswordModal = true;
  }

  function closeModal() {
    showForgotPasswordModal = false;
  }

  function handleSchoolSearch(event) {
    schoolSearchText = event.target.value;
    showSchoolDropdown = true;
  }

  function selectSchool(school) {
    selectedSchool = school.nev;
    schoolSearchText = school.nev;
    showSchoolDropdown = false;
  }

  $: filteredSchools = schoolSearchText.length > 0
    ? schools.filter(school => school.nev.toLowerCase().includes(schoolSearchText.toLowerCase())).slice(0, 5)
    : schools.slice(0, 5);

  onMount(() => {
    loadDirtyWords();
    loadSchools();
  });
</script>

<svelte:head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://ekreten.hu/">
  <meta property="og:title" content="KRETÉN">
  <meta property="og:description" content="orbán 🍊">
  <meta property="og:image" content="https://ekreten.hu/favicon.png">

  <meta property="twitter:card" content="summary">
  <meta property="twitter:url" content="https://ekreten.hu/">
  <meta property="twitter:title" content="KRETÉN">
  <meta property="twitter:description" content="orbán 🍊">
  <meta property="twitter:image" content="https://ekreten.hu/favicon.png">
</svelte:head>

<div class="app-container">
  <main>
    <div class="logo-container">
      <img src="/logo.png" class="logo" alt="KRETÉN logo">
    </div>

    {#if !isAdmin}
      <div class="login-container">
        <div class="login-header">
          <h2>Mi van, te kis {selectedWords || 'toszatlan'}?</h2>
          <button class="refresh-button" on:click={shuffleWords}>⟳</button>
        </div>

        <div class="login-form">
          <p class="login-instructions">
            Kérjük, adja meg az intézményi KRETÉN felhasználónevét és jelszavát.
            Amennyiben elfelejtette, keresse meg valamelyik publikus adatbázisban
          </p>

          <p class="login-note">
            Tisztelt <span class="highlight">Róbert');-- DROP TABLE Tanulo;</span>, technikai okok miatt lehetséges, hogy a rendszer néha (<i>azaz soha</i>) nem működik.
          </p>
          <form 
            on:submit|preventDefault={handleLogin}
            class="login-form-content"
          >
           

            <div class="form-group">
              <input 
                type="text" 
                placeholder="Felhasználónév" 
                bind:value={username}
                class="form-input"
                disabled={isLoggingIn}
              />
            </div>

            <div class="form-group">
              <input 
                type="password" 
                placeholder="Jelszó" 
                bind:value={password}
                class="form-input"
                disabled={isLoggingIn}
              />
            </div>

            <!-- School selector temporarily disabled
             <div class="form-group school-selector">
              <div class="select-wrapper">
                <input 
                  type="text" 
                  id="school-search" 
                  placeholder="Kezdje el begépelni az intézmény nevének valamely részletét..." 
                  class="form-input school-search"
                  disabled
                  bind:value={schoolSearchText}
                  on:input={handleSchoolSearch}
                  on:focus={() => showSchoolDropdown = true}
                  on:blur={() => setTimeout(() => showSchoolDropdown = false, 200)}
                />
                {#if showSchoolDropdown && filteredSchools.length > 0}
                  <div class="school-dropdown">
                    {#each filteredSchools as school}
                      <div 
                        class="school-option" 
                        on:mousedown={() => selectSchool(school)}
                      >
                        {school.nev}
                      </div>
                    {/each}
                  </div>
                {/if}
              </div>
            </div>
            -->

            {#if loginMessage}
              <div class={isLoggingIn ? "login-message" : "login-error"}>
                <p>{loginMessage}</p>
                {#if isLoggingIn}
                  <div class="spinner"></div>
                {/if}
              </div>
            {/if}

            <div class="form-actions">
              <a href="#" on:click|preventDefault={handleForgotPassword} class="forgot-password">
                Elfelejtettem a jelszavam
              </a>
              <button type="submit" class="login-button" disabled={isLoggingIn}>
                Bejelentkezés
              </button>
            </div>
          </form>
        </div>
      </div>

      <div class="disclaimer-alert">
        Ez az oldal kizárólag szatirikus céllal készült, semmilyen kapcsolatban nincs ez az eredeti e-kretaval.<br>
        A bejelentkezési adatok nem az igazi KRÉTA-hoz tartoznak, hanem az oldal easter egg-jei.<br>
        Ne add meg a valódi KRÉTA bejelentkezési adataidat!
      </div>
    {/if}
  </main>

  <footer>
    <a href="https://git.spitkov.hu/spitkov/ekreten">Az oldal forráskódja</a>
    <p>Készült 🍊 megbízásából, 12 Mrd ft közpénzből</p> 
  </footer>
</div>

{#if showForgotPasswordModal}
  <div class="modal-backdrop" on:click={closeModal}>
    <div class="modal-content" on:click|stopPropagation>
      <div class="modal-header">
        <h3>Jelszó visszaállítás</h3>
        <button class="modal-close" on:click={closeModal}>×</button>
      </div>
      <div class="modal-body">
        <div class="spinner modal-spinner"></div>
        <p class="modal-text">A jelszó helyreállítási kérelmét feldolgoztuk, és a következő eredményre jutottunk:</p>
        <p class="modal-error">A KRETÉN nem találta önt <span class="highlight">(Róbert');-- DROP TABLE Tanulo;)</span>-t elég fontosnak ahhoz, hogy foglalkozzon a problémájával.</p>
        <p class="modal-tip">Javasolt megoldások:</p>
        <ul class="modal-solutions">
          <li>Próbáld meg kitalálni a jelszavad. 
            Tippek: <strong>123456</strong>, <strong>password</strong>, <strong>admin</strong>, <strong>qwerty</strong>.</li>
          <li>Kérdezd meg az informatika tanárodat, ő biztosan jobban emlékszik a jelszavadra, mint te.</li>
          <li>Kapcsold ki és be a gépedet.</li>
          <li>Használj firkát. (legjobb opció)</li>
          <li>Az is lehet, hogy a reFilc leakelt adatbázisában lett elmentve a jelszavad, kérdezd meg Kimát is.</li>
        </ul>
        <p class="modal-footer-text">Az új jelszót elküldtük egy véletlenszerű e-mail címre, amit hasonlónak véltünk a tiedhez.</p>
      </div>
    </div>
  </div>
{/if}

<style>
  :global(html), :global(body) {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    -webkit-text-size-adjust: 100%;
    touch-action: manipulation;
  }
  
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: Arial, sans-serif;
    -webkit-tap-highlight-color: transparent;
  }

  .app-container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    width: 100vw;
    background-color: #385764;
    color: #333;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow-x: hidden;
    padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
  }

  main {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    padding: clamp(1rem, 5vw, 2rem);
    width: 100%;
    margin-top: clamp(1rem, 5vh, 3rem);
  }

  .logo-container {
    margin-bottom: clamp(1.5rem, 5vh, 2rem);
    text-align: center;
    padding: 0 1rem;
  }

  .logo {
    max-width: 100%;
    height: auto;
    width: auto;
    max-height: 120px;
  }

  .login-container {
    background-color: white;
    border-radius: 4px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    width: 100%;
    max-width: 600px;
    overflow: hidden;
    margin: 0 1rem;
  }

  .login-header {
    background-color: #30b0d5;
    color: white;
    padding: 1rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .login-header h2 {
    font-size: clamp(1rem, 4vw, 1.2rem);
    font-weight: normal;
    margin: 0;
    line-height: 1.3;
  }

  .refresh-button {
    background: none;
    border: none;
    color: white;
    font-size: clamp(1.2rem, 5vw, 1.5rem);
    cursor: pointer;
    padding: 0.5rem;
    width: 44px;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    touch-action: manipulation;
  }

  .login-form {
    padding: clamp(1rem, 4vw, 1.5rem);
  }

  .login-instructions {
    margin-bottom: 1rem;
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
  }

  .login-note {
    margin-bottom: 1.5rem;
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
  }

  .highlight {
    color: #30b0d5;
    text-decoration: underline;
    cursor: pointer;
  }

  .form-group {
    margin-bottom: clamp(0.8rem, 3vw, 1rem);
  }

  .form-input {
    width: 100%;
    padding: 0.4rem 0.6rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: #f5f5f5;
    font-size: 16px;
  }

  .select-wrapper {
    position: relative;
  }

  .school-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    max-height: clamp(180px, 40vh, 300px);
    overflow-y: auto;
    background-color: white;
    border: 1px solid #ddd;
    border-top: none;
    border-radius: 0 0 4px 4px;
    z-index: 10;
    display: block;
  }

  .school-option {
    padding: clamp(0.7rem, 3vw, 0.8rem);
    cursor: pointer;
    border-bottom: 1px solid #eee;
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
  }

  .school-option:hover {
    background-color: #f5f5f5;
  }

  .login-message {
    background-color: #f8f9fa;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: clamp(0.8rem, 3vw, 1rem);
    margin-bottom: 1.5rem;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1rem;
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
  }

  .login-error {
    background-color: #f8d7da;
    border: 1px solid #f5c6cb;
    border-radius: 4px;
    padding: clamp(0.8rem, 3vw, 1rem);
    margin-bottom: 1.5rem;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1rem;
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
    color: #e74c3c;
  }

  .spinner {
    width: clamp(30px, 8vw, 40px);
    height: clamp(30px, 8vw, 40px);
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-radius: 50%;
    border-top-color: #30b0d5;
    animation: spin 1s ease-in-out infinite;
  }

  .form-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 1.5rem;
    gap: 1rem;
  }

  .forgot-password {
    color: #30b0d5;
    text-decoration: none;
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
  }

  .login-button {
    background-color: #30b0d5;
    color: white;
    border: none;
    border-radius: 4px;
    padding: clamp(0.4rem, 2vw, 0.5rem) clamp(0.8rem, 3vw, 1rem);
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
    cursor: pointer;
    transition: background-color 0.2s;
    min-width: 120px;
  }

  .login-button:hover {
    background-color: #2698bb;
  }

  .login-button:disabled {
    background-color: #88cce2;
    cursor: not-allowed;
  }

  .disclaimer-alert {
    background-color: #cce5ff;
    border: 1px solid #b8daff;
    color: #004085;
    padding: 12px 20px;
    border-radius: 4px;
    margin-top: 20px;
    text-align: center;
    font-size: 0.95rem;
    max-width: 600px;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 0;
  }

  .modal-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
  }

  .modal-content {
    background-color: white;
    border-radius: 4px;
    width: 95%;
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
  }

  .modal-header {
    background-color: #30b0d5;
    color: white;
    padding: clamp(0.8rem, 3vw, 1rem);
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 60px;
  }

  .modal-header h3 {
    font-size: clamp(1rem, 4vw, 1.2rem);
    font-weight: normal;
    margin: 0;
  }

  .modal-close {
    background: none;
    border: none;
    color: white;
    font-size: clamp(1.5rem, 5vw, 1.8rem);
    cursor: pointer;
    padding: 0.3rem;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    touch-action: manipulation;
  }

  .modal-body {
    padding: clamp(1rem, 4vw, 1.5rem);
    text-align: center;
  }

  .modal-spinner {
    margin: 0 auto 1.5rem;
  }

  .modal-text {
    margin-bottom: 1rem;
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
  }

  .modal-error {
    margin-bottom: 1.5rem;
    color: #e74c3c;
    font-weight: bold;
    font-size: clamp(0.9rem, 3.5vw, 1rem);
  }

  .modal-tip {
    margin-bottom: 0.5rem;
    font-weight: bold;
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
  }

  .modal-solutions {
    text-align: left;
    margin-bottom: 1.5rem;
    padding-left: 1.5rem;
  }

  .modal-solutions li {
    margin-bottom: 0.5rem;
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
  }

  .modal-footer-text {
    font-size: clamp(0.8rem, 3vw, 0.85rem);
    font-style: italic;
    color: #777;
  }

  footer {
    text-align: center;
    padding: clamp(0.8rem, 3vw, 1rem);
    color: white;
    font-size: clamp(0.75rem, 3vw, 0.8rem);
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    align-items: center;
  }

  .footer-links {
    display: flex;
    align-items: center;
    gap: 1rem;
  }

  .footer-separator {
    color: rgba(255, 255, 255, 0.5);
  }

  footer a {
    color: white;
    text-decoration: none;
    padding: 0.5rem;
    min-height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  @keyframes spin {
    to { transform: rotate(360deg); }
  }

  @media (max-width: 640px) {
    .form-actions {
      flex-direction: column;
      align-items: stretch;
    }

    .login-button {
      width: 100%;
      order: -1;
    }

    .forgot-password {
      text-align: center;
    }

    .modal-content {
      width: 100%;
      height: 100%;
      max-height: none;
      border-radius: 0;
    }
  }

  @media (orientation: landscape) and (max-height: 600px) {
    main {
      margin-top: 0.5rem;
    }

    .logo {
      max-height: 80px;
    }

    .logo-container {
      margin-bottom: 1rem;
    }

    .login-form {
      padding: 1rem;
    }

    .form-group {
      margin-bottom: 0.5rem;
    }

    .form-actions {
      margin-top: 1rem;
    }
  }

  .admin-button {
    background-color: #30b0d5;
    color: white;
    border: none;
    border-radius: 4px;
    padding: clamp(0.4rem, 2vw, 0.5rem) clamp(0.8rem, 3vw, 1rem);
    font-size: clamp(0.85rem, 3.5vw, 0.9rem);
    cursor: pointer;
    transition: background-color 0.2s;
    text-align: center;
    text-decoration: none;
    display: block;
  }
</style>
