"use client";
import React, { useState, useEffect } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import AppImage from "@/components/ui/AppImage";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import AdImage from "@/components/AdImage";
import { pickAds } from "@/lib/ads";
import SidebarAdStack from "@/components/SidebarAdStack";

interface AuthorProfile {
  slug: string;
  display_name: string;
  role: string;
  kind: string;
  bio: string | null;
  address_line1: string | null;
  address_line2: string | null;
  city: string | null;
  state: string | null;
  postal_code: string | null;
  country: string | null;
  phone: string | null;
  email: string | null;
  website: string | null;
  twitter: string | null;
  linkedin: string | null;
  facebook: string | null;
  instagram: string | null;
  avatar_url: string;
  cover_url: string;
  specialties: string[];
  location_text: string | null;
  first_post_date: string | null;
  joined_label: string;
}

interface AuthorArticle {
  slug: string;
  title: string;
  excerpt: string;
  category: string;
  date: string;
  image: string | null;
  alt: string;
  readTime: string;
}

function combineLocation(p: AuthorProfile): string {
  const parts = [p.city, p.state, p.country].filter(Boolean);
  if (parts.length > 0) return parts.join(", ");
  return p.location_text || "";
}

function combineAddress(p: AuthorProfile): string[] {
  const lines: string[] = [];
  if (p.address_line1) lines.push(p.address_line1);
  if (p.address_line2) lines.push(p.address_line2);
  const cityLine = [p.city, p.state].filter(Boolean).join(", ");
  const tail = [cityLine, p.postal_code].filter(Boolean).join(" ");
  if (tail) lines.push(tail);
  if (p.country) lines.push(p.country);
  return lines;
}

export default function AuthorProfilePage() {
  const params = useParams();
  const slug = params?.slug as string;
  const [activeTab, setActiveTab] = useState<"articles" | "about">("articles");

  const [profile, setProfile] = useState<AuthorProfile | null>(null);
  const [articles, setArticles] = useState<AuthorArticle[]>([]);
  const [articleTotal, setArticleTotal] = useState<number>(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!slug) return;
    let cancelled = false;
    setLoading(true);
    fetch(`/api/author/${encodeURIComponent(slug)}?limit=500`, { cache: "no-store" })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (cancelled || !d) return;
        setProfile(d.profile as AuthorProfile);
        const live: AuthorArticle[] = (d.articles || []).map((a: any) => ({
          slug: a.slug,
          title: a.title,
          excerpt: a.excerpt || "",
          category: a.category || "News",
          date: a.date || "",
          image: a.image || "/assets/images/article-placeholder-v2.svg",
          alt: a.alt || a.title,
          readTime: a.readTime || "1 min read",
        }));
        setArticles(live);
        if (typeof d.total === "number") setArticleTotal(d.total);
      })
      .catch(() => {
        // network/API error — let the page render its empty state below.
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [slug]);

  const locationLine = profile ? combineLocation(profile) : "";
  const addressLines = profile ? combineAddress(profile) : [];

  return (
    <>
      <Header />
      <main className="bg-[#F8FAFC] min-h-screen">
      <aside className="float-right ml-6 mb-6 hidden lg:block max-w-[300px]"><SidebarAdStack /></aside>
        {/* Cover Image */}
        <div className="relative h-40 md:h-52 overflow-hidden">
          {profile && (
            <AppImage
              src={profile.cover_url}
              alt={`${profile.display_name} cover image`}
              width={1200}
              height={400}
              className="w-full h-full object-cover opacity-40"
            />
          )}
          <div className="absolute inset-0 bg-gradient-to-t from-[#F8FAFC] via-[#F8FAFC]/60 to-transparent" />
        </div>

        <div className="max-w-container mx-auto px-4">
          {/* Author Header */}
          <div className="relative -mt-16 md:-mt-20 mb-6">
            <div className="flex flex-col sm:flex-row sm:items-end gap-4">
              <div className="w-24 h-24 md:w-28 md:h-28 rounded-full overflow-hidden border-4 border-[#F8FAFC] flex-shrink-0 bg-[#FFFFFF]">
                {profile && (
                  <AppImage
                    src={profile.avatar_url}
                    alt={`${profile.display_name} profile photo`}
                    width={112}
                    height={112}
                    className="w-full h-full object-cover"
                  />
                )}
              </div>
              <div className="pb-1 flex-1">
                <h1 className="font-heading text-2xl md:text-3xl font-bold text-[#0F172A] leading-tight">
                  {loading ? "Loading…" : profile?.display_name || "Author"}
                </h1>
                <p className="font-body text-sm text-[#1D4ED8] mt-0.5">
                  {profile?.role || "Contributor"}
                </p>
                <div className="flex flex-wrap items-center gap-3 mt-2">
                  {locationLine && (
                    <span className="font-body text-xs text-[#666] flex items-center gap-1">
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                        <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z" />
                        <circle cx="12" cy="10" r="3" />
                      </svg>
                      {locationLine}
                    </span>
                  )}
                  {profile?.joined_label && (
                    <span className="font-body text-xs text-[#666]">
                      Joined {profile.joined_label}
                    </span>
                  )}
                  <span className="font-body text-xs font-bold text-[#888]">
                    {articleTotal.toLocaleString()} articles
                  </span>
                </div>
              </div>
              {/* Social Links */}
              {profile && (profile.twitter || profile.linkedin || profile.email) && (
                <div className="flex items-center gap-2 pb-1">
                  {profile.twitter && (
                    <a
                      href={profile.twitter}
                      target="_blank"
                      rel="noopener noreferrer"
                      aria-label={`${profile.display_name} on Twitter`}
                      className="w-8 h-8 flex items-center justify-center bg-[#FFFFFF] border border-[#DCE6F2] hover:border-[#1D4ED8] hover:text-[#1D4ED8] text-[#888] transition-colors rounded-sm"
                    >
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                        <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                      </svg>
                    </a>
                  )}
                  {profile.linkedin && (
                    <a
                      href={profile.linkedin}
                      target="_blank"
                      rel="noopener noreferrer"
                      aria-label={`${profile.display_name} on LinkedIn`}
                      className="w-8 h-8 flex items-center justify-center bg-[#FFFFFF] border border-[#DCE6F2] hover:border-[#1D4ED8] hover:text-[#1D4ED8] text-[#888] transition-colors rounded-sm"
                    >
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                        <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
                      </svg>
                    </a>
                  )}
                  {profile.email && (
                    <a
                      href={`mailto:${profile.email}`}
                      aria-label={`Email ${profile.display_name}`}
                      className="w-8 h-8 flex items-center justify-center bg-[#FFFFFF] border border-[#DCE6F2] hover:border-[#1D4ED8] hover:text-[#1D4ED8] text-[#888] transition-colors rounded-sm"
                    >
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                        <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
                        <polyline points="22,6 12,13 2,6" />
                      </svg>
                    </a>
                  )}
                </div>
              )}
            </div>
          </div>

          {/* Specialties */}
          {profile?.specialties && profile.specialties.length > 0 && (
            <div className="flex flex-wrap gap-2 mb-6">
              {profile.specialties.map((spec) => (
                <span
                  key={spec}
                  className="font-body text-xs text-[#1D4ED8] bg-[#DCE6F2]/30 border border-[#DCE6F2] px-2.5 py-1 rounded-sm"
                >
                  {spec}
                </span>
              ))}
            </div>
          )}

          {/* Tabs */}
          <div className="flex gap-0 border-b border-[#DCE6F2] mb-6">
            <button
              onClick={() => setActiveTab("articles")}
              className={`font-body text-xs font-bold uppercase tracking-wider px-4 py-3 border-b-2 transition-colors ${
                activeTab === "articles"
                  ? "border-[#1D4ED8] text-[#1D4ED8]"
                  : "border-transparent text-[#666] hover:text-[#aaa]"
              }`}
            >
              Articles ({loading ? "…" : articleTotal.toLocaleString()})
            </button>
            <button
              onClick={() => setActiveTab("about")}
              className={`font-body text-xs font-bold uppercase tracking-wider px-4 py-3 border-b-2 transition-colors ${
                activeTab === "about"
                  ? "border-[#1D4ED8] text-[#1D4ED8]"
                  : "border-transparent text-[#666] hover:text-[#aaa]"
              }`}
            >
              About
            </button>
          </div>

          {/* Articles tab */}
          {activeTab === "articles" && (
            <div className="pb-10">
              {loading ? (
                <p className="font-body text-sm text-[#666]">Loading articles…</p>
              ) : articles.length === 0 ? (
                <div className="empty-state">
                  <p className="empty-state-title">No articles yet</p>
                  <p className="empty-state-desc">This author hasn't published any articles yet.</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                  {articles.map((article) => (
                    <Link
                      key={article.slug}
                      href={`/articles/${article.slug}`}
                      className="group bg-[#FFFFFF] border border-[#DCE6F2] hover:border-[#1D4ED8] transition-colors rounded-sm overflow-hidden article-card"
                    >
                      <div className="img-zoom h-44 overflow-hidden">
                        <AppImage
                          src={article.image || "/assets/images/article-placeholder-v2.svg"}
                          alt={article.alt}
                          width={400}
                          height={176}
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <div className="p-4">
                        <div className="flex items-center gap-2 mb-2">
                          <span className="font-body text-[9px] font-bold uppercase tracking-widest text-[#1D4ED8]">
                            {article.category}
                          </span>
                          <span className="font-body text-[10px] text-[#555]">·</span>
                          <span className="font-body text-[10px] text-[#555]">{article.readTime}</span>
                        </div>
                        <h3 className="font-heading text-sm font-bold text-[#0F172A] group-hover:text-[#1D4ED8] transition-colors leading-snug mb-2 line-clamp-2">
                          {article.title}
                        </h3>
                        <p className="font-body text-xs text-[#777] leading-relaxed line-clamp-2 mb-3">
                          {article.excerpt}
                        </p>
                        <time className="font-body text-[10px] text-[#555]">{article.date}</time>
                      </div>
                    </Link>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* About tab */}
          {activeTab === "about" && profile && (
            <div className="max-w-3xl pb-10 space-y-5">
              <div className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-sm p-6">
                <p className="section-label mb-4">Biography</p>
                {profile.bio ? (
                  <p className="font-body text-sm text-[#1e293b] leading-relaxed whitespace-pre-line">
                    {profile.bio}
                  </p>
                ) : (
                  <p className="font-body text-sm text-[#666] italic">
                    No biography has been added yet for {profile.display_name}.
                  </p>
                )}
              </div>

              {/* Contact card — render when ANY contact field is populated */}
              {(profile.phone ||
                profile.email ||
                profile.website ||
                profile.address_line1 ||
                profile.city ||
                profile.country) && (
                <div className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-sm p-6">
                  <p className="section-label mb-4">Contact</p>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                    {addressLines.length > 0 && (
                      <div>
                        <p className="font-body text-xs font-bold uppercase tracking-wider text-[#555] mb-1">
                          Address
                        </p>
                        <address className="font-body text-sm text-[#1e293b] not-italic leading-relaxed">
                          {addressLines.map((line, i) => (
                            <span key={i}>
                              {line}
                              {i < addressLines.length - 1 && <br />}
                            </span>
                          ))}
                        </address>
                      </div>
                    )}
                    {profile.phone && (
                      <div>
                        <p className="font-body text-xs font-bold uppercase tracking-wider text-[#555] mb-1">
                          Phone
                        </p>
                        <a
                          href={`tel:${profile.phone.replace(/\s+/g, "")}`}
                          className="font-body text-sm text-[#1D4ED8] hover:underline"
                        >
                          {profile.phone}
                        </a>
                      </div>
                    )}
                    {profile.email && (
                      <div>
                        <p className="font-body text-xs font-bold uppercase tracking-wider text-[#555] mb-1">
                          Email
                        </p>
                        <a
                          href={`mailto:${profile.email}`}
                          className="font-body text-sm text-[#1D4ED8] hover:underline break-all"
                        >
                          {profile.email}
                        </a>
                      </div>
                    )}
                    {profile.website && (
                      <div>
                        <p className="font-body text-xs font-bold uppercase tracking-wider text-[#555] mb-1">
                          Website
                        </p>
                        <a
                          href={profile.website}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="font-body text-sm text-[#1D4ED8] hover:underline break-all"
                        >
                          {profile.website.replace(/^https?:\/\//, "").replace(/\/$/, "")}
                        </a>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* Profile facts */}
              <div className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-sm p-6">
                <p className="section-label mb-4">Profile</p>
                <div className="grid grid-cols-2 gap-4">
                  {locationLine && (
                    <div>
                      <p className="font-body text-xs font-bold uppercase tracking-wider text-[#555] mb-1">
                        Location
                      </p>
                      <p className="font-body text-sm text-[#1e293b]">{locationLine}</p>
                    </div>
                  )}
                  {profile.joined_label && (
                    <div>
                      <p className="font-body text-xs font-bold uppercase tracking-wider text-[#555] mb-1">
                        Member Since
                      </p>
                      <p className="font-body text-sm text-[#1e293b]">{profile.joined_label}</p>
                    </div>
                  )}
                  <div>
                    <p className="font-body text-xs font-bold uppercase tracking-wider text-[#555] mb-1">
                      Articles Published
                    </p>
                    <p className="font-body text-sm text-[#1e293b]">
                      {articleTotal.toLocaleString()}
                    </p>
                  </div>
                  <div>
                    <p className="font-body text-xs font-bold uppercase tracking-wider text-[#555] mb-1">
                      Role
                    </p>
                    <p className="font-body text-sm text-[#1e293b]">{profile.role}</p>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

      </main>
      <Footer />
    </>
  );
}
