---
import Layout from '@layouts/Layout.astro'
import type { Course } from '@globalInterfaces';
import { decodeHtmlEntities } from '@globalInterfaces';
import { pb } from '@lib/pocketbase';
import { processHtmlContent } from '@lib/processHtmlContent';

const { slug } = Astro.params

// Получаем курс из PocketBase по slug
let courseData: Course | null = null;
let title = 'Курс не найден | Redi - Веб-разработчик';
let description = 'Запрашиваемый курс не найден';

try {
  const record = await pb.collection('courses').getFirstListItem(`slug = "${slug}"`, {
    requestKey: `course_${slug}`
  });

  // Преобразуем данные в нужный формат
  courseData = {
    id: record.id,
    title: record.title,
    slug: record.slug,
    description: record.description,
    price: record.price,
    duration: record.duration,
    level: record.levels,
    tags: record.tags || [],
    thumbnail: record.thumbnail || '',
    content: processHtmlContent(decodeHtmlEntities(record.content || '')) // Декодируем HTML-сущности и обрабатываем контент
  };

  title = `${courseData.title} | Redi - Веб-разработчик`;
  description = courseData.description;
} catch (error) {
  console.error('Ошибка при получении курса:', error);
}
---

<Layout title={title} description={description} canonicalLink={`/courses/${slug}`}>
  {courseData ? (
    <main class="max-w-5xl mx-auto px-4 py-1 space-y-8">
      <div>
        {/* Стрелка возврата */}
        <div class="mb-6">
          <a href="/courses" class="inline-flex items-center text-neutral-600 hover:text-indigo-600 dark:text-neutral-400 dark:hover:text-indigo-400 text-sm font-medium transition-colors hover:underline hover:underline-offset-4 hover:decoration-indigo-600 dark:hover:decoration-indigo-400">
            ← Вернуться к курсам
          </a>
        </div>

        {/* Изображение курса */}
        {courseData.thumbnail && (
          <div class="mb-8">
            <img
              src={`${import.meta.env.PUBLIC_POCKETBASE_URL}/api/files/courses/${courseData.id}/${courseData.thumbnail}`}
              alt={courseData.title}
              class="w-full h-auto rounded-2xl shadow-lg object-cover max-w-5xl mx-auto"
            />
          </div>
        )}

        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6 gap-4">
          <h1 class="text-4xl font-bold text-neutral-900 dark:text-neutral-100">{courseData.title}</h1>
          <div class="flex items-center gap-4">
            <span class="text-3xl font-bold text-indigo-600 dark:text-indigo-400">{courseData.price} ₽</span>
            <button class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-6 rounded-lg transition-colors duration-300">
              Купить курс
            </button>
          </div>
        </div>

        <div class="flex flex-wrap items-center gap-4 mb-8">
          <span class="font-medium uppercase tracking-wide text-xs text-neutral-500 bg-neutral-200 dark:bg-neutral-800 px-2 py-1 rounded">
            {courseData.level}
          </span>
          <div class="flex items-center gap-2 text-sm text-neutral-500">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-4 h-4 text-neutral-400">
              <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25zM12.75 6a.75.75 0 00-1.5 0v6c0 .414.336.75.75.75h4.5a.75.75 0 000-1.5h-3.75V6z" clip-rule="evenodd" />
            </svg>
            <span class="font-medium">{courseData.duration}</span>
          </div>
        </div>

        <div class="prose prose-neutral dark:prose-invert max-w-none mb-12 bg-neutral-50 dark:bg-neutral-900/30 p-6 rounded-xl">
          <div set:html={courseData.content} />
        </div>

        {courseData.tags && courseData.tags.length > 0 && (
          <div class="pt-4 border-t border-neutral-200 dark:border-neutral-800 flex flex-wrap gap-2">
            {courseData.tags.map((tag) => (
              <span class="text-sm text-neutral-500 bg-white dark:bg-neutral-950 px-3 py-1 rounded border border-neutral-200 dark:border-neutral-800">
                #{tag}
              </span>
            ))}
          </div>
        )}
      </div>
    </main>
  ) : (
    <main class="max-w-5xl mx-auto px-4 py-1 space-y-8">
      <div class="text-center">
        <h1 class="text-4xl font-bold text-neutral-900 dark:text-neutral-100 mb-4">Курс не найден</h1>
        <p class="text-xl text-neutral-600 dark:text-neutral-400">
          К сожалению, запрашиваемый курс не существует
        </p>
      </div>
    </main>
  )}
</Layout>