import React from "react";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, Search } from "lucide-react";
import { joomlaService } from "@/services/joomlaService";
import { getNavigationData } from "@/app/api/navigation/route";
import { Breadcrumb } from "@/components/common/Breadcrumb";
import { ListingPagination } from "@/components/common/ListingPagination";
import {
  displayOnlyCount,
  escapeHtml,
  fillSamplesSidebarTokens,
  hireWriterUrl,
  LISTING_PAGE_SIZE,
  resolveImageUrl,
} from "@/lib/pageHelpers";
import { SAMPLES_BADGES } from "./samplesConstants";
import { SampleSubjectFilter } from "@/components/common/SampleSubjectFilter";

export async function SamplesSubjectPage({
  subjectAlias,
  page,
  basePath = "/free-samples",
}: {
  subjectAlias: string;
  page: number;
  basePath?: string;
}) {
  const rootAlias = basePath === "/answers" ? "answers" : "free-samples";
  const [
    { data: samples, total, categoryTitle },
    navigationData,
    categories,
    { data: sidebarWriters },
    siteStats,
    sidebarModuleHtml,
  ] = await Promise.all([
    joomlaService.getSampleArticles(subjectAlias, LISTING_PAGE_SIZE, (page - 1) * LISTING_PAGE_SIZE),
    getNavigationData(),
    joomlaService.getSampleCategories(rootAlias),
    joomlaService.getWriters(3, 0),
    joomlaService.getSiteStats(),
    joomlaService.getSamplesSidebarHtml(),
  ]);
  const sidebarWriterImages = await Promise.all(sidebarWriters.map((writer) => resolveImageUrl(writer.imageUrl)));

  if (total === 0 && !categoryTitle) notFound();

  // Writer cards for the module's own `dynamic_writer_section` slot, built
  // from the real `type=writers` bridge data (name, photo, rating, review
  // count) plus the real `?writer=` order-form deep link.
  const sidebarWritersHtml = sidebarWriters
    .map((writer, index) => {
      const ratingMarkup =
        writer.rating !== null
          ? `<p class="writer-rating"><span class="stars">★</span> ${writer.rating.toFixed(1)} (${writer.reviewCount})</p>`
          : "";
      return `<li class="writer-card">
        <img src="${escapeHtml(sidebarWriterImages[index])}" alt="${escapeHtml(writer.name)}" />
        <div class="writer-info">
          <p class="writer-name">${escapeHtml(writer.name)}</p>
          ${ratingMarkup}
          <p class="writer-orders">${displayOnlyCount(writer.id, 150, 1400)} - Completed Orders</p>
        </div>
        <a href="${escapeHtml(hireWriterUrl(writer.name))}" class="hire-now-btn">Hire Now</a>
      </li>`;
    })
    .join("");

  const sidebarHtml = sidebarModuleHtml
    ? fillSamplesSidebarTokens(sidebarModuleHtml, {
      writersCount: siteStats.writersCount,
      categoryTitle: categoryTitle || "Assignment",
      rating: navigationData.footer.ratingInfo.rating.replace("/5", ""),
      reviewsCount: navigationData.footer.ratingInfo.reviewsCount,
      orderNowUrl: navigationData.header.cta.orderNowUrl,
      writersHtml: sidebarWritersHtml,
    })
    : null;

  const dateFormatter = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric" });
  const rootLabel = basePath === "/answers" ? "Answers" : "Samples";

  return (
    <div className="min-h-[60vh] bg-white">
      {/* Same real `.sample-top-banner` gradient/doodle treatment as the root
          `/free-samples` page (SamplesIndexPage above), with the heading and
          badges kept generic/real rather than fabricating subject-specific
          marketing copy the CMS doesn't actually provide. */}
      <section
        className="relative overflow-hidden text-white text-center py-[30px] px-4 sm:px-6 lg:px-8"
        style={{ background: "radial-gradient(50% 50% at 50% 50%, #759B45 0%, #5F8037 100%)" }}
      >
        <Image
          src="/icons/pen-doodle-1.svg"
          alt=""
          width={115}
          height={112}
          className="hidden sm:block absolute top-0 right-0 pointer-events-none select-none"
        />
        <Image
          src="/icons/pen-doodle-2.svg"
          alt=""
          width={97}
          height={116}
          className="hidden sm:block absolute bottom-0 left-8 pointer-events-none select-none"
        />

        <div className="relative z-[1] max-w-3xl mx-auto space-y-1">
          <h1 className="text-[28px] sm:text-[32px] leading-tight sm:leading-[38px] font-bold">
            Free Samples of <span>{categoryTitle}</span> Assignments
          </h1>
          <p className="text-[15px] sm:text-base leading-[19px] text-green-50 my-[15px]">
            Explore our list of free samples of {categoryTitle} assignments to get academic writing help. We have
            curated a vast library of examples of {categoryTitle} assignments for free to help students with
            writing tasks. So, if you want to seek {categoryTitle} assignment help, our experts are here for you.
          </p>
          <Link
            href="https://customerpanel.globalassignmenthelp.com/Order?ser=assignment"
            className="inline-block rounded px-[9px] py-[6px] mb-[15px] font-bold text-sm text-white"
            style={{ background: "#f58e0e" }}
          >
            Explore Free Samples
          </Link>
        </div>

        <div className="relative z-[1] flex flex-wrap items-center justify-center gap-x-[30px] gap-y-4 mt-4">
          {SAMPLES_BADGES.map(({ src, width, height, top, bottom, topIsBadge }) => (
            <div key={bottom} className="flex items-center gap-1.5 text-left">
              <Image src={src} alt="" width={width} height={height} className="shrink-0" style={{ width, height }} />
              <p className="text-[19px] leading-[25px]">
                {topIsBadge ? (
                  <span className="inline-block bg-[#333333] text-[14px] leading-[19px] rounded px-1">{top}</span>
                ) : (
                  <span>{top}</span>
                )}
                <span className="block text-base leading-[21px]">{bottom}</span>
              </p>
            </div>
          ))}
        </div>
      </section>

      <div className="bg-slate-50">
        <Breadcrumb items={[{ label: rootLabel, href: basePath }, { label: categoryTitle || subjectAlias }]} />


        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          {/* Subject switcher + keyword search — real subjects (same data as
              the root `/free-samples` page), not a fabricated taxonomy. */}
          <SampleSubjectFilter categories={categories} currentSubjectAlias={subjectAlias} basePath={basePath} />

          <div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-8 items-start">
            <div className="space-y-6">
              {samples.length === 0 ? (
                <p className="text-sm text-slate-500">No samples published in this subject yet.</p>
              ) : (
                <div className="space-y-4">
                  {samples.map((sample, index) => (
                    <React.Fragment key={sample.id}>
                      <Link
                        href={`${basePath}/${subjectAlias}/${sample.alias}`}
                        className="group relative flex flex-col sm:flex-row gap-4 bg-white rounded-2xl border border-slate-200 shadow-sm p-4 transition-all duration-200 hover:shadow-lg hover:-translate-y-0.5 hover:border-[#5C7A36]/40"
                      >
                        <span className="absolute top-4 right-4 rounded-full bg-[#5C7A36] text-white text-xs font-bold px-2.5 py-1">
                          Pages: {sample.pageCount}
                        </span>
                        {sample.imageUrl && (
                          // eslint-disable-next-line @next/next/no-img-element -- external CMS-hosted image, not a static asset
                          <img
                            src={sample.imageUrl}
                            alt={sample.title}
                            className="w-full sm:w-48 h-40 sm:h-auto rounded-xl object-cover shrink-0"
                          />
                        )}
                        <div className="flex-1 flex flex-col pr-20">
                          <h2 className="font-bold text-base text-slate-900 leading-snug group-hover:text-[#5C7A36] transition-colors">
                            {sample.title}
                          </h2>
                          <div className="flex items-center gap-3 mt-1.5 text-xs text-slate-500">
                            {sample.createdAt && <span>{dateFormatter.format(new Date(sample.createdAt))}</span>}
                            <span aria-hidden="true">&middot;</span>
                            <span>Downloads: {(sample.downloads ?? 0).toLocaleString()}</span>
                            <span aria-hidden="true">&middot;</span>
                            <span>Words: {(sample.wordCount ?? 0).toLocaleString()}</span>
                          </div>
                          <p className="text-sm text-slate-500 leading-relaxed mt-2 flex-1">{sample.excerpt}</p>
                          <span className="inline-flex items-center gap-1 mt-3 text-sm font-bold text-[#f58e0e] w-fit">
                            View or Download
                            <ArrowLeft className="w-3.5 h-3.5 rotate-180 transition-transform group-hover:translate-x-1" />
                          </span>
                        </div>
                      </Link>

                      {/* The real `.whatsapp-query-strip` — confirmed from the
                          live install's actual rendered output for this exact
                          URL, sourced from `category/blog.php` lines 989-1010
                          (Joomla category layouts aren't tied to the file's
                          name). Illustration copied from the template's own
                          images folder; link built from the real site number. */}




                      {index === 2 && (
                        <a
                          href={navigationData.header.topBar.whatsappUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="relative flex min-h-[180px] w-full items-center overflow-hidden rounded-2xl bg-[#DFFFE0] px-6 py-6 sm:min-h-[190px] sm:px-8"
                        >
                          {/* WhatsApp Background */}
                          <svg
                            className="pointer-events-none absolute -left-2 top-1/2 h-[157px] w-[148px] -translate-y-1/2"
                            viewBox="0 0 148 157"
                            fill="none"
                            xmlns="http://www.w3.org/2000/svg"
                          >
                            <g opacity="0.15" clipPath="url(#whatsapp-strip-clip)">
                              <path
                                d="M-21.5775 76.1988C-19.1301 89.5584 -13.2462 101.962 -4.49947 112.241L-8.05073 153.498L30.2158 135.581C42.4454 139.594 55.4852 140.479 68.1452 138.158L68.1784 138.152C109.971 130.483 137.751 90.2337 130.099 48.4307C126.391 28.1743 115.015 10.5738 98.0678 -1.12853C81.1229 -12.8301 60.6346 -17.2317 40.3466 -13.5188C-1.45072 -5.84973 -29.2288 34.3976 -21.5769 76.1987"
                                fill="url(#whatsapp-strip-g1)"
                              />

                              <path
                                d="M-24.2893 76.6712C-21.7543 90.5116 -15.6597 103.359 -6.60083 114.006L-10.2795 156.742L29.3591 138.183C41.9807 142.333 55.5041 143.261 68.6501 140.854L68.6839 140.848C111.976 132.905 140.753 91.2075 132.828 47.908C128.985 26.9239 117.201 8.69082 99.6474 -3.43103C82.0926 -15.5507 60.8712 -20.1114 39.8567 -16.2646C-3.44245 -8.31998 -32.2162 33.3714 -24.2893 76.6712ZM7.33697 109.329L5.32926 107.146C-3.11379 97.9525 -8.76726 86.5756 -11.0251 74.2426C-17.6145 38.253 6.30111 3.60086 42.3147 -3.00697C59.7565 -6.19958 77.3943 -2.40821 91.9854 7.66512C106.576 17.7398 116.368 32.8941 119.564 50.3366C126.151 86.3266 102.236 120.983 66.2505 127.585L66.2246 127.59C54.5063 129.734 42.4374 128.695 31.3245 124.588L28.6801 123.611L5.15762 134.624L7.33697 109.329Z"
                                fill="url(#whatsapp-strip-g2)"
                              />

                              <path
                                d="M28.6076 33.0319C26.5376 30.0336 24.978 30.2516 23.5692 30.4508C22.4151 30.6116 21.1068 30.8555 19.7991 31.0954C18.4901 31.3356 16.4538 32.2182 15.0162 34.5109C13.5772 36.8057 9.37766 42.4839 11.1494 52.1402C12.9212 61.7965 21.6671 69.8388 22.8881 70.9697C24.1098 72.0979 40.4586 90.237 61.852 94.4439C79.6318 97.9397 82.7673 96.0203 86.3055 95.0322C89.8446 94.0452 97.0476 88.1549 97.8416 83.2717C98.637 78.3889 97.9163 74.4608 97.2751 73.73C96.6345 73.0022 95.2354 72.7512 93.0926 72.1302C90.9498 71.5093 80.4282 68.5309 78.5091 68.2059C76.5896 67.8816 75.2213 67.795 74.2729 70.0005C73.324 72.2029 70.3763 77.3124 69.4709 78.8315C68.5672 80.3536 67.4515 80.7271 65.3092 80.1054C63.1644 79.481 56.4635 78.5707 47.7374 73.2608C40.948 69.1288 35.83 63.427 34.3244 61.6718C32.8193 59.9197 33.6465 58.6684 34.4513 57.5098C35.1718 56.4686 35.9942 54.8576 36.7663 53.5318C37.5346 52.2059 37.7112 51.3282 38.1255 49.8992C38.5402 48.4688 38.002 47.3827 37.332 46.4909C36.6601 45.5994 31.0649 36.5923 28.6076 33.0319Z"
                                fill="white"
                              />
                            </g>

                            <defs>
                              <linearGradient
                                id="whatsapp-strip-g1"
                                x1="10385.9"
                                y1="13901.9"
                                x2="7578.91"
                                y2="-1396.71"
                                gradientUnits="userSpaceOnUse"
                              >
                                <stop offset="0.545" stopColor="#60D669" />
                                <stop offset="0.835" stopColor="#1FAF38" />
                              </linearGradient>

                              <linearGradient
                                id="whatsapp-strip-g2"
                                x1="10756.6"
                                y1="14398.1"
                                x2="7848.9"
                                y2="-1449.08"
                                gradientUnits="userSpaceOnUse"
                              >
                                <stop stopColor="#F9F9F9" />
                                <stop offset="1" stopColor="white" />
                              </linearGradient>

                              <clipPath id="whatsapp-strip-clip">
                                <rect
                                  width="160.399"
                                  height="161.652"
                                  fill="white"
                                  transform="translate(-39.3562 -1.73047) rotate(-10.3971)"
                                />
                              </clipPath>
                            </defs>
                          </svg>

                          {/* Mail Decoration */}
                          <svg
                            className="pointer-events-none absolute right-[100px] top-5 hidden h-[39px] w-[43px] sm:block"
                            viewBox="0 0 43 39"
                            fill="none"
                            xmlns="http://www.w3.org/2000/svg"
                          >
                            <path
                              d="M29.4869 37.3119L1.91065 21.2592C0.899345 20.6705 0.557034 19.3737 1.14576 18.3624L10.873 1.65296C11.4618 0.641655 12.7585 0.299344 13.7698 0.888065L41.3461 16.9408C42.3574 17.5295 42.6997 18.8262 42.111 19.8375L32.3837 36.547C31.795 37.5583 30.4982 37.9006 29.4869 37.3119Z"
                              stroke="#169047"
                              strokeWidth="1.115"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            />

                            <path
                              d="M10.5183 2.26172L18.9801 19.0213C19.7405 20.5288 21.3182 21.4465 23.0041 21.364L41.7562 20.4463"
                              stroke="#169047"
                              strokeWidth="1.115"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            />

                            <path
                              d="M5.38745 17.8138C8.62765 17.864 11.8667 17.9142 15.1069 17.9643"
                              stroke="#169047"
                              strokeWidth="1.115"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            />

                            <path
                              d="M30.7657 32.5864C29.1222 29.7933 27.4787 27.0013 25.8352 24.2083"
                              stroke="#169047"
                              strokeWidth="1.115"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            />
                          </svg>

                          {/* Content */}
                          <div className="relative z-10 flex min-w-0 flex-1 flex-col justify-center">

                            {/* Heading */}
                            <h2 className="flex items-center gap-2 text-base font-bold leading-tight text-[#263238] sm:text-xl">
                              <svg
                                width="29"
                                height="30"
                                viewBox="0 0 29 30"
                                fill="none"
                                xmlns="http://www.w3.org/2000/svg"
                                className="h-7 w-7 shrink-0"
                              >
                                <path
                                  d="M0.614066 14.4264C0.613392 16.8629 1.25004 19.2421 2.46062 21.3391L0.498291 28.5039L7.83057 26.5813C9.85859 27.6853 12.1308 28.2638 14.4399 28.264H14.4459C22.0686 28.264 28.2735 22.0612 28.2768 14.4373C28.2783 10.7429 26.8409 7.26899 24.2293 4.6554C21.6182 2.04202 18.1455 0.602028 14.4454 0.600342C6.82187 0.600342 0.617326 6.80274 0.614179 14.4264"
                                  fill="#CEFFCF"
                                />

                                <path
                                  d="M0.120271 14.4219C0.119485 16.9462 0.778954 19.4104 2.0327 21.5825L0 29.0041L7.59519 27.0126C9.68791 28.1537 12.0441 28.7552 14.4417 28.7561H14.4478C22.3439 28.7561 28.7718 22.3303 28.7752 14.4334C28.7765 10.6063 27.2874 7.00748 24.5826 4.30025C21.8774 1.59336 18.2805 0.101549 14.4478 0.0999756C6.5504 0.0999756 0.123419 6.52494 0.120271 14.4219ZM4.64349 21.2084L4.35989 20.7582C3.16774 18.8626 2.53851 16.6721 2.53941 14.4228C2.54188 7.85905 7.88373 2.51889 14.4523 2.51889C17.6334 2.52024 20.6228 3.76027 22.8713 6.01013C25.1197 8.26022 26.357 11.2513 26.3562 14.4325C26.3532 20.9963 21.0113 26.3371 14.4478 26.3371H14.4431C12.306 26.336 10.21 25.7621 8.38212 24.6775L7.94713 24.4195L3.43999 25.6012L4.64349 21.2084Z"
                                  fill="#05D459"
                                />

                                <path
                                  d="M10.8669 8.43426C10.5987 7.83818 10.3165 7.82616 10.0614 7.8157C9.85258 7.80671 9.61384 7.80738 9.37532 7.80738C9.13658 7.80738 8.74867 7.89719 8.42079 8.2552C8.09258 8.61354 7.16772 9.47949 7.16772 11.2407C7.16772 13.002 8.45058 14.7042 8.62941 14.9433C8.80847 15.1819 11.106 18.9119 14.7447 20.3468C17.7688 21.5393 18.3842 21.3022 19.0405 21.2424C19.697 21.1828 21.1586 20.3766 21.4569 19.5407C21.7553 18.7049 21.7553 17.9884 21.6658 17.8387C21.5763 17.6895 21.3376 17.5999 20.9796 17.421C20.6216 17.2421 18.8615 16.3759 18.5334 16.2564C18.2051 16.137 17.9665 16.0774 17.7278 16.4359C17.489 16.7938 16.8035 17.5999 16.5945 17.8387C16.3858 18.078 16.1768 18.1078 15.8189 17.9287C15.4607 17.7491 14.3078 17.3715 12.94 16.1521C11.8757 15.2032 11.1572 14.0314 10.9484 13.6729C10.7396 13.315 10.926 13.121 11.1055 12.9426C11.2664 12.7822 11.4637 12.5246 11.6428 12.3156C11.8213 12.1066 11.8809 11.9574 12.0003 11.7187C12.1198 11.4797 12.06 11.2706 11.9706 11.0916C11.8809 10.9125 11.1852 9.14206 10.8669 8.43426Z"
                                  fill="#05D459"
                                />
                              </svg>

                              <span>Exciting Offers are Waiting For You</span>
                            </h2>

                            {/* Description */}
                            <p className="mt-2 text-sm leading-6 text-[#263238] sm:text-base">
                              Get Expert Assistance on Your{" "}
                              <span className="font-bold text-[#169047]">WhatsApp</span>!
                            </p>

                            {/* Button */}
                            <div className="mt-3 w-fit rounded-full bg-[#F58E0E] px-5 py-2 text-align-center text-sm font-bold text-white transition-colors duration-200 hover:bg-[#e47d00]">
                              Get Assistance
                            </div>
                          </div>

                          {/* Girl */}
                          <div className="pointer-events-none relative z-10 hidden h-[138px] w-[100px] shrink-0 sm:block md:h-[159px] md:w-[115px]">
                            <Image
                              src="/images/whatsapp-phone-girl.png"
                              alt="WhatsApp assistance"
                              fill
                              sizes="115px"
                              className="object-contain"
                            />
                          </div>
                        </a>
                      )}
                    </React.Fragment>
                  ))}
                </div>
              )}

              <ListingPagination basePath={`${basePath}/${subjectAlias}`} page={page} total={total} />
            </div>

            {/* Sidebar — the real "Samples listing sidebar" module
                (`#__modules` id 118), fetched live through the bridge and
                rendered as stored, with only its own placeholder tokens
                filled in (writer cards, counts, rating, URLs). Every
                heading, label and list item therefore comes from Joomla, so
                editing that module in Joomla Admin changes this page with no
                code change. Styled by `app/samples-sidebar.css`, same
                approach as the other CMS-sourced blocks in this app. */}
            <aside className="samples-sidebar">
              {sidebarHtml ? (
                <div dangerouslySetInnerHTML={{ __html: sidebarHtml }} />
              ) : (
                /* Only if the module can't be fetched at all — keeps the real
                   offer strip visible rather than rendering an empty column. */
                <a href={`${navigationData.header.cta.orderNowUrl}?code=EXTRA25`} className="block">
                  <Image
                    src="/images/service-offer-strip.png"
                    alt="Seasonal offer: up to 56% off with code EXTRA25"
                    width={340}
                    height={340}
                    className="w-full h-auto rounded-xl shadow-sm"
                  />
                </a>
              )}
            </aside>
          </div>
        </div>
      </div>
    </div>
  );
}
