
import React, { useState, useEffect } from 'react';
import { Helmet } from 'react-helmet';
import { motion } from 'framer-motion';
import { Search } from 'lucide-react';
import BlogCard from '@/components/BlogCard';
import { blogPosts } from '@/lib/data';
import { useLanguage } from '@/contexts/LanguageContext';

const BlogPage = () => {
  const { t } = useLanguage();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');

  useEffect(() => {
    // Debug logging to verify data loading
    console.log("BlogPage mounted. Loaded blog posts:", blogPosts);
    if (!blogPosts || blogPosts.length === 0) {
      console.warn("No blog posts found in @/lib/data.js!");
    }
  }, []);

  // Extract unique categories from data
  const categoryKeys = ['all', ...new Set(blogPosts.map(post => post.category))];

  // Filter posts
  const filteredPosts = blogPosts.filter(post => {
    const title = (post.title || t(`blog.posts.${post.id}.title`)).toLowerCase();
    const excerpt = (post.excerpt || t(`blog.posts.${post.id}.excerpt`)).toLowerCase();
    
    const matchesSearch = title.includes(searchTerm.toLowerCase()) || 
                          excerpt.includes(searchTerm.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || post.category === selectedCategory;
    
    return matchesSearch && matchesCategory;
  });

  return (
    <>
      <Helmet>
        <title>{t('meta.blog.title')}</title>
        <meta name="description" content={t('meta.blog.description')} />
      </Helmet>

      <div className="min-h-screen pt-20 bg-charcoal" role="main" aria-label="Blog">
        {/* Header */}
        <section className="bg-gradient-to-br from-charcoal to-teal text-white py-16">
          <div className="container mx-auto px-4">
            <motion.div 
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
              className="max-w-4xl mx-auto text-center"
            >
              <h1 className="mb-6">{t('blog.hero.title')}</h1>
              <p className="text-xl text-silver/90 leading-relaxed max-w-2xl mx-auto">
                {t('blog.hero.subtitle')}
              </p>
            </motion.div>
          </div>
        </section>

        {/* Filter & Search */}
        <section className="py-6 bg-charcoal border-b border-silver/10 sticky top-[72px] z-40 backdrop-blur-md bg-charcoal/90">
          <div className="container mx-auto px-4">
            <div className="flex flex-col md:flex-row justify-between items-center gap-6">
              
              {/* Categories */}
              <div className="flex flex-wrap gap-2 justify-center md:justify-start">
                {categoryKeys.map(catKey => (
                  <button
                    key={catKey}
                    onClick={() => setSelectedCategory(catKey)}
                    className={`px-4 py-2 rounded-full text-sm font-medium transition-all duration-300 border ${
                      selectedCategory === catKey
                        ? 'bg-deepGreen text-white border-deepGreen shadow-lg shadow-deepGreen/20'
                        : 'bg-transparent text-silver border-silver/20 hover:border-silver/50 hover:text-white'
                    }`}
                  >
                    {t(`blog.categories.${catKey}`) || catKey}
                  </button>
                ))}
              </div>

              {/* Search */}
              <div className="relative w-full md:w-72">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-silver/50 w-4 h-4" />
                <input
                  type="text"
                  placeholder={t('blog.search.placeholder')}
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 bg-charcoal-light border border-silver/20 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-deepGreen focus:border-transparent transition-all"
                />
              </div>
            </div>
          </div>
        </section>

        {/* Blog Grid */}
        <section className="py-16 bg-charcoal">
          <div className="container mx-auto px-4">
            {filteredPosts.length > 0 ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {filteredPosts.map((post) => (
                  <BlogCard key={post.id} post={post} />
                ))}
              </div>
            ) : (
              <div className="text-center py-20">
                <p className="text-xl text-silver/60">{t('blog.search.noResults')}</p>
                <button 
                  onClick={() => {setSearchTerm(''); setSelectedCategory('all');}}
                  className="mt-4 text-deepGreen hover:text-deepGreen-light transition-colors font-medium hover:underline"
                >
                  {t('blog.search.filterReset')}
                </button>
              </div>
            )}
          </div>
        </section>
      </div>
    </>
  );
};

export default BlogPage;
