﻿import React from 'react';
import { Head, Link } from '@inertiajs/react';
import { useLocalizedRoutes } from '@/hooks/useLocalizedRoutes';
import { useTranslation } from 'react-i18next';
import MarketingLayout from '@/layouts/mainWebsite';

interface Props {
  posts: {
    data: any[];
    links: any[];
    current_page: number;
    last_page: number;
  };
}

const Blog: React.FC<Props> = ({ posts }) => {
  const { localizedPath } = useLocalizedRoutes();
  const { t } = useTranslation('marketing');

  const resolvePaginationHref = React.useCallback(
    (raw?: string | null) => {
      if (!raw) {
        return null;
      }

      try {
        const parsed = new URL(
          raw,
          typeof window !== 'undefined' ? window.location.origin : 'http://localhost'
        );

        const normalized = `${parsed.pathname}${parsed.search}`;
        return localizedPath(normalized);
      } catch (error) {
        console.warn('[Marketing Blog] Fallback resolving pagination link', { raw, error });
        return localizedPath(raw);
      }
    },
    [localizedPath]
  );

  const renderPagination = () => {
    if (!posts.links || posts.links.length <= 3) return null;

    return (
      <div className="mt-12 text-center">
        <div className="flex justify-center space-x-2">
          {posts.links.map((link, index) => {
            const href = resolvePaginationHref(link.url);

            const baseClasses = `px-3 py-2 rounded ${
              link.active
                ? 'bg-[#FFB6C1] text-white'
                : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
            }`;

            if (!href) {
              return (
                <span
                  key={index}
                  className={`${baseClasses} cursor-default`}
                  dangerouslySetInnerHTML={{ __html: link.label }}
                />
              );
            }

            return (
              <Link
                key={index}
                href={href}
                className={baseClasses}
                dangerouslySetInnerHTML={{ __html: link.label }}
              />
            );
          })}
        </div>
      </div>
    );
  };

  return (
    <MarketingLayout title={t('blog.title')}>
      <Head title={t('blog.title')} />
      {/* Hero Section */}
      <section className="bg-aurora-enhanced text-gray-900 dark:text-gray-100 py-20 px-4">
        <div className="container mx-auto text-center">
          <h1 className="text-4xl md:text-6xl font-bold mb-4 font-display">{t('blog.hero_title')}</h1>
          <p className="text-xl md:text-2xl mb-8 max-w-3xl mx-auto font-sans-marketing">{t('blog.hero_description')}</p>
          <Link href="#posts" className="bg-white dark:bg-gray-800 text-[#FFB6C1] px-8 py-4 rounded-full font-semibold text-lg font-sans-marketing hover:bg-gray-100 dark:hover:bg-gray-700 transition">
            {t('blog.hero_cta')}
          </Link>
        </div>
      </section>

      {/* Posts Section */}
      <section id="posts" className="py-20 px-4 bg-white dark:bg-gray-900">
        <div className="container mx-auto max-w-4xl">
          <h2 className="text-3xl font-bold text-center mb-12 font-display text-gray-900 dark:text-gray-100">{t('blog.posts_title')}</h2>
          {posts.data.length > 0 ? (
            <>
              <div className="grid md:grid-cols-2 gap-8">
                {posts.data.map((post) => (
                  <div key={post.id} className="bg-gray-50 dark:bg-gray-800 p-6 rounded-lg">
                    {post.featured_image && (
                      <img
                        src={post.featured_image}
                        alt={post.title}
                        className="w-full h-48 object-cover rounded mb-4"
                      />
                    )}
                    <h3 className="text-xl font-semibold mb-2 font-sans-marketing text-gray-900 dark:text-gray-100">
                      <Link href={`${localizedPath(`/blog/${post.slug}`)}`} className="hover:text-[#FFB6C1]">
                        {post.title}
                      </Link>
                    </h3>
                    <p className="mb-4 text-gray-700 dark:text-gray-300 font-serif-custom">{post.excerpt}</p>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mb-4 font-sans-marketing">
                      {t('blog.by')} {post.author?.name || t('blog.team')} | {t('blog.published_at')} {post.published_at}
                    </p>
                    <Link
                      href={`${localizedPath(`/blog/${post.slug}`)}`}
                      className="text-[#FFB6C1] font-semibold font-sans-marketing hover:underline"
                    >
                      {t('blog.read_more')}
                    </Link>
                  </div>
                ))}
              </div>
              {renderPagination()}
            </>
          ) : (
            <p className="text-center text-gray-600 dark:text-gray-400 font-serif-custom">{t('blog.empty')}</p>
          )}
        </div>
      </section>
    </MarketingLayout>
  );
};

export default Blog;