import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, CalendarDays, Clock, Eye, MessageCircle, Share2 } from "lucide-react";
import { joomlaService } from "@/services/joomlaService";
import { getNavigationData } from "@/app/api/navigation/route";
import { getHomePageData } from "@/app/api/home/route";
import { Breadcrumb } from "@/components/common/Breadcrumb";
import { BlogTocScroll } from "@/components/common/BlogTocScroll";
import { ExploreFreeToolsBlock } from "@/components/common/ExploreFreeToolsBlock";
import { ServiceOrderForm } from "@/components/home/ServiceOrderForm";
import { estimateReadMinutes, resolveImageUrl } from "@/lib/pageHelpers";


/**
 * Individual `/blog/{alias}` post — real article body (same `getArticleBySlug`
 * every other page uses) plus the live site's actual sidebar chrome: a real
 * price calculator (the same `<ServiceOrderForm>` services pages use, not a
 * second copy of the pricing logic), links to the free tools this app has
 * actually built, and the real "Latest"/"Most Viewed" blog lists. Built with
 * Tailwind classNames directly rather than a dedicated CSS file — unlike the
 * free-tool pages, none of this sidebar is raw Joomla-authored HTML this app
 * has to match byte-for-byte; it's chrome this app controls, so there's no
 * reason not to use ordinary React/Tailwind for it.
 *
 * The Table of Contents is real CMS content, not generated — article bodies
 * already embed a hand-authored `<div class="table-content">` with real
 * `onclick="scrollTodiv('1')"` links against real `<h3 id="1">` section
 * headings. See `BlogTocScroll` for how those links are wired up to work.
 */
export async function BlogArticlePage({ alias }: { alias: string }) {
  const [article, navigationData, { data: recentPosts }, { data: mostViewedPosts }, orderConfig, pricing, homeData] =
    await Promise.all([
      joomlaService.getArticleBySlug(alias),
      getNavigationData(),
      joomlaService.getBlogPosts(5, 0, "created"),
      joomlaService.getBlogPosts(4, 0, "hits"),
      joomlaService.getOrderServiceConfig(),
      joomlaService.getPricingConfig(),
      getHomePageData(),
    ]);

  if (!article || (!article.introtext && !article.fulltext)) {
    notFound();
  }

  const articleHtml = [article.introtext, article.fulltext]
    .filter(Boolean)
    .join("\n")
    .replace(/\r\n/g, "\n");

  const plainText = articleHtml.replace(/<[^>]*>/g, " ");
  const readMinutes = estimateReadMinutes(plainText);
  const publishedDate = article.created ? new Date(article.created) : null;
  const heroImage = article.imageUrl ? await resolveImageUrl(article.imageUrl) : null;

  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || "https://www.globalassignmenthelp.com";
  const shareUrl = `${siteUrl}/blog/${article.alias}`;
  const shareLinks = {
    facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`,
    whatsapp: `https://wa.me/?text=${encodeURIComponent(`${article.title} ${shareUrl}`)}`,
    x: `https://twitter.com/intent/tweet?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(article.title)}`,
    linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareUrl)}`,
  };

  const freeToolsBottom = [
    { label: "AI Essay Writer", desc: "Get a well-researched and quality essay effortlessly in a few seconds!", href: "/ai-essay-writer" },
    { label: "Grammar Checker", desc: "Write an error-free document with our grammar checker tool!", href: "/grammar-checker" },
  ];

  return (
    <div className="bg-slate-50 min-h-screen">
      <Breadcrumb items={[{ label: "Blogs", href: "/blog" }, { label: article.title }]} />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 grid grid-cols-1 lg:grid-cols-[1fr_340px] gap-8 items-start">
        <article className="min-w-0">
          <div className="flex flex-col sm:flex-row gap-6 items-start">
            <div className="flex-1">
              <h1 className="text-2xl sm:text-3xl font-extrabold text-slate-900 leading-tight">{article.title}</h1>
              <div className="mt-4 flex flex-wrap items-center gap-x-5 gap-y-2 text-xs text-slate-500 font-medium">
                {publishedDate && (
                  <span className="flex items-center gap-1.5">
                    <CalendarDays className="w-3.5 h-3.5" />
                    {publishedDate.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })}
                  </span>
                )}
                {typeof article.hits === "number" && (
                  <span className="flex items-center gap-1.5">
                    <Eye className="w-3.5 h-3.5" />
                    {article.hits.toLocaleString()}
                  </span>
                )}
                <span className="flex items-center gap-1.5">
                  <Clock className="w-3.5 h-3.5" />
                  {readMinutes} minutes
                </span>
                <span className="flex items-center gap-2 ml-auto">
                  <span className="text-slate-400">SHARE IT:</span>
                  {/* Real footer social icons (facebook.png/twitter.png) reused here;
                      WhatsApp/LinkedIn have no matching brand asset in public/icons,
                      so those two use generic Lucide icons instead of the wrong brand mark. */}
                  <a
                    href={shareLinks.facebook}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-7 h-7 rounded-full bg-slate-100 hover:bg-[#5C7A36] flex items-center justify-center transition-colors"
                  >
                    <Image src="/icons/facebook.png" alt="Share on Facebook" width={14} height={14} />
                  </a>
                  <a
                    href={shareLinks.whatsapp}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-7 h-7 rounded-full bg-slate-100 hover:bg-[#5C7A36] hover:text-white flex items-center justify-center text-slate-600 transition-colors"
                  >
                    <MessageCircle className="w-3.5 h-3.5" />
                  </a>
                  <a
                    href={shareLinks.x}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-7 h-7 rounded-full bg-slate-100 hover:bg-[#5C7A36] flex items-center justify-center transition-colors"
                  >
                    <Image src="/icons/twitter.png" alt="Share on X" width={14} height={14} />
                  </a>
                  <a
                    href={shareLinks.linkedin}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-7 h-7 rounded-full bg-slate-100 hover:bg-[#5C7A36] hover:text-white flex items-center justify-center text-slate-600 transition-colors"
                  >
                    <Share2 className="w-3.5 h-3.5" />
                  </a>
                </span>
              </div>
            </div>
            {heroImage && (
              <div className="w-full sm:w-[320px] shrink-0 rounded-xl overflow-hidden shadow-sm">
                {/* eslint-disable-next-line @next/next/no-img-element -- real CMS-hosted image */}
                <img src={heroImage} alt={article.title} className="w-full h-auto object-cover" />
              </div>
            )}
          </div>

          {articleHtml.includes("scrollTodiv") && <BlogTocScroll />}

          <div
            className="prose prose-green max-w-none text-sm text-slate-700 leading-relaxed mt-6"
            dangerouslySetInnerHTML={{ __html: articleHtml }}
          />

          <div className="mt-10 grid grid-cols-1 sm:grid-cols-2 gap-4">
            {freeToolsBottom.map((tool) => (
              <Link
                key={tool.href}
                href={tool.href}
                className="group rounded-xl bg-white border border-slate-200 shadow-sm hover:shadow-md hover:border-[#5C7A36]/40 transition-all p-5"
              >
                <p className="text-xs font-bold text-[#5C7A36] uppercase tracking-wide">Free Tools</p>
                <p className="mt-1 text-lg font-bold text-slate-900 group-hover:text-[#5C7A36] transition-colors">
                  {tool.label}
                </p>
                <p className="mt-1 text-sm text-slate-500">{tool.desc}</p>
                <span className="mt-3 inline-flex items-center gap-1 text-sm font-semibold text-[#f58e0e]">
                  Check Now <ArrowLeft className="w-3.5 h-3.5 rotate-180" />
                </span>
              </Link>
            ))}
          </div>
        </article>

        <aside className="space-y-6 lg:sticky lg:top-6">
          <ServiceOrderForm
            variant="sidebar"
            config={homeData.hero.calculator}
            orderConfig={orderConfig}
            pricing={pricing}
            title="Price Calculator"
            subtitle="Get an instant estimate for your assignment"
          />

          <ExploreFreeToolsBlock />

          <div className="rounded-xl bg-white border border-slate-200 shadow-sm p-5">
            <div className="flex items-center gap-4 text-sm font-bold border-b border-slate-100 mb-4">
              <span className="pb-2.5 border-b-2 border-[#5C7A36] text-slate-900">Latest Blog&apos;s</span>
              <span className="pb-2.5 text-slate-400">Featured Posts</span>
            </div>
            <ul className="space-y-4">
              {recentPosts.slice(0, 4).map((post) => (
                <li key={post.id}>
                  <Link href={`/blog/${post.alias}`} className="group flex gap-3">
                    <div className="w-16 h-16 rounded-lg overflow-hidden bg-slate-100 shrink-0">
                      {post.imageUrl ? (
                        // eslint-disable-next-line @next/next/no-img-element -- real CMS-hosted image
                        <img src={post.imageUrl} alt={post.title} className="w-full h-full object-cover" />
                      ) : null}
                    </div>
                    <p className="text-sm font-semibold text-slate-800 leading-snug line-clamp-3 group-hover:text-[#5C7A36] transition-colors">
                      {post.title}
                    </p>
                  </Link>
                </li>
              ))}
            </ul>
          </div>

          <div
            className="rounded-xl overflow-hidden shadow-sm p-6 text-white"
            style={{ background: "linear-gradient(135deg, #2e6434 0%, #1d3f22 100%)" }}
          >
            <p className="text-lg font-bold leading-snug">Big Project Or Small Hurdle?</p>
            <p className="mt-1 text-sm text-white/80">Our Exciting Offers are For Every Student.</p>
            <Link
              href={navigationData.header.cta.orderNowUrl}
              className="mt-4 inline-block rounded px-4 py-2.5 text-xs font-bold uppercase bg-[#f58e0e] hover:bg-[#e07d0d] transition-colors"
            >
              Explore offers!
            </Link>
          </div>

          {mostViewedPosts.length > 0 && (
            <div className="rounded-xl bg-white border border-slate-200 shadow-sm p-5">
              <p className="text-sm font-bold text-slate-900 mb-4">Most Viewed</p>
              <ul className="space-y-3">
                {mostViewedPosts.map((post) => (
                  <li key={post.id}>
                    <Link
                      href={`/blog/${post.alias}`}
                      className="text-sm font-medium text-slate-700 hover:text-[#5C7A36] transition-colors line-clamp-2"
                    >
                      {post.title}
                    </Link>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </aside>
      </div>
    </div>
  );
}
