<script>
  import { browser } from '$app/environment';
  import { onMount } from 'svelte';
  import { base } from '$app/paths';
  import { translateText, translateWord } from '$lib/translation';
  import { marked } from 'marked';

  let content = '';
  let contentElement;
  let translation = '';
  let isLoading = false;
  let location = browser && localStorage.getItem("book-progress") || null;
  let error = null;
  let popoverVisible = false;
  let popoverStyle = '';
  let selectedText = '';
  let isArabic = true; // Varsayılan olarak true yapıldı
  let currentSelection = null;
  const translationCache = new Map();

  marked.setOptions({
    breaks: true,
    gfm: true,
    headerIds: true,
  });

  const handleClickOutside = (event) => {
    if (!event.target.closest('.custom-popover') && !event.target.closest('.highlighted-text')) {
      popoverVisible = false;
      if (currentSelection) {
        const parent = currentSelection.parentElement;
        if (parent && parent.className === 'highlighted-text') {
          parent.replaceWith(...parent.childNodes);
        }
        currentSelection = null;
      }
    }
  };

  const cleanText = (text) => {
    return text
      .replace(/&[^;]+;/g, '')
      .replace(/[\u200B-\u200D\uFEFF]/g, '');
  };

  async function loadMarkdownContent(url) {
    try {
      const response = await fetch(url);
      if (!response.ok) throw new Error('Markdown dosyası yüklenemedi');
      const markdownText = await response.text();
      content = marked(markdownText);
    } catch (err) {
      console.error('Markdown yükleme hatası:', err);
      error = err.message;
    }
  }

  onMount(() => {
    try {
      const params = new URLSearchParams(window.location.search);
      const url = params.get('url');

      if (!url) {
        throw new Error('URL parametresi bulunamadı');
      }

      const decodedUrl = decodeURIComponent(url);
      const fullUrl = !decodedUrl.startsWith('http') 
        ? `${base}${decodedUrl.startsWith('/') ? '' : '/'}${decodedUrl}`
        : decodedUrl;

      loadMarkdownContent(fullUrl);
    } catch (err) {
      console.error('Kitap yüklenemedi:', err);
      error = err.message;
    }

    document.addEventListener('click', handleClickOutside);

    if (location && contentElement) {
      window.scrollTo(0, parseInt(location));
    }

    if (browser) {
      let scrollTimeout;
      window.addEventListener('scroll', () => {
        clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(() => {
          localStorage.setItem("book-progress", window.scrollY.toString());
        }, 100);
      });
    }

    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  });

  async function handleMouseUp(event) {
    if (!browser) return;
    
    const selection = window.getSelection();
    const selected = cleanText(selection.toString().trim());

    if (!selected) {
      return;
    }

    if (selected.length > 200) {
      alert('Lütfen 200 karakterden kısa bir metin seçin.');
      return;
    }

    try {
      isLoading = true;

      const range = selection.getRangeAt(0);
      const rect = range.getBoundingClientRect();
      
      // Calculate position relative to viewport
      const popoverLeft = rect.left + (rect.width / 2);
      const popoverTop = rect.top - 60 + window.scrollY;

      popoverStyle = `
        position: absolute;
        left: ${popoverLeft}px;
        top: ${popoverTop}px;
        transform: translateX(-50%);
        z-index: 1000;
      `;

      // Highlight selected text before showing popover
      const span = document.createElement('span');
      span.className = 'highlighted-text';
      
      try {
        range.surroundContents(span);
        currentSelection = span;
      } catch (e) {
        const contents = range.cloneContents();
        span.appendChild(contents);
        range.deleteContents();
        range.insertNode(span);
        currentSelection = span;
      }

      selectedText = selected;
      popoverVisible = true;

      if (translationCache.has(selected)) {
        translation = translationCache.get(selected);
        isLoading = false;
      } else {
        const parentElement = range.commonAncestorContainer.parentElement;
        const context = parentElement ? parentElement.textContent : '';
        const textIndex = context.indexOf(selected);
        const surroundingContext = context.substring(
          Math.max(0, textIndex - 30),
          Math.min(context.length, textIndex + selected.length + 30)
        );

        const isSingleWord = selected.split(/\s+/).length === 1;
        const translationResult = isSingleWord
          ? await translateWord(selected, surroundingContext)
          : await translateText(selected);

        translation = marked.parseInline(translationResult);
        translationCache.set(selected, translation);
        isLoading = false;
      }

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

  const closePopover = () => {
    popoverVisible = false;
    if (currentSelection) {
      const parent = currentSelection.parentElement;
      if (parent && parent.className === 'highlighted-text') {
        parent.replaceWith(...parent.childNodes);
      }
      currentSelection = null;
    }
  };

  const goBack = () => {
    window.location.href = `${base}/books`;
  };
</script>

<style>
  .markdown-content {
    font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    line-height: 1.8;
    color: #374151;
    max-width: 65ch;
    margin: 0 auto;
    padding: 1rem;
    direction: rtl;
    text-align: right;
  }

  .markdown-content :global(h1),
  .markdown-content :global(h2),
  .markdown-content :global(h3),
  .markdown-content :global(h4),
  .markdown-content :global(h5),
  .markdown-content :global(h6) {
    direction: rtl;
    text-align: right;
  }

  .markdown-content :global(h1) {
    font-size: 2em;
    margin-top: 1.5em;
    margin-bottom: 0.5em;
    font-weight: 700;
    color: #111827;
  }

  .markdown-content :global(h2) {
    font-size: 1.5em;
    margin-top: 1.3em;
    margin-bottom: 0.4em;
    font-weight: 600;
    color: #1F2937;
  }

  .markdown-content :global(h3) {
    font-size: 1.25em;
    margin-top: 1.2em;
    margin-bottom: 0.3em;
    font-weight: 600;
    color: #374151;
  }

  .markdown-content :global(p) {
    margin-bottom: 1.2em;
    line-height: 1.8;
  }

  .markdown-content :global(ul), 
  .markdown-content :global(ol) {
    margin-bottom: 1.2em;
    padding-right: 1.5em;
    padding-left: 0;
    direction: rtl;
  }

  .markdown-content :global(li) {
    margin-bottom: 0.3em;
  }

  .markdown-content :global(blockquote) {
    border-right: 4px solid #E5E7EB;
    border-left: none;
    padding-right: 1em;
    padding-left: 0;
    margin: 1.5em 0;
    color: #4B5563;
  }

  .markdown-content :global(code) {
    background-color: #F3F4F6;
    padding: 0.2em 0.4em;
    border-radius: 0.25em;
    font-size: 0.875em;
    color: #DC2626;
    direction: ltr;
    display: inline-block;
  }

  .markdown-content :global(pre) {
    background-color: #F3F4F6;
    padding: 1em;
    border-radius: 0.5em;
    overflow-x: auto;
    margin: 1.5em 0;
    direction: ltr;
  }

  .markdown-content :global(pre code) {
    background-color: transparent;
    padding: 0;
    color: #374151;
  }

  .markdown-content :global(a) {
    color: #2563EB;
    text-decoration: underline;
  }

  .markdown-content :global(a:hover) {
    color: #1D4ED8;
  }

  .markdown-content :global(hr) {
    border: 0;
    border-top: 1px solid #E5E7EB;
    margin: 2em 0;
  }

  ::selection {
    background: #FDE68A;
    color: #1F2937;
  }

  .highlighted-text {
    background-color: #FDE68A;
    border-radius: 2px;
    padding: 0 2px;
  }

  .custom-popover {
    background: white;
    border: 1px solid #E5E7EB;
    border-radius: 0.75rem;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
    padding: 1rem;
    width: 280px;
    position: absolute;
    transition: opacity 0.2s ease;
    max-width: 90vw;
  }

  .popover-close {
    position: absolute;
    top: 0.5rem;
    right: 0.5rem;
    background: transparent;
    border: none;
    font-size: 1.2rem;
    cursor: pointer;
    color: #6B7280;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background-color 0.2s ease;
  }

  .popover-close:hover {
    background-color: #F3F4F6;
    color: #374151;
  }

  .fade-in {
    animation: fadeIn 0.2s ease-out;
  }

  @keyframes fadeIn {
    from { 
      opacity: 0;
      transform: translateY(-5px) translateX(-50%);
    }
    to { 
      opacity: 1;
      transform: translateY(0) translateX(-50%);
    }
  }

  .spinner {
    border: 3px solid #F3F4F6;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    border-top-color: #6366F1;
    animation: spin 0.8s linear infinite;
  }

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

  .header {
    position: sticky;
    top: 0;
    z-index: 50;
    backdrop-filter: blur(8px);
  }

  .back-button {
    font-size: 1.5rem;
    line-height: 1;
  }
</style>

<div class="min-h-screen bg-gray-50">
  <!-- Header -->
  <header class="header bg-white/80 border-b border-gray-200">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="flex items-center justify-between h-16">
        <button 
          on:click={goBack}
          class="inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
        >
          <span class="back-button mr-1">&lt;</span>
          Kitaplara Dön
        </button>
      </div>
    </div>
  </header>

  {#if error}
    <div class="p-4 bg-red-50 border border-red-200 rounded-md text-red-700 max-w-7xl mx-auto mt-4">
      Hata: {error}
    </div>
  {/if}

  <!-- Markdown Content -->
  <div 
    bind:this={contentElement}
    class="markdown-content py-8"
    on:mouseup={handleMouseUp}
  >
    {@html content}
  </div>

  {#if popoverVisible}
    <div 
      class="custom-popover fade-in"
      style={popoverStyle}
    >
      <button class="popover-close" on:click={closePopover}>&times;</button>
      {#if isLoading}
        <div class="flex justify-center items-center py-4">
          <div class="spinner"></div>
        </div>
      {:else}
        <div class="text-gray-700 prose prose-sm max-w-none">{@html translation}</div>
      {/if}
    </div>
  {/if}
</div> buradaki popoverda bir sıkıntı var. bir metni seçtiğim anda popoverın gelmesini istiyorum. tıklamak falan gerekiyor şu anki kodda. bunu ayarla. bir metin seçildiği anda popover gözüksün. birde popover metnin tam üstüne geliyor olmuyor. ok işaretiyle seçilen metni gösterse süpper olur.