import { useEffect, useState } from "react";
import { useParams, Link } from "react-router-dom";
import { apiFetch } from "../lib/api";

type ArticleDetail = {
  id: string;
  title: string;
  subtitle: string | null;
  body: string;
  coverImage: string;
  caption: string | null;
};

export default function ArticlePage() {
  const { id } = useParams();
  const [article, setArticle] = useState<ArticleDetail | null>(null);
  const [state, setState] = useState<"loading" | "ok" | "error">("loading");

  useEffect(() => {
    if (!id) return;
    setState("loading");
    apiFetch<ArticleDetail>(`/articles/${id}`)
      .then((data) => {
        setArticle(data);
        setState("ok");
      })
      .catch(() => setState("error"));
  }, [id]);

  if (state === "loading") {
    return (
      <div className="min-h-svh paper-texture flex items-center justify-center">
        <p className="text-[var(--text-muted)] text-sm tracking-wider">加载中…</p>
      </div>
    );
  }

  if (state === "error" || !article) {
    return (
      <div className="min-h-svh paper-texture flex flex-col items-center justify-center gap-4 px-6">
        <p className="text-[var(--text-secondary)]">文章不存在或已下架</p>
        <Link
          to="/"
          className="px-5 py-2 rounded-full bg-[var(--gold)] text-white text-sm hover:bg-[var(--gold-hover)]"
        >
          返回首页
        </Link>
      </div>
    );
  }

  const paragraphs = article.body.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);

  return (
    <div className="relative paper-texture grain-overlay min-h-svh">
      {/* Top back button */}
      <Link
        to="/"
        aria-label="返回"
        className="fixed top-4 left-4 z-20 w-10 h-10 rounded-full bg-white/70 backdrop-blur border border-[var(--border-muted)]
          flex items-center justify-center text-[var(--text-secondary)] hover:bg-white shadow-sm"
      >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M15 18l-6-6 6-6" />
        </svg>
      </Link>

      <article className="relative max-w-2xl mx-auto px-6 pt-20 pb-24">
        {/* Hero */}
        <header className="text-center animate-fade-in-up">
          <div className="inline-flex items-center gap-3 mb-6">
            <span className="block w-8 h-px bg-[var(--gold)]/50" />
            <span className="text-[var(--gold)] text-[10px] tracking-[0.4em] uppercase"
              style={{ fontFamily: "'Playfair Display', serif" }}>
              CityWalk · Story
            </span>
            <span className="block w-8 h-px bg-[var(--gold)]/50" />
          </div>

          <h1
            className="text-[var(--text-primary)] leading-[1.15] mb-4"
            style={{
              fontSize: "clamp(2.25rem, 8vw, 3.25rem)",
              fontFamily: "'Playfair Display', serif",
              fontWeight: 700,
              letterSpacing: "-0.01em",
            }}
          >
            {article.title}
          </h1>

          {article.subtitle && (
            <p className="text-[var(--text-secondary)] text-base tracking-[0.08em] leading-relaxed">
              {article.subtitle}
            </p>
          )}

          <div className="ornament-line mt-10" />
        </header>

        {/* Cover image */}
        {article.coverImage && (
          <figure className="mt-8 animate-fade-in-up" style={{ animationDelay: "0.1s" }}>
            <div className="w-full aspect-[4/3] rounded-lg overflow-hidden bg-[var(--bg-paper)] shadow-[0_8px_24px_rgba(26,26,46,0.12)]">
              <img
                src={article.coverImage}
                alt={article.caption || article.title}
                className="w-full h-full object-cover"
              />
            </div>
            {article.caption && (
              <figcaption className="mt-3 text-center text-xs text-[var(--text-muted)] italic tracking-wide">
                {article.caption}
              </figcaption>
            )}
          </figure>
        )}

        {/* Body */}
        <section
          className="mt-10 animate-fade-in-up"
          style={{ animationDelay: "0.2s" }}
        >
          {paragraphs.map((p, i) => (
            <p
              key={i}
              className="text-[15px] text-[var(--text-primary)] mb-5"
              style={{ lineHeight: 2, textIndent: "2em" }}
            >
              {p}
            </p>
          ))}
        </section>

        {/* Footer */}
        <footer className="mt-16 text-center animate-fade-in-up" style={{ animationDelay: "0.3s" }}>
          <div className="ornament-line mb-8" />
          <p className="text-[var(--text-muted)] text-[11px] tracking-[0.3em] uppercase mb-5">
            Continue Your CityWalk
          </p>
          <Link
            to="/"
            className="inline-flex items-center gap-2 px-6 py-2.5 rounded-full border border-[var(--gold)]/60
              text-[var(--gold-hover)] text-sm hover:bg-[var(--gold)]/10 transition-colors"
          >
            返回首页
          </Link>
        </footer>
      </article>
    </div>
  );
}
