"use client";

import { useState } from "react";
import Link from "next/link";
import { decodeHtmlEntities } from "@/lib/pageHelpers";
import { SampleWhatsappStrip } from "@/components/samples/SampleWhatsappStrip";

interface SampleLandingItem {
  id: number;
  alias: string;
  title: string;
  excerpt: string;
  subjectAlias: string;
  pageCount: number;
  downloads: number;
  wordCount: number;
}

function SampleCard({ sample }: { sample: SampleLandingItem }) {
  const href = `/free-samples/${sample.subjectAlias}/${sample.alias}`;
  return (
    <div className="relative bg-white rounded-md shadow-[0_0_4px_rgba(0,0,0,0.25)] px-5 py-3 mb-5">
      <span className="absolute top-2.5 right-0 rounded-l-md bg-[#5C7A36] text-white text-sm px-2.5 py-1">
        Pages : {sample.pageCount}
      </span>
      <Link href={href} className="font-bold text-base text-slate-900 hover:text-[#5C7A36] transition-colors pr-20 block">
        {sample.title}
      </Link>
      <div className="flex items-center gap-3 text-sm text-slate-500 mt-3">
        <span>Downloads: {sample.downloads}</span>
        <span className="text-slate-300">|</span>
        <span>Words: {sample.wordCount}</span>
      </div>
      <p className="text-sm text-slate-600 mt-2 line-clamp-2">{decodeHtmlEntities(sample.excerpt)}</p>
      <Link href={href} className="inline-block mt-2 text-sm font-bold text-[#EF841F] hover:underline">
        View or Download &rarr;
      </Link>
    </div>
  );
}

/**
 * Real sample list for a "sample landing" page, with the live site's own
 * "Next" load-more button (`#load-mode-btn`'s AJAX, same offset-paged
 * `/api/sample-landing` call) and the WhatsApp strip inserted after the
 * 5th result, same as `samplelanding.php`'s `if ($key == 5)`.
 */
export function SampleLandingList({ initialSamples, filter }: { initialSamples: SampleLandingItem[]; filter: number }) {
  const [samples, setSamples] = useState(initialSamples);
  const [loading, setLoading] = useState(false);
  const [exhausted, setExhausted] = useState(initialSamples.length < 10);

  const loadMore = async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/sample-landing?filter=${filter}&offset=${samples.length}`);
      const json = await res.json();
      const more: SampleLandingItem[] = json.data || [];
      setSamples((prev) => [...prev, ...more]);
      if (more.length < 10) setExhausted(true);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      {samples.map((sample, index) => (
        <div key={sample.id}>
          {index === 5 && <SampleWhatsappStrip />}
          <SampleCard sample={sample} />
        </div>
      ))}
      {!exhausted && (
        <div className="flex justify-center mt-2 mb-8">
          <button
            onClick={loadMore}
            disabled={loading}
            className="rounded bg-[#f58e0e] hover:bg-[#e07d0d] disabled:opacity-60 text-white font-bold text-sm px-10 py-2.5 transition-colors"
          >
            {loading ? "Loading..." : "Next"}
          </button>
        </div>
      )}
    </div>
  );
}
