<script>
  import { SvelteReader } from "svelte-reader";
  import { browser } from '$app/environment';
  import { onMount } from 'svelte';
  import { base } from '$app/paths';
  import { translateText, translateWord } from '$lib/translation';
  import { Tooltip } from 'flowbite-svelte';
  
  let url = '';
  let rendition = null;
  let selections = [];
  let translation = '';
  let isLoading = false;
  let location = browser && localStorage.getItem("book-progress") || null;
  let firstRenderDone = false;
  let error = null;
  let tooltipVisible = false;
  let tooltipStyle = '';

  onMount(async () => {
    try {
      const params = new URLSearchParams(window.location.search);
      url = params.get('url');
      
      if (!url) {
        throw new Error('URL parametresi bulunamadı');
      }

      url = decodeURIComponent(url);
      
      if (!url.startsWith('http')) {
        url = `${base}${url.startsWith('/') ? '' : '/'}${url}`;
      }
      
      if (rendition) {
        rendition.load(url);
      }
    } catch (err) {
      console.error('Kitap yüklenemedi:', err);
      error = err.message;
    }
  });

  const locationChange = (e) => {
    if(!browser) return;
    const epubcifi = e.detail;
    
    if (!firstRenderDone) {
      location = localStorage.getItem("book-progress");
      return (firstRenderDone = true);
    }
    
    localStorage.setItem("book-progress", epubcifi);
    location = epubcifi;
  };

  const getRendition = (val) => {
    rendition = val;
    rendition.themes.default({
      "::selection": {
        background: "orange",
      },
    });

    rendition.on("mouseup", handleMouseUp);
    rendition.on("click", () => {
      tooltipVisible = false;
    });
  };

  async function handleMouseUp(event, contents) {
    const selection = contents.window.getSelection();
    const selectedText = selection.toString().trim();
    
    if (!selectedText) {
      tooltipVisible = false;
      return;
    }

    try {
      isLoading = true;

      // Seçimin pozisyonunu al
      const range = selection.getRangeAt(0);
      const rect = range.getBoundingClientRect();
      
      // Tooltip pozisyonunu hesapla
      tooltipStyle = `
        position: fixed;
        left: ${rect.left + rect.width / 2}px;
        top: ${rect.top - 10}px;
        transform: translateX(-50%);
        z-index: 1000;
      `;

      // Context al ve çeviriyi yap
      const section = contents.window.document.querySelector("body").textContent;
      const textIndex = section.indexOf(selectedText);
      const context = section.substring(
        Math.max(0, textIndex - 30),
        Math.min(section.length, textIndex + selectedText.length + 30)
      );

      const isSingleWord = selectedText.split(/\s+/).length === 1;
      translation = isSingleWord 
        ? await translateWord(selectedText, context)
        : await translateText(selectedText);

      tooltipVisible = true;

      // Seçimi kaydet
      selections = [...selections, {
        text: selectedText,
        translation,
        cfiRange: rendition.location.start.cfi
      }];

      // Highlight ekle
      rendition.annotations.highlight(
        rendition.location.start.cfi,
        {},
        null,
        "hl",
        {
          fill: "#fff59d",
          "fill-opacity": "0.5",
        }
      );

    } catch (err) {
      console.error('Çeviri hatası:', err);
      translation = 'Çeviri yapılırken bir hata oluştu.';
    } finally {
      isLoading = false;
    }
  }

  const removeSelection = (index) => {
    const selection = selections[index];
    if (selection?.cfiRange) {
      rendition.annotations.remove(selection.cfiRange, "hl");
    }
    selections = selections.filter((_, i) => i !== index);
  };
</script>

<div class="relative h-screen bg-gray-100">
  {#if error}
    <div class="p-4 bg-red-100 text-red-700">
      Hata: {error}
    </div>
  {/if}

  <div class="h-full relative">
    {#if url}
      <SvelteReader 
        {url}
        epubOptions="{{
          flow: 'scrolled',
          manager: 'continuous'
        }}"
        {location}
        getRendition={getRendition}
        on:update:location={locationChange}
        let:title
        class="z-10" <!-- Buraya z-index ekledik, daha düşük olacak -->
      >
        <div slot="loadingView" class="flex items-center justify-center h-full">
          <div class="text-center">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 mb-4"></div>
            <p>Kitap yükleniyor...</p>
          </div>
        </div>
      </SvelteReader>
    {/if}
  </div>

  {#if tooltipVisible && translation}
    <div 
      style={`${tooltipStyle}; z-index: 9999;`}
      class="bg-white shadow-lg rounded p-2 min-w-[150px] max-w-[300px] text-sm border"
    >
      {#if isLoading}
        <div class="flex justify-center p-2">
          <div class="animate-spin h-4 w-4 border-b-2 border-gray-900"></div>
        </div>
      {:else}
        {translation}
      {/if}
    </div>
  {/if}

  <div class="absolute bottom-0 right-0 left-0 bg-white shadow-lg rounded-t-lg p-4 max-h-[40vh] overflow-y-auto">
    <h3 class="text-lg font-semibold mb-4">Seçilen Metinler ve Çevirileri</h3>
    
    <ul class="space-y-4">
      {#each selections as { text, translation }, index}
        <li class="border-b pb-2">
          <div class="flex justify-between items-start">
            <div class="flex-1">
              <p class="font-medium text-gray-900">{text}</p>
              <p class="text-gray-600 mt-1">{translation}</p>
            </div>
            <button
              class="text-red-600 hover:text-red-800"
              on:click={() => removeSelection(index)}
            >
              Sil
            </button>
          </div>
        </li>
      {/each}
    </ul>
  </div>
</div> hacı burada biz epub reader kütüphanesini kullanıyoruz. bunun yerine kitapları html formatında yüklemeye karar verdim. bu sistemi html ile çalışabilecek şekilde güncelle. this is svelteeeeee