'use client';

import React, { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import { blogPosts as localPosts, blogCategories as localCategories } from '@/data/blog';
import { useLanguage } from '@/context/LanguageContext';

interface Post {
  id: number | string;
  title: string;
  slug: string;
  excerpt: string | null;
  category: string;
  author: string | null;
  date?: string;
  createdAt?: string;
  image: string | null;
}

interface Category {
  id: number | string;
  name: string;
  slug?: string;
}

export default function BlogPage() {
  const [selectedCategory, setSelectedCategory] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const { t } = useLanguage();
  const sliderRef = useRef<HTMLDivElement>(null);
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';

  const [posts, setPosts] = useState<Post[]>(localPosts as any);
  const [categories, setCategories] = useState<Category[]>(localCategories as any);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [articlesRes, catsRes] = await Promise.all([
          fetch(`${apiUrl}/api/articles`),
          fetch(`${apiUrl}/api/categories`),
        ]);
        if (articlesRes.ok) {
          const data = await articlesRes.json();
          if (Array.isArray(data) && data.length > 0) setPosts(data);
        }
        if (catsRes.ok) {
          const data = await catsRes.json();
          if (Array.isArray(data) && data.length > 0) setCategories(data);
        }
      } catch (e) {
        // keep local fallback
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [apiUrl]);

  const stripHtml = (html: string | null) => (html || '').replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').trim();
  // Category identifier: API uses slug, local data uses id
  const catKey = (c: Category) => (c.slug || String(c.id));
  const catName = (key: string) => categories.find(c => catKey(c) === key)?.name || key;
  const postDate = (p: Post) => p.date || p.createdAt || '';
  // Real image if it's a path/URL; emoji fallback otherwise
  const isRealImage = (img: string | null) => !!img && (img.startsWith('/') || img.startsWith('http'));
  const imgSrc = (img: string | null) => (img && img.startsWith('http') ? img : `${apiUrl}${img}`);

  const filteredPosts = posts.filter((post) => {
    const matchCategory = !selectedCategory || post.category === selectedCategory;
    const matchSearch = post.title.toLowerCase().includes(searchQuery.toLowerCase()) || stripHtml(post.excerpt).toLowerCase().includes(searchQuery.toLowerCase());
    return matchCategory && matchSearch;
  });

  const featuredPost = posts[0];
  const otherPosts = filteredPosts.filter((p) => p.id !== featuredPost?.id);
  const recentPosts = [...posts].sort((a, b) => new Date(postDate(b)).getTime() - new Date(postDate(a)).getTime()).slice(0, 5);

  const scrollSlider = (direction: 'left' | 'right') => {
    if (sliderRef.current) {
      const scrollAmount = 320;
      sliderRef.current.scrollBy({ left: direction === 'left' ? -scrollAmount : scrollAmount, behavior: 'smooth' });
    }
  };

  const renderImage = (img: string | null, textSize: string) => (
    isRealImage(img)
      ? <img src={imgSrc(img)} alt="" className="w-full h-full object-cover" />
      : <div className={textSize}>{img || '✨'}</div>
  );

  return (
    <main className="min-h-screen bg-ivory">
      <Navbar />
      <section className="relative py-16 md:py-24 bg-espresso overflow-hidden">
        <div className="container-custom text-center text-white relative z-10">
          <h1 className="font-cormorant text-4xl md:text-6xl font-bold mb-4 uppercase text-white">{t('blog.page.title')}</h1>
          <p className="text-ivory/80 max-w-2xl mx-auto">{t('blog.page.subtitle')}</p>
          <nav className="mt-4 text-xs tracking-widest uppercase text-white">
            <Link href="/" className="hover:text-gold transition text-white">{t('breadcrumb.home')}</Link><span className="mx-2 text-white">/</span><span className="text-white/60">{t('breadcrumb.blog')}</span>
          </nav>
        </div>
      </section>

      {/* Featured Article */}
      {!selectedCategory && !searchQuery && featuredPost && (
        <section className="py-16 pb-8">
          <div className="container-custom">
            <div className="card bg-white overflow-hidden mb-12 hover:shadow-lg transition-all duration-300">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-0">
                <div className="bg-blush h-64 md:h-auto flex items-center justify-center overflow-hidden">{renderImage(featuredPost.image, 'text-8xl')}</div>
                <div className="p-6 md:p-8 flex flex-col justify-center">
                  <span className="inline-block px-3 py-1 bg-gold text-white text-xs font-bold rounded-full w-fit mb-3">📌 {t('blog.featured')}</span>
                  <span className="inline-block px-3 py-1 bg-blush text-gold text-xs font-bold rounded-full w-fit mb-4">{catName(featuredPost.category)}</span>
                  <h2 className="font-cormorant text-2xl md:text-3xl font-bold text-espresso mb-4">{featuredPost.title}</h2>
                  <p className="text-grey-dark mb-4">{stripHtml(featuredPost.excerpt)}</p>
                  <div className="flex items-center gap-4 text-xs text-grey mb-6">
                    <span>📅 {postDate(featuredPost) ? new Date(postDate(featuredPost)).toLocaleDateString('id-ID') : ''}</span>
                    <span>✍️ {featuredPost.author}</span>
                  </div>
                  <Link href={`/blog/${featuredPost.slug}`} className="btn-primary w-fit">{t('general.read-more')}</Link>
                </div>
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Artikel Terbaru - Slider */}
      {!selectedCategory && !searchQuery && recentPosts.length > 0 && (
        <section className="pb-8">
          <div className="container-custom">
            <div className="flex items-center justify-between mb-6">
              <h2 className="font-cormorant text-2xl font-bold text-espresso">📰 Artikel Terbaru</h2>
              <div className="flex gap-2">
                <button onClick={() => scrollSlider('left')} className="w-9 h-9 rounded-full bg-blush flex items-center justify-center hover:bg-gold hover:text-white transition text-espresso">
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7"/></svg>
                </button>
                <button onClick={() => scrollSlider('right')} className="w-9 h-9 rounded-full bg-blush flex items-center justify-center hover:bg-gold hover:text-white transition text-espresso">
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7"/></svg>
                </button>
              </div>
            </div>
            <div ref={sliderRef} className="flex gap-6 overflow-x-auto scrollbar-hide pb-4 -mx-4 px-4 snap-x snap-mandatory">
              {recentPosts.map((post) => (
                <Link key={post.id} href={`/blog/${post.slug}`} className="min-w-[280px] md:min-w-[300px] snap-start card bg-white overflow-hidden hover:shadow-lg transition-all duration-300 block flex-shrink-0">
                  <div className="h-40 bg-blush flex items-center justify-center text-5xl overflow-hidden">{renderImage(post.image, 'text-5xl')}</div>
                  <div className="p-5">
                    <span className="inline-block px-2 py-1 bg-blush text-gold text-xs font-bold rounded mb-3">{catName(post.category)}</span>
                    <h3 className="font-cormorant text-lg font-semibold text-espresso mb-2 line-clamp-2">{post.title}</h3>
                    <p className="text-xs text-grey-dark mb-3 line-clamp-2">{stripHtml(post.excerpt)}</p>
                    <div className="flex items-center justify-between text-xs text-grey">
                      <span>✍️ {post.author}</span>
                      <span>📅 {postDate(post) ? new Date(postDate(post)).toLocaleDateString('id-ID') : ''}</span>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Filter Bar */}
      <section className="sticky top-16 z-40 bg-ivory border-b border-blush py-6">
        <div className="container-custom">
          <div className="mb-4"><input type="text" placeholder={t('blog.search.placeholder')} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="input-field w-full" /></div>
          <div className="flex flex-wrap gap-2">
            <button onClick={() => setSelectedCategory('')} className={`px-4 py-2 rounded-full text-xs uppercase tracking-wider font-semibold transition ${!selectedCategory ? 'bg-gold text-white' : 'border border-gold text-gold hover:bg-gold hover:text-white'}`}>{t('blog.filter.all')}</button>
            {categories.map((cat) => (
              <button key={cat.id} onClick={() => setSelectedCategory(catKey(cat))} className={`px-4 py-2 rounded-full text-xs uppercase tracking-wider font-semibold transition ${selectedCategory === catKey(cat) ? 'bg-gold text-white' : 'border border-gold text-gold hover:bg-gold hover:text-white'}`}>{cat.name}</button>
            ))}
          </div>
        </div>
      </section>

      {/* Article Grid */}
      <section className="pb-16">
        <div className="container-custom">
          {otherPosts.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {otherPosts.map((post) => (
                <Link key={post.id} href={`/blog/${post.slug}`} className="card bg-white overflow-hidden hover:shadow-lg transition-all duration-300 block">
                  <div className="h-40 bg-blush flex items-center justify-center text-5xl overflow-hidden">{renderImage(post.image, 'text-5xl')}</div>
                  <div className="p-6">
                    <span className="inline-block px-2 py-1 bg-blush text-gold text-xs font-bold rounded mb-3">{catName(post.category)}</span>
                    <h3 className="font-cormorant text-xl font-semibold text-espresso mb-2">{post.title}</h3>
                    <p className="text-sm text-grey-dark mb-4 line-clamp-3">{stripHtml(post.excerpt)}</p>
                    <div className="flex items-center justify-between text-xs text-grey">
                      <span>✍️ {post.author}</span>
                      <span>📅 {postDate(post) ? new Date(postDate(post)).toLocaleDateString('id-ID') : ''}</span>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          ) : (
            <div className="text-center py-12"><p className="text-grey-dark text-lg">{loading ? 'Memuat artikel...' : t('general.no-results')}</p></div>
          )}
        </div>
      </section>

      <section className="bg-gold text-white py-12 md:py-16">
        <div className="container-custom text-center max-w-2xl">
          <h2 className="font-cormorant text-2xl md:text-3xl font-bold mb-4">📧 {t('blog.newsletter.title')}</h2>
          <p className="mb-6">{t('blog.newsletter.desc')}</p>
          <form className="flex gap-2 flex-col sm:flex-row"><input type="email" placeholder="your@email.com" required className="flex-1 px-4 py-3 rounded-lg text-espresso" /><button type="submit" className="px-6 py-3 bg-white text-espresso text-xs uppercase tracking-widest font-semibold rounded whitespace-nowrap">{t('blog.newsletter.btn')}</button></form>
        </div>
      </section>
      <Footer />
    </main>
  );
}
