"use client";

import { useEffect, useState, use } from "react";
import BottomNav from "@/components/BottomNav";
import AppHeader from "@/components/AppHeader";
import { Calendar, Share2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { sanitizeHtml } from "@/lib/sanitize";

interface Post {
  id: number;
  title: string;
  content: string;
  image: string | null;
  date: string;
}

export default function NewsDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const [post, setPost] = useState<Post | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/posts/${id}`)
      .then((r) => r.json())
      .then((data) => { if (data.id) setPost(data); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [id]);

  if (loading) {
    return (
      <div className="pb-20">
        <AppHeader title="Nyheter" />
        <div className="aspect-video skeleton" />
        <div className="p-4 space-y-3"><div className="h-3 skeleton rounded w-24" /><div className="h-6 skeleton rounded w-full" /><div className="h-6 skeleton rounded w-3/4" /><div className="h-4 skeleton rounded w-full mt-4" /><div className="h-4 skeleton rounded w-full" /></div>
        <BottomNav />
      </div>
    );
  }

  if (!post) {
    return (
      <div className="pb-20">
        <AppHeader title="Nyheter" />
        <div className="text-center py-16"><p className="text-gray-500">Artikeln hittades inte.</p>
          <button onClick={() => router.back()} className="mt-4 px-6 py-2 bg-emerald-mosque text-white rounded-lg font-medium">Tillbaka</button>
        </div>
        <BottomNav />
      </div>
    );
  }

  return (
    <div className="pb-20">
      <AppHeader title="Nyheter" />

      {post.image && (
        <div className="aspect-video bg-gray-100 overflow-hidden">
          <img src={post.image} alt="" className="w-full h-full object-cover" />
        </div>
      )}

      <div className="p-5">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2 text-xs text-gray-500">
            <Calendar size={12} />
            <time>{new Date(post.date).toLocaleDateString("sv-SE", { weekday: "long", year: "numeric", month: "long", day: "numeric" })}</time>
          </div>
          <button className="p-2 rounded-full hover:bg-gray-100"><Share2 size={16} className="text-gray-500" /></button>
        </div>

        <h1 className="text-2xl font-bold text-gray-900 leading-tight mb-4" dangerouslySetInnerHTML={{ __html: sanitizeHtml(post.title) }} />

        <div
          className="prose prose-sm max-w-none text-gray-700 leading-relaxed
            [&_p]:mb-4 [&_h2]:text-lg [&_h2]:font-bold [&_h2]:mt-6 [&_h2]:mb-2 [&_h2]:text-gray-900
            [&_h3]:font-bold [&_h3]:mt-4 [&_h3]:mb-2
            [&_img]:rounded-xl [&_img]:my-4
            [&_a]:text-emerald-mosque [&_a]:underline
            [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5
            [&_strong]:text-gray-900
            [&_figure]:my-4 [&_figcaption]:text-xs [&_figcaption]:text-gray-400 [&_figcaption]:mt-1"
          dangerouslySetInnerHTML={{ __html: sanitizeHtml(post.content) }}
        />
      </div>

      <BottomNav />
    </div>
  );
}
