---
import { Image } from 'astro:assets';
import Layout from '@layouts/Layout.astro';
import TableOfContents from '../components/blog/TableOfContents.tsx';
import { Icon } from 'astro-icon/components';
import '@assets/css/Post.css'; 
import RelatedPosts from '@components/blog/RelatedPosts.astro';

interface Frontmatter {
  id: string;
  title: string;
  description: string;
  publishDate: string;
  tags: string[];
  image?: string;
  slug: string;
  content?: string;
  isFeatured?: boolean;
  isActive: boolean;  
  coverImage?: string;      
  coverImageAlt?: string;  
}

interface Props {
  frontmatter: Frontmatter;
  slug: string;
}

// Получаем пропсы
const { frontmatter, slug }: Props = Astro.props;

// --- 1. Логика Даты и Заголовка ---
const currentYear = new Date().getFullYear();

// Заменяем {year} на текущий год (например, "Тренды {year}" -> "Тренды 2025")
const dynamicTitle = frontmatter.title.replace('{year}', currentYear.toString());

const formattedDate = new Date(frontmatter.publishDate).toLocaleDateString('ru-RU', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
});

// Данные для соцсетей
const postUrl = Astro.url.href;

// --- 2. Логика Изображения PocketBase ---
// Получаем URL сервера из переменных среды или фоллбэк на локальный
const PB_URL = import.meta.env.PUBLIC_POCKETBASE_URL || 'http://127.0.0.1:8090';

// Используем поле image или coverImage из поста
let imageFilename = frontmatter.image || frontmatter.coverImage;

// Если в посте нет изображения, пробуем найти первое изображение в контенте
if (!imageFilename && frontmatter.content) {
  // Ищем первое изображение в HTML-контенте
  const imgMatch = frontmatter.content.match(/<img[^>]+src="([^"]+)"[^>]*>/i);
  if (imgMatch && imgMatch[1]) {
    const imgSrc = imgMatch[1];
    // Если это URL PocketBase, извлекаем имя файла
    if (imgSrc.includes('/api/files/')) {
      const parts = imgSrc.split('/');
      imageFilename = parts[parts.length - 1];
    }
  }
}

// Формируем полную ссылку: URL / api / files / COLLECTION / ID / FILENAME
const heroImageSrc = imageFilename
  ? `${PB_URL}/api/files/posts/${frontmatter.id}/${imageFilename}`
  : null;

// Alt текст: используем заголовок статьи или coverImageAlt из поста
const heroImageAlt = frontmatter.coverImageAlt || dynamicTitle;
---

<Layout
  title={`${dynamicTitle} | Блог Redi`}
  description={frontmatter.description}
  canonicalLink={`/blog/${slug}`}
>

  <!-- Стрелка возврата -->
  <div class="max-w-5xl mx-auto px-4 mb-6">
    <a href="/blog" 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>

  {/* --- ХЕДЕР СТАТЬИ (Hero Section) --- */}
  <header class="relative max-w-5xl mx-auto md:rounded-2xl overflow-hidden shadow-2xl mb-8 group" id="article-header">

    {/* Фон: Картинка или заливка */}
    {heroImageSrc ? (
      <div class="absolute inset-0">
        <Image
          src={heroImageSrc}
          alt={heroImageAlt}
          width={1030}
          height={560}
          class="w-full h-full object-cover"
          loading="eager"
        />
      </div>
    ) : (
      <div class="absolute inset-0 bg-neutral-800 flex items-center justify-center">
        <svg class="w-16 h-16 text-neutral-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
        </svg>
      </div>
    )}

    {/* Градиенты для читаемости текста */}
    <div class="absolute inset-0 bg-gradient-to-b from-black/40 via-transparent to-black/70 transition-opacity duration-500 ease-in-out group-hover:opacity-0"></div>
    <div class="absolute inset-0 bg-black/40 backdrop-blur-sm transition-all duration-500 ease-in-out group-hover:opacity-0 group-hover:backdrop-blur-none"></div>

    {/* Заголовок по центру */}
    <div class="relative z-10 flex flex-col w-full h-full text-white aspect-[1030/460] p-6 md:p-10 transition-opacity duration-500 ease-in-out group-hover:opacity-0">
      <div class="flex items-center justify-center flex-grow px-4">
        <h1 class="text-2xl font-bold leading-tight tracking-tight text-balance text-center md:text-5xl lg:text-6xl drop-shadow-xl">
          {dynamicTitle}
        </h1>
      </div>
    </div>

    {/* --- ВЫДВИЖНАЯ ПАНЕЛЬ С МЕТА-ДАННЫМИ --- */}
    <div id="meta-panel" class="absolute right-0 bottom-4 z-20 bg-black/80 backdrop-blur-xl rounded-l-2xl px-3 py-2 md:px-6 md:py-3 border border-white/10 transform translate-x-full transition-transform duration-500 shadow-2xl">
      <div class="flex flex-row items-center gap-x-3 md:gap-x-4 text-xs md:text-sm">

        {/* Дата */}
        <div class="flex items-center text-neutral-100">
          <Icon name="calendar" class="h-3.5 w-3.5 md:h-4 md:w-4 mr-1.5 md:mr-2 opacity-80" />
          <span class="font-medium whitespace-nowrap">{formattedDate}</span>
        </div>

        {/* Автор */}
        <div class="flex items-center text-neutral-100">
          <Icon name="user" class="h-3.5 w-3.5 md:h-4 md:w-4 mr-1.5 md:mr-2 opacity-80" />
          <span class="whitespace-nowrap">RediBedi</span>
        </div>

        <div class="border-l border-white/20 h-5 md:h-6"></div>

        {/* Поделиться */}
        <div class="flex items-center gap-x-2 md:gap-x-3">
          <span class="text-neutral-300 whitespace-nowrap hidden sm:inline">Поделиться:</span>
          <div class="flex gap-x-1.5 md:gap-x-2">
            <a
              href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(postUrl)}&text=${encodeURIComponent(dynamicTitle)}`}
              target="_blank"
              rel="noopener noreferrer"
              aria-label="Twitter"
              class="social-share-btn hover:bg-blue-500"
            >
              <Icon name="twitter" class="h-3 w-3 md:h-3.5 md:w-3.5" />
            </a>
            <a
              href={`https://www.linkedin.com/shareArticle?mini=true&url=${encodeURIComponent(postUrl)}&title=${encodeURIComponent(dynamicTitle)}`}
              target="_blank"
              rel="noopener noreferrer"
              aria-label="LinkedIn"
              class="social-share-btn hover:bg-blue-600"
            >
              <Icon name="linkedin" class="h-3 w-3 md:h-3.5 md:w-3.5" />
            </a>
            <a
              href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(postUrl)}`}
              target="_blank"
              rel="noopener noreferrer"
              aria-label="Facebook"
              class="social-share-btn hover:bg-blue-700"
            >
              <Icon name="facebook" class="h-3 w-3 md:h-3.5 md:w-3.5" />
            </a>
          </div>
        </div>
      </div>
    </div>

    {/* Кнопка открытия панели */}
    <button id="toggle-meta" aria-label="Показать информацию" class="absolute bottom-4 right-4 z-30 w-8 h-8 flex items-center justify-center rounded-full bg-black/60 text-white backdrop-blur-md border border-white/20 hover:bg-black/90 transition-all duration-300">
      <Icon name="chevron-left" class="h-4 w-4 transition-transform duration-300" id="toggle-arrow" />
    </button>
  </header>

  {/* --- ОСНОВНОЙ КОНТЕНТ --- */}
  <main class="max-w-5xl px-4 py-1 mx-auto">

    <TableOfContents client:load />

    <article class="w-full max-w-5xl mx-auto mb-20 prose prose-sm md:prose-lg dark:prose-invert prose-headings:font-bold prose-a:text-blue-600 dark:prose-a:text-blue-400 hover:prose-a:text-blue-700 dark:hover:prose-a:text-blue-300 prose-img:rounded-2xl prose-img:shadow-lg">
      <slot />
    </article>

    {/* --- ТЕГИ --- */}
    {frontmatter.tags && frontmatter.tags.length > 0 && (
      <div class="max-w-5xl mx-auto mt-16 mb-16">
        <div class="border-t border-dashed border-neutral-300 dark:border-neutral-700"></div>
        <div class="mt-8">
          <h2 class="text-xl md:text-2xl font-bold mb-6 text-neutral-800 dark:text-neutral-200">Теги статьи</h2>
          <div class="flex flex-wrap items-center gap-3">
            {frontmatter.tags.map((tag) => (
              <a href={`/blog/tags/${tag.toLowerCase()}`} class="rounded-full bg-sky-100 px-4 py-1.5 text-xs font-medium text-sky-700 dark:bg-sky-900/50 dark:text-sky-200 hover:bg-sky-200 dark:hover:bg-sky-800 transition-colors duration-200">
                {tag}
              </a>
            ))}
          </div>
        </div>
      </div>
    )}

    {/* --- ПОХОЖИЕ СТАТЬИ --- */}
    <RelatedPosts currentTags={frontmatter.tags} currentSlug={slug} />

  </main>
</Layout>

<style>
  #meta-panel {
    box-shadow: -5px 0 20px rgba(0, 0, 0, 0.4);
  }
  h1 {
    text-shadow: 0 4px 20px rgba(0, 0, 0, 0.8);
  }
  .social-share-btn {
    @apply flex items-center justify-center w-6 h-6 md:w-7 md:h-7 rounded-full bg-white/10 text-neutral-200 transition-all duration-200;
  }
</style>

<script>
  // Логика для кнопки "i" (показать мета-данные)
  document.addEventListener('DOMContentLoaded', () => {
    const metaPanel = document.getElementById('meta-panel');
    const toggleButton = document.getElementById('toggle-meta');
    const toggleArrow = document.getElementById('toggle-arrow');

    if (!metaPanel || !toggleButton || !toggleArrow) return;

    let isMetaVisible = false;
    let autoHideTimeout: number | null = null;

    const showMetaPanel = () => {
      metaPanel.style.transform = 'translateX(0)';
      toggleArrow.style.transform = 'rotate(180deg)';
      isMetaVisible = true;
      toggleButton.style.opacity = '0';
      toggleButton.style.pointerEvents = 'none';

      if (autoHideTimeout) clearTimeout(autoHideTimeout);
      autoHideTimeout = window.setTimeout(hideMetaPanel, 5000);
    };

    const hideMetaPanel = () => {
      metaPanel.style.transform = 'translateX(100%)';
      toggleArrow.style.transform = 'rotate(0deg)';
      isMetaVisible = false;
      toggleButton.style.opacity = '1';
      toggleButton.style.pointerEvents = 'auto';
    };

    toggleButton.addEventListener('click', () => {
      isMetaVisible ? hideMetaPanel() : showMetaPanel();
    });

    metaPanel.addEventListener('mouseenter', () => {
      if (autoHideTimeout) clearTimeout(autoHideTimeout);
    });

    metaPanel.addEventListener('mouseleave', () => {
      if (isMetaVisible) autoHideTimeout = window.setTimeout(hideMetaPanel, 5000);
    });
  });
</script>