import { Package, Users, Star, MessageSquareQuote } from "lucide-react";
import type { JoomlaArticle, OfferEvent, OfferListItem } from "@/services/joomlaService";
import type { NavigationResponse } from "@/types/navigation";
import { Breadcrumb } from "@/components/common/Breadcrumb";
import { OffersList, AnimatedCount, type OfferCardData } from "@/components/offers/OffersInteractive";
import {
  CHECK_ICON_SVG,
  FEATURE_LI_ICON_SVG,
  AFFILIATE_ARROW_SVG,
  TOP_SERVICE_FEATURES,
} from "@/components/offers/offersIcons";

interface OffersPageViewProps {
  article: JoomlaArticle;
  navigationData: NavigationResponse;
  offers: OfferListItem[];
  offerEvent: OfferEvent | null;
}

/** `offers.php`: `$offer->discount_type == 3 ? "A" : ($offer->discount_type == 1 ? "%" : "$")`. */
function formatDiscountBadge(discount: number, discountType: number): string {
  const rounded = Math.round(discount);
  const symbol = discountType === 3 ? "A" : discountType === 1 ? "%" : "$";
  return `${rounded}${symbol}`;
}

/**
 * The CMS description stores literal entities (`we&rsquo;ll`). Rendered as a
 * plain React text node (not `dangerouslySetInnerHTML`), those never get
 * decoded by the browser, so without this they show up as visible
 * `&rsquo;`/`&amp;rsquo;` text instead of the real quote mark.
 */
function decodeHtmlEntities(text: string): string {
  const named: Record<string, string> = {
    amp: "&",
    lt: "<",
    gt: ">",
    quot: '"',
    apos: "'",
    nbsp: " ",
    ldquo: "“",
    rdquo: "”",
    lsquo: "‘",
    rsquo: "’",
    mdash: "—",
    ndash: "–",
    hellip: "…",
  };
  return text
    .replace(/&#(\d+);/g, (_m, code) => String.fromCharCode(Number(code)))
    .replace(/&#x([0-9a-fA-F]+);/g, (_m, code) => String.fromCharCode(parseInt(code, 16)))
    .replace(/&([a-zA-Z]+);/g, (m, name) => named[name] ?? m);
}

/** `strip_tags($description)` then `substr(..., 0, 150)` — same as `offers.php`. */
function truncateDescription(html: string): { text: string; hasMore: boolean } {
  const text = decodeHtmlEntities(
    html
      .replace(/<[^>]*>/g, " ")
      .replace(/\s+/g, " ")
      .trim()
  );
  if (text.length <= 150) return { text, hasMore: false };
  return { text: text.slice(0, 150), hasMore: true };
}

/**
 * `/offers` — entirely template-driven (`offers.php` + `offers.css`, copied
 * to `app/css/offers.css`), real coupon cards from the central `coupons`
 * table (`joomlaService.getAllOffers()`) and a seasonal banner/strip from
 * the central `crm_offers` table (`joomlaService.getOfferEvent()`), both
 * live per request — not hardcoded, so an admin changing either in the CMS
 * shows up here without a code change. Stat counters (orders/writers/
 * rating/reviews) are the one exception: the live template hardcodes those
 * literal numbers in its own inline `<script>`, not sourced from any DB
 * table, so matching it exactly means keeping them hardcoded too.
 */
export function OffersPageView({ article, navigationData, offers, offerEvent }: OffersPageViewProps) {
  const cartUrl = navigationData.header.cta.cartUrl;
  const orderNowUrl = navigationData.header.cta.orderNowUrl;

  const offerCards: OfferCardData[] = offers.map((offer) => {
    const { text, hasMore } = truncateDescription(offer.description);
    return {
      id: offer.id,
      name: decodeHtmlEntities(offer.name),
      code: offer.code,
      discountLabel: formatDiscountBadge(offer.discount, offer.discountType),
      truncatedDescription: text,
      hasMore,
      fullDescriptionHtml: offer.description,
      cartUrl: `${cartUrl}?code=`,
    };
  });

  // The real DB row's `offer_strip_mobile_image` path has a folder typo
  // (`images/seasonal-offer/seasonal-offer/...` — the file actually lives
  // alongside the other seasonal assets, `images/dynamic-offers/<campaign>/`).
  // Derived from the (correct) desktop strip path's own folder instead of
  // trusting the stored value, so this self-corrects for whichever seasonal
  // campaign is active, not just this one.
  const stripMobilePath = offerEvent
    ? `${offerEvent.offerStripImage.slice(0, offerEvent.offerStripImage.lastIndexOf("/"))}/${offerEvent.offerStripMobileImage.slice(offerEvent.offerStripMobileImage.lastIndexOf("/") + 1)}`
    : null;

  const orderWithCode = (code: string) => `${orderNowUrl}?code=${encodeURIComponent(code)}`;

  return (
    <section className="offer-page">
      <div className="container">
        <Breadcrumb items={[{ label: article.title }]} />

        {offerEvent && (
          <section className="christmas-banner">
            <div className="container">
              <a href={orderWithCode(offerEvent.offerCode)} id="offer-link">
                <img
                  src={`/${offerEvent.offerImage}`}
                  alt={offerEvent.offerName}
                  width="100%"
                  height="100%"
                  id="offer-d-img"
                  className="hidden md:block"
                />
                <img
                  src={`/${offerEvent.offerMobileImage}`}
                  alt={offerEvent.offerName}
                  width="100%"
                  height="100%"
                  id="offer-m-img"
                  className="block md:hidden"
                />
              </a>
            </div>
          </section>
        )}

        <div className="offer-inner-block">
          <div className="offerlist">
            <OffersList
              offers={offerCards}
              insertBefore={
                offerCards.length > 1
                  ? {
                      index: 1,
                      content: (
                        <>
                          <div className="afffiliate-partner">
                            <div className="detail">
                              <p className="title">
                                Start Earning <span>By</span> Sharing
                              </p>
                              <p className="sub-title">Through Our Affiliate Program!</p>
                              <figure className="partner-img-mob">
                                <img src="/images/affiliate-partner.png" alt="partner image" height="100%" width="100%" />
                              </figure>
                              <a href="/affiliate" className="check-Out-btn">
                                Know More!
                                <span dangerouslySetInnerHTML={{ __html: AFFILIATE_ARROW_SVG }} />
                              </a>
                            </div>
                            <figure className="partner-img">
                              <img src="/images/affiliate-partner.png" alt="partner image" height="100%" width="100%" />
                            </figure>
                          </div>

                          {offerEvent && stripMobilePath && (
                            <>
                              <a href={orderWithCode(offerEvent.offerCode)} className="offer-img" id="link-o-d">
                                <img src={`/${offerEvent.offerStripImage}`} height="100%" width="100%" alt={offerEvent.offerName} className="loading" id="ofr-strip-d" />
                              </a>
                              <a href={orderWithCode(offerEvent.offerCode)} className="offer-img-mobile" id="link-o-m">
                                <img src={`/${stripMobilePath}`} height="100%" width="100%" alt={offerEvent.offerName} id="ofr-strip-m" />
                              </a>
                            </>
                          )}
                        </>
                      ),
                    }
                  : undefined
              }
            />
          </div>

          <div className="right-block">
            <div className="feature-list">
              <p className="feature-head">
                <span dangerouslySetInnerHTML={{ __html: CHECK_ICON_SVG }} />
                Our Top 6 Services
              </p>
              <ul className="feature-li">
                {TOP_SERVICE_FEATURES.map((feature) => (
                  <li key={feature}>
                    <span dangerouslySetInnerHTML={{ __html: FEATURE_LI_ICON_SVG }} />
                    {feature}
                  </li>
                ))}
              </ul>
            </div>
            {/* The real template's 4 stat icons are large multi-gradient
                illustrations (copied verbatim everywhere else this app
                touches `offers.php`); extracting them cleanly needs more
                care than this pass allowed, so these use plain Lucide icons
                as a placeholder — visually different from the live site. */}
            <div className="overview">
              <div className="list">
                <Package aria-hidden className="w-[42px] h-[42px]" color="#5C7A36" />
                <p>
                  <span className="counts">
                    <AnimatedCount id="total-order" start={78900} end={78938} />+
                  </span>
                  <span className="counts-msg">Delivered Write-Ups</span>
                </p>
              </div>
              <div className="list">
                <Users aria-hidden className="w-[42px] h-[42px]" color="#5C7A36" />
                <p>
                  <span className="counts">
                    <AnimatedCount id="total-writers" start={2200} end={2252} />+
                  </span>
                  <span className="counts-msg">Subject Experts</span>
                </p>
              </div>
              <div className="list">
                <Star aria-hidden className="w-[42px] h-[42px]" color="#5C7A36" />
                <p>
                  <span className="counts">4.8/5</span>
                  <span className="counts-msg">Customer Ratings</span>
                </p>
              </div>
              <div className="list">
                <MessageSquareQuote aria-hidden className="w-[42px] h-[42px]" color="#5C7A36" />
                <p>
                  <span className="counts">
                    <AnimatedCount id="total-reviews" start={5700} end={5768} />
                  </span>
                  <span className="counts-msg">Authentic Reviews</span>
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
