---
import Layout from '@layouts/Layout.astro';
import { SITE_URL } from '@constants';
import BlogCard from '@components/blog/BlogCard.astro';
import SearchModal from '@components/base/SearchModal.astro';
import { getPosts, getPostImageUrl } from '@lib/pb';

const url = new URL(Astro.request.url);
const searchQuery = url.searchParams.get('q') || '';

const { posts: searchResults } = searchQuery 
  ? await getPosts({ perPage: 20, search: searchQuery })
  : { posts: [], total: 0, page: 1, totalPages: 1 };

const breadcrumbsItems = [
	{ label: 'Главная', href: '/' },
	{ label: 'Блог', href: '/blog' },
	{ label: searchQuery ? `Поиск: "${searchQuery}"` : 'Поиск' }
];

const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('ru-RU', {
    day: 'numeric',
    month: 'long',
    year: 'numeric'
  });
};
---

<Layout
	title={`${searchQuery ? 'Результаты поиска: ' + searchQuery : 'Поиск статей'} — автоюрист в Сургуте`}
	description={`Результаты поиска статей по запросу "${searchQuery}"`}
	canonicalLink={`${SITE_URL}/blog/search?q=${encodeURIComponent(searchQuery)}`}
	breadcrumbs={breadcrumbsItems}
>
	<!-- Hero-секция поиска -->
	<section class="search-hero">
		<div class="site-container">
			<div class="search-hero-content">
				<h1 class="search-title">
					{searchQuery ? `Результаты поиска` : 'Поиск статей'}
				</h1>

				{searchQuery && (
					<div class="search-info">
						<p class="search-query-text">
							По запросу: <span class="query-highlight">"{searchQuery}"</span>
						</p>
						<p class="search-count">
							{searchResults.length === 0
								? 'Ничего не найдено'
								: `Найдено статей: ${searchResults.length}`}
						</p>
					</div>
				)}

				<button class="open-search-btn" id="open-search-btn" data-modal-target="search-modal">
					<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<circle cx="11" cy="11" r="8"></circle>
						<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
					</svg>
					Изменить запрос
				</button>
			</div>
		</div>
	</section>

	<!-- Результаты поиска -->
	{searchQuery && searchResults.length > 0 ? (
		<section class="results-section">
			<div class="site-container">
				<div class="results-grid">
					{searchResults.map((post: any) => (
						<BlogCard
							title={post.title}
							description={post.description}
							category={post.category}
							categoryColor={post.categoryColor}
							date={formatDate(post.date)}
							readTime={post.readTime}
							readmeTime={post.readmeTime}
							image={getPostImageUrl(post)}
							slug={`/blog/${post.slug}`}
						/>
					))}
				</div>
			</div>
		</section>
	) : searchQuery ? (
		<section class="no-results">
			<div class="site-container">
				<div class="no-results-content">
					<svg class="no-results-icon" width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
						<circle cx="11" cy="11" r="8"></circle>
						<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
						<line x1="8" y1="8" x2="14" y2="14"></line>
						<line x1="14" y1="8" x2="8" y2="14"></line>
					</svg>
					<h2 class="no-results-title">По вашему запросу ничего не найдено</h2>
					<p class="no-results-text">
						Попробуйте изменить запрос или посмотрите все статьи в блоге
					</p>
					<a href="/blog" class="back-to-blog-btn">
						<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
							<line x1="19" y1="12" x2="5" y2="12"></line>
							<polyline points="12 19 5 12 12 5"></polyline>
						</svg>
						Вернуться в блог
					</a>
				</div>
			</div>
		</section>
	) : (
		<section class="no-results">
			<div class="site-container">
				<div class="no-results-content">
					<p class="no-results-text">Введите запрос для поиска статей</p>
				</div>
			</div>
		</section>
	)}
</Layout>

<SearchModal />

<script>
  (function() {
    const btn = document.getElementById('open-search-btn');

    btn?.addEventListener('click', () => {
      window.dispatchEvent(new CustomEvent('open-modal', {
        detail: 'search-modal'
      }));
    });

    document.addEventListener('DOMContentLoaded', () => {
      const urlParams = new URLSearchParams(window.location.search);
      const query = urlParams.get('q');

      if (!query && btn) {
        setTimeout(() => {
          window.dispatchEvent(new CustomEvent('open-modal', {
            detail: 'search-modal'
          }));
        }, 300);
      }
    });
  })();
</script>

<style>
	.search-hero {
		padding: 6rem 0 3rem;
		background: linear-gradient(135deg, #0a2540 0%, #1e3a5f 100%);
		position: relative;
		overflow: hidden;
	}

	.search-hero::before {
		content: '';
		position: absolute;
		top: -30%;
		right: -5%;
		width: 500px;
		height: 500px;
		background: radial-gradient(circle, rgba(212, 175, 55, 0.08) 0%, transparent 70%);
		border-radius: 50%;
	}

	.search-hero-content {
		position: relative;
		z-index: 1;
		text-align: center;
		max-width: 700px;
		margin: 0 auto;
	}

	.search-title {
		font-size: clamp(2rem, 4vw, 3rem);
		font-weight: 800;
		color: #ffffff;
		margin: 0 0 1.5rem;
		letter-spacing: -0.02em;
	}

	.search-info {
		margin-bottom: 2rem;
	}

	.search-query-text {
		color: rgba(255, 255, 255, 0.8);
		font-size: 1.1rem;
		margin: 0 0 0.5rem;
	}

	.query-highlight {
		color: #eac26e;
		font-weight: 700;
	}

	.search-count {
		color: rgba(255, 255, 255, 0.6);
		font-size: 0.95rem;
		margin: 0;
	}

	.open-search-btn {
		background: linear-gradient(135deg, #d4af37 0%, #eac26e 100%);
		color: #1e293b;
		border: none;
		padding: 0.875rem 2rem;
		border-radius: 0.75rem;
		font-size: 1rem;
		font-weight: 700;
		cursor: pointer;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		box-shadow: 0 4px 15px rgba(212, 175, 55, 0.3);
		display: inline-flex;
		align-items: center;
		gap: 0.5rem;
	}

	.open-search-btn:hover {
		transform: translateY(-3px);
		box-shadow: 0 8px 25px rgba(212, 175, 55, 0.4);
	}

	.open-search-btn:active {
		transform: translateY(0);
	}

	.results-section {
		padding: 3rem 0;
		background: #f8fafc;
	}

	.results-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 2rem;
	}

	.no-results {
		padding: 5rem 0;
		background: #f8fafc;
	}

	.no-results-content {
		text-align: center;
		max-width: 600px;
		margin: 0 auto;
	}

	.no-results-icon {
		color: #d1d5db;
		margin-bottom: 1.5rem;
	}

	.no-results-title {
		font-size: 1.75rem;
		font-weight: 700;
		color: #1e3050;
		margin: 0 0 1rem;
	}

	.no-results-text {
		color: #535e6c;
		font-size: 1.1rem;
		line-height: 1.6;
		margin: 0 0 2rem;
	}

	.back-to-blog-btn {
		background: linear-gradient(135deg, #0a2540 0%, #1e3a5f 100%);
		color: #ffffff;
		border: none;
		padding: 0.875rem 2rem;
		border-radius: 0.75rem;
		font-size: 1rem;
		font-weight: 700;
		cursor: pointer;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		text-decoration: none;
		display: inline-flex;
		align-items: center;
		gap: 0.5rem;
		box-shadow: 0 4px 15px rgba(10, 37, 64, 0.3);
	}

	.back-to-blog-btn:hover {
		transform: translateY(-3px);
		box-shadow: 0 8px 25px rgba(10, 37, 64, 0.4);
	}

	/* ===== RESPONSIVE ===== */
	@media (max-width: 1024px) {
		.results-grid {
			grid-template-columns: repeat(2, 1fr);
		}
	}

	@media (max-width: 768px) {
		.search-hero {
			padding: 5rem 0 2.5rem;
		}

		.results-grid {
			grid-template-columns: 1fr;
			gap: 1.5rem;
		}

		.search-title {
			font-size: 2rem;
		}

		.no-results {
			padding: 3rem 0;
		}

		.no-results-title {
			font-size: 1.5rem;
		}
	}
</style>