import Image from "next/image";
import { notFound } from "next/navigation";
import { joomlaService, SAMPLE_LANDING_PAGES } from "@/services/joomlaService";
import { Breadcrumb } from "@/components/common/Breadcrumb";
import { WritersCarousel } from "@/components/home/WritersCarousel";
import { SampleTypeSelect } from "@/components/samples/SampleTypeSelect";
import { SampleLandingList } from "@/components/samples/SampleLandingList";
import { displayOnlyCount, resolveImageUrl, stripSampleLandingChrome } from "@/lib/pageHelpers";

const TRUST_BADGES = [
  { icon: "/icons/samples-original-document.svg", value: "100%", label: "Original Document" },
  { icon: "/icons/samples-free-paper.svg", value: "AI", label: "Free Paper" },
  { icon: "/icons/samples-experienced-writers.svg", value: "Experienced", label: "Writers" },
  { icon: "/icons/samples-plagiarism-report.svg", value: "Plagiarism", label: "Report" },
];

/** The same family of sibling landing pages the live `#select_trigger`
 * dropdown links between (`samplelanding.php`'s hardcoded `<option>` list)
 * — real internal routes, not an invented set. */
const LANDING_NAV = [
  { alias: "case-study-examples", label: "Case Study" },
  { alias: "coursework-examples", label: "Course Work" },
  { alias: "dissertation-examples", label: "Dissertation" },
  { alias: "essay-examples", label: "Essay" },
  { alias: "thesis-examples", label: "Ph.D. Thesis" },
];

/**
 * The live site's "sample landing" pages (`/case-study-examples`,
 * `/essay-examples`, ...) — see `SAMPLE_LANDING_PAGES` for how this app
 * detects them and where the real sample list comes from. Rebuilds the
 * banner, filter row and sample list as real components (the live
 * template's own markup for these relies on client-side jQuery this
 * server-rendered app doesn't run — see `stripSampleLandingChrome`), while
 * keeping the article's own real SEO body content underneath unchanged.
 */
export async function SampleLandingPage({ alias }: { alias: string }) {
  const config = SAMPLE_LANDING_PAGES[alias];
  if (!config) notFound();

  const [article, samples, { data: writers }] = await Promise.all([
    joomlaService.getArticleBySlug(alias),
    joomlaService.getSampleLandingArticles(config.filter),
    joomlaService.getWriters(6, 0),
  ]);

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

  const writerImages = await Promise.all(writers.map((w) => resolveImageUrl(w.imageUrl)));
  const writerItems = writers.map((w, i) => ({
    id: w.id,
    alias: w.alias,
    name: w.name,
    rating: w.rating || 5.0,
    completedProjects: w.reviewCount ? w.reviewCount * 150 + 400 : displayOnlyCount(w.id, 400, 1600),
    qualification: w.degree || w.position || "Academic Expert",
    bio: w.bio || "Experienced academic writer with expertise in university level research and assignment support.",
    location: w.location || "UK",
    avatarUrl: writerImages[i] || "/images/defaultWritter.png",
  }));
  const rawHtml = [article.introtext, article.fulltext].filter(Boolean).join("\n").replace(/\r\n/g, "\n");
  const seoHtml = stripSampleLandingChrome(rawHtml);
  const cpanelUrl = process.env.NEXT_PUBLIC_CPANEL_URL || "https://customerpanel.globalassignmenthelp.com";

  return (
    <div className="bg-slate-50 min-h-screen">
      {/* Banner — live `.sample-top-banner`: radial-gradient(#759B45 -> #5F8037) */}
      <section
        className="relative overflow-hidden text-white text-center py-10 px-4"
        style={{ background: "radial-gradient(50% 50% at 50% 50%, #759B45 0%, #5F8037 100%)" }}
      >
        <Image
          src="/icons/pen-doodle-1.svg"
          alt=""
          width={120}
          height={120}
          className="pointer-events-none select-none absolute -top-4 -left-4 w-24 h-24 opacity-40"
        />
        <Image
          src="/icons/pen-doodle-2.svg"
          alt=""
          width={120}
          height={120}
          className="pointer-events-none select-none absolute -bottom-4 -right-4 w-24 h-24 opacity-40"
        />
        <div className="relative max-w-4xl mx-auto">
          <h1 className="font-bold text-2xl sm:text-4xl leading-tight">{article.title}</h1>
          {article.bannerSubtitle && (
            <p className="mt-3 text-sm sm:text-base text-white/90 max-w-2xl mx-auto">{article.bannerSubtitle}</p>
          )}
          {config.ctaText && (
            <a
              href={`${cpanelUrl}/Order?ser=${config.service}`}
              className="inline-block mt-4 rounded bg-[#f58e0e] hover:bg-[#e07d0d] text-white font-bold text-sm px-6 py-2.5 transition-colors"
            >
              {config.ctaText}
            </a>
          )}
          <div className="mt-8 flex flex-wrap items-center justify-center gap-x-8 gap-y-5">
            {TRUST_BADGES.map((badge) => (
              <div key={badge.label} className="flex items-center gap-2.5 text-left">
                <Image src={badge.icon} alt="" width={32} height={32} className="w-8 h-8 shrink-0" />
                <p className="text-sm sm:text-base leading-tight">
                  <span className="font-bold">{badge.value}</span>
                  <br />
                  <span className="text-white/90">{badge.label}</span>
                </p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <Breadcrumb items={[{ label: "Sample", href: "/free-samples" }, { label: article.title }]} />

      {/* Filter row — real navigation between the live sibling landing
          pages; subject dropdown is display-only, same established pattern
          as the order form's "Select Services" dropdown (AGENTS.md: "the
          live list is filled client-side", no CMS-exposed source here either). */}
      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-5 flex flex-wrap items-center gap-3">
        <SampleTypeSelect current={alias} options={LANDING_NAV} />
        <select disabled className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-slate-400" defaultValue="">
          <option value="">Choose Your Subject</option>
        </select>
      </div>

      {/* Real sample list — single column, "Pages : N" corner badge, and
          the live site's own "Next" load-more + mid-list WhatsApp strip. */}
      {samples.length > 0 && (
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <SampleLandingList initialSamples={samples} filter={config.filter} />
        </div>
      )}

      {/* Real writer carousel, replacing the live page's empty
          AJAX-populated placeholder (`.writer-list`) — same real
          `getWriters()` data and carousel component the homepage uses,
          matching the live page's wide horizontal card layout. */}
      <div className="mt-6">
        <WritersCarousel
          writers={writerItems}
          subtitle="Experienced Writers"
          title="Pick Among the Thousands of Experienced Writers"
        />
      </div>

      {/* Real SEO article body */}
      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <div
          className="prose prose-green max-w-none text-sm text-slate-700 leading-relaxed"
          dangerouslySetInnerHTML={{ __html: seoHtml }}
        />
      </div>
    </div>
  );
}
