"use client";

import { motion, useInView } from "framer-motion";
import { useRef, useState, useEffect } from "react";
import { ArrowRight, Clock, User, Loader2 } from "lucide-react";
import Link from "next/link";
import api from "@/lib/api";
import type { Post } from "@/lib/types";

export function Blog() {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchPosts() {
      try {
        const res = await api.get("/api/posts", { params: { per_page: 3 } });
        setPosts(res.data.data || []);
      } catch {
        setPosts([]);
      } finally {
        setLoading(false);
      }
    }
    fetchPosts();
  }, []);

  return (
    <section className="py-24 lg:py-32 bg-white" ref={ref}>
      <div className="mx-auto max-w-7xl px-6 lg:px-8">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.7 }}
          className="flex flex-col sm:flex-row sm:items-end sm:justify-between mb-16"
        >
          <div>
            <p className="text-xs text-primary uppercase tracking-[0.2em] font-semibold mb-4">
              //OUR BLOG
            </p>
            <h2 className="font-display text-3xl sm:text-4xl lg:text-5xl font-bold text-obsidian-700 leading-tight">
              READ OUR <span className="text-primary">LATEST BLOG</span>
            </h2>
          </div>
          <Link
            href="/blog"
            className="mt-6 sm:mt-0 inline-flex items-center gap-2 bg-obsidian-700 text-white px-8 py-4 text-sm font-semibold uppercase tracking-wider hover:bg-obsidian-900 transition-colors"
          >
            More Blog <ArrowRight size={16} />
          </Link>
        </motion.div>

        {/* Blog Grid */}
        {loading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="animate-spin text-primary" size={32} />
          </div>
        ) : posts.length === 0 ? (
          <div className="text-center py-16">
            <p className="text-obsidian-400">No blog posts yet. Check back soon!</p>
          </div>
        ) : (
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-8">
            {posts.map((post, i) => (
              <motion.article
                key={post.id}
                initial={{ opacity: 0, y: 40 }}
                animate={isInView ? { opacity: 1, y: 0 } : {}}
                transition={{ duration: 0.6, delay: i * 0.1 }}
                className="group"
              >
                <Link href={`/blog/${post.slug}`} className="block">
                  {/* Image */}
                  <div className="relative aspect-[16/10] overflow-hidden">
                    {post.featured_image ? (
                      <img
                        src={post.featured_image}
                        alt={post.featured_image_alt || post.title}
                        className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-110"
                      />
                    ) : (
                      <div className="h-full w-full bg-obsidian-100 flex items-center justify-center">
                        <span className="text-obsidian-300 text-sm">No image</span>
                      </div>
                    )}
                    <div className="absolute inset-0 bg-obsidian-900/0 group-hover:bg-obsidian-900/20 transition-colors duration-500" />
                  </div>

                  {/* Content */}
                  <div className="pt-5">
                    {/* Meta */}
                    <div className="flex items-center gap-4 text-xs text-obsidian-400">
                      <div className="flex items-center gap-1.5">
                        <User size={12} />
                        <span>By {post.author?.name}</span>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <Clock size={12} />
                        <span>{post.reading_time_minutes} min read</span>
                      </div>
                    </div>

                    <h3 className="mt-3 font-display text-base font-bold text-obsidian-700 group-hover:text-primary transition-colors leading-snug">
                      {post.title}
                    </h3>

                    <span className="inline-flex items-center gap-2 mt-4 text-xs font-semibold text-primary uppercase tracking-wider">
                      Read More <ArrowRight size={12} />
                    </span>
                  </div>
                </Link>
              </motion.article>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}
