"use client";

import React, { useEffect, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { Roboto } from "next/font/google";
import { CalculatorConfig } from "@/types/home";
import type { OrderServiceConfig, PricingConfig } from "@/services/joomlaService";
import type { SubjectOption } from "@/app/api/subjects/route";
import type { PriceQuote } from "@/app/api/price/route";
import serviceJson from "@/data/service-json.json";
import calculatorConstants from "@/data/calculator-constants.json";

// The live templates set these forms in Roboto (regular + "robotomedium");
// scoped to the form so the rest of the app's typography is left alone.
const roboto = Roboto({ subsets: ["latin"], weight: ["400", "500", "700"], display: "swap" });

interface ServiceOrderFormProps {
  config: CalculatorConfig;
  /** Real per-service ordering limits from `JM_assignment_web`. */
  orderConfig: OrderServiceConfig[];
  /** Real site-wide pricing from the Joomla custom fields + central rates. */
  pricing: PricingConfig | null;
  title: string;
  subtitle: string;
  /**
   * "service" is the Services-page banner sidebar (`service.php`'s
   * `.side-bar` widget): a "Prices Start From" block, 12px-radius selects.
   * "sidebar" is the real, separate `.sample-calculator` widget
   * (Samples/Questions/Blog sidebars) — same shape but 3px-radius selects
   * and a simpler one-row `.amount-banner` price display, pixel-measured
   * off the live site rather than approximated from the "service" variant.
   * "home" is the homepage hero form (`default.php`): a compact price
   * banner plus the Ph.D. Writers / Free Plagiarism Report strip.
   */
  variant?: "service" | "sidebar" | "home";
}

/**
 * The real service list the live order form uses: `templates/GAH/js/service-json.json`,
 * copied verbatim to `data/service-json.json`. Each entry is
 * `"Label": [groupId, unit]`.
 *
 * All 25 are listed separately even though several share a `groupId`
 * (id 1 covers Assignment/Coursework/Homework/Term Paper/Personal Statement;
 * id 2 covers Research Paper/Research Proposal/Dissertation/PHD Thesis/
 * Dissertation Proposal; 14 and 5 are shared by two each), so the option list
 * is keyed by label, and the id rides along in a hidden `group_id` input the
 * way the live form posts it.
 */
interface ServiceEntry {
  label: string;
  groupId: number;
  unit: string;
}

const INITIAL_SERVICE_OPTIONS: ServiceEntry[] = Object.entries(
  serviceJson.service[0] as Record<string, (string | number)[]>
).map(([label, [groupId, unit]]) => ({
  label,
  groupId: Number(groupId),
  unit: String(unit),
}));

/**
 * The second field of each entry is the unit the order form counts in, which
 * is what drives the quantity select's wording ("Select Page" vs
 * "Select Slide" ...). Replaces a hardcoded PowerPoint special case.
 */
/**
 * The real deadline slices from `calculator_constants.php` on the Joomla
 * server, exported verbatim to `data/calculator-constants.json`. The keys are
 * the urgency ids the order system itself uses (the template's own AJAX call
 * posts `urgency: 8`, i.e. the 25–30 day slice).
 */
const DAY_SLICES = Object.entries(calculatorConstants.daySlice)
  .map(([id, slice]) => ({ id: Number(id), maxDay: Number(slice.maxday), minDay: Number(slice.minday) }))
  .sort((a, b) => a.maxDay - b.maxDay);

const HOUR_SLICES = Object.entries(calculatorConstants.hoursSlice)
  .map(([id, slice]) => ({ id: Number(id), hours: Number(slice.hours) }))
  .sort((a, b) => a.hours - b.hours);

/**
 * DATA NOT FOUND: nothing in the Joomla database or the templates folder
 * defines the page/quantity options — the live form's list is built by the
 * customer panel at runtime. This range is generated, and is the one part of
 * the form not backed by a real source.
 */
const QUANTITY_STEPS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20];

const UNIT_NOUN: Record<string, string> = {
  "Pages | Words": "Page",
  Slides: "Slide",
  Poster: "Poster",
  Leaflet: "Leaflet",
  "Que. | Word/Que.": "Question",
};

// Shared by every select: the template's `.side-bar .box select` rule
// (14px, #d8d8d8 border, 12px radius, custom down-arrow on the right).
const SELECT_BASE =
  "w-full appearance-none truncate text-sm leading-[18px] border border-[#d8d8d8] py-3 pl-2.5 pr-6 cursor-pointer bg-white bg-no-repeat bg-[position:right_10px_center] bg-[url('/icons/down-arrow.svg')]";
// Services banner sidebar: `.side-bar .box select` (12px radius, #656565 text).
const SELECT_SERVICE = `${SELECT_BASE} rounded-xl text-[#656565]`;
// Homepage: `.slider-section .box select` (3px radius, #2a2a2a text).
const SELECT_HOME = `${SELECT_BASE} rounded-[3px] text-[#2a2a2a]`;
// Samples/Questions/Blog sidebar: `.sample-calculator .box select`
// (3px radius, #2a2a2a text — pixel-measured off the live install).
const SELECT_SIDEBAR = `${SELECT_BASE} rounded-[3px] text-[#2a2a2a]`;

/**
 * Per-service field visibility, replicated from the two (near-identical)
 * `d_service == '...'` branch chains in `calculator3.js`'s
 * `price_calculater_order()`. Only the fields that actually differ from the
 * default (subject + pages both shown) are listed here.
 */
interface ServiceFieldRules {
  hideSubject?: boolean;
  /** Pages dropdown replaced by a plain word-count input. */
  useWordsInput?: boolean;
}

const SERVICE_FIELD_RULES: Record<string, ServiceFieldRules> = {
  "PowerPoint Presentation": { hideSubject: true },
  "Editing | Proofreading": { hideSubject: true, useWordsInput: true },
  "Plagiarism Report": { hideSubject: true, useWordsInput: true },
  "Personal Statement": { hideSubject: true },
  Paraphrasing: { hideSubject: true },
  "Summary Writing": { hideSubject: true },
  Portfolio: { hideSubject: true },
};

/**
 * `group_id == 4` ("Online Exam | Question based test Papers") replaces the
 * pages dropdown with two selects — Number of Questions x Words/Question —
 * and derives the effective page count from them (`ass_select`'s
 * `Math.ceil((no_of_q * no_of_w) / words)`, `words` = 250/page as everywhere
 * else in the calculator).
 */
const QA_GROUP_ID = 4;
const WORDS_PER_PAGE = 250;
const QUESTION_STEPS = Array.from({ length: 49 }, (_, i) => i + 1); // live: `for (i = q_default; i < 50; i++)`, q_default = 1
const WORDS_PER_QUESTION_STEPS = Array.from({ length: 99 }, (_, i) => (i + 1) * 50); // live: 50..4950 step 50

/**
 * The order system auto-selects the last (longest/cheapest) urgency option
 * for these group ids rather than requiring the visitor to pick one —
 * `price_calculater_order`'s `groupIds = [8, 9, 10, 6, 7, 11]` forces
 * `#urgency option:last-child` selected. (8 PowerPoint, 9 Poster, 10 Leaflet,
 * 6 Summary Writing, 7 Portfolio, 11 Resume/CV Services.)
 */
const AUTO_LAST_URGENCY_GROUP_IDS = [8, 9, 10, 6, 7, 11];

function nearestPageCount(value: number, steps: number[]): number {
  // Faithful to `exact_page_count_get`: if nothing in the list is >= value,
  // the live code falls back to 1 rather than the largest option.
  return steps.find((step) => step >= value) ?? 1;
}

/**
 * The order form used in the Services-page sidebar, mirroring the markup and
 * CSS of `.banner_landing_pages .side-bar` in the live `service.php` /
 * `default.php` templates: four selects (services, subject, pages, urgency),
 * a "Prices Start From" / discount price block, and an orange Order Now button.
 *
 * Subject, pages and urgency options and the price maths come from the same
 * real calculator config the homepage uses.
 */
export const ServiceOrderForm: React.FC<ServiceOrderFormProps> = ({
  config,
  orderConfig,
  pricing,
  title,
  subtitle,
  variant = "service",
}) => {

  const isHome = variant === "home";
  const isSidebar = variant === "sidebar";
  const isService = variant === "service";
  const SELECT_CLASS = isHome ? SELECT_HOME : isSidebar ? SELECT_SIDEBAR : SELECT_SERVICE;
  const [serviceOptions, setServiceOptions] = useState<ServiceEntry[]>(INITIAL_SERVICE_OPTIONS);
  const [service, setService] = useState("");
  const [subjectId, setSubjectId] = useState("");
  const [pages, setPages] = useState("");
  const [urgency, setUrgency] = useState("");
  // Q&A flow (`group_id == 4`): questions x words/question, in place of pages.
  const [questionCount, setQuestionCount] = useState("");
  const [wordsPerQuestion, setWordsPerQuestion] = useState("");
  // Editing | Proofreading / Plagiarism Report: a plain word count in place
  // of the pages dropdown (the live form's file-upload word count).
  const [wordsInput, setWordsInput] = useState("");
  // Tracks whether the visitor has touched urgency, so the auto-last-option
  // default (see AUTO_LAST_URGENCY_GROUP_IDS) doesn't fight a manual choice.
  const [urgencyTouched, setUrgencyTouched] = useState(false);

  // Dynamically fetch service categories from /api/services API
  useEffect(() => {
    fetch("/api/services")
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (data?.services && Array.isArray(data.services) && data.services.length > 0) {
          setServiceOptions(data.services);
        }
      })
      .catch(() => {});
  }, []);

  const selectedService = serviceOptions.find((option) => option.label === service);

  /**
   * Real, per-service subjects from the customer panel (`/api/subjects` →
   * `api/get_subjects`) — not a stand-in. Refetched whenever the selected
   * service changes, since the panel scopes the list to it.
   */
  const [subjects, setSubjects] = useState<SubjectOption[]>([]);

  useEffect(() => {
    setSubjectId("");
    if (!selectedService) {
      setSubjects([]);
      return;
    }
    const controller = new AbortController();
    fetch("/api/subjects", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        groupId: selectedService.groupId,
        unitTag: selectedService.unit,
        serviceName: selectedService.label,
      }),
      signal: controller.signal,
    })
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => setSubjects(data?.subjects ?? []))
      .catch(() => setSubjects([]));
    return () => controller.abort();
  }, [selectedService]);

  const selectedSubject = subjects.find((subject) => subject.value === subjectId);

  // Real grouping from the panel's response (`<optgroup>`s in its own HTML),
  // preserving first-seen order rather than sorting alphabetically.
  const subjectGroups: Array<[string | null, SubjectOption[]]> = [];
  for (const subject of subjects) {
    const bucket = subjectGroups.find(([group]) => group === subject.group);
    if (bucket) bucket[1].push(subject);
    else subjectGroups.push([subject.group, [subject]]);
  }

  // Deadline choices come from the CMS's real limit for this service
  // (`max_day_slice`), not an invented ladder. `hours_slice` marks services
  // that can also be ordered in hours. Matching is by name because
  // `JM_assignment_web` names are a coarser set than service-json's labels.
  const serviceLimits =
    orderConfig.find((row) => row.name.toLowerCase() === service.toLowerCase()) ??
    orderConfig.find((row) => row.name.toLowerCase() === "others");
  const assignmentId = serviceLimits?.id;
  const maxDays = serviceLimits?.maxDays ?? 0;

  const [urgencyOptions, setUrgencyOptions] = useState<Array<{ value: string; label: string }>>([]);

  useEffect(() => {
    setUrgency("");
    setPages("");
    setQuestionCount("");
    setWordsPerQuestion("");
    setWordsInput("");
    setUrgencyTouched(false);
    if (!assignmentId || !service) {
      setUrgencyOptions([]);
      return;
    }
    const controller = new AbortController();
    fetch("/api/urgency", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ assignmentId }),
      signal: controller.signal,
    })
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => setUrgencyOptions(data?.urgencies ?? []))
      .catch(() => setUrgencyOptions([]));
    return () => controller.abort();
  }, [assignmentId, service]);

  const deadlineOptions = !service
    ? []
    : urgencyOptions.length > 0
      ? urgencyOptions.map((u) => ({ id: u.value, label: u.label }))
      : [
        ...(serviceLimits?.hoursSlice
          ? HOUR_SLICES.map((slice) => ({ id: String(slice.id), label: `${slice.hours} Hours` }))
          : []),
        ...DAY_SLICES.filter((slice) => slice.maxDay <= maxDays).map((slice) => ({
          id: String(slice.id),
          label: `${slice.maxDay} Day${slice.maxDay > 1 ? "s" : ""}`,
        })),
      ];

  // `groupIds = [8, 9, 10, 6, 7, 11]` in the live script: these services
  // don't ask the visitor to pick a deadline — the longest/cheapest option
  // is auto-selected as soon as the list loads.
  const lastDeadlineId = deadlineOptions.length > 0 ? deadlineOptions[deadlineOptions.length - 1].id : null;
  useEffect(() => {
    if (
      !urgencyTouched &&
      lastDeadlineId &&
      selectedService &&
      AUTO_LAST_URGENCY_GROUP_IDS.includes(selectedService.groupId)
    ) {
      setUrgency(lastDeadlineId);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [lastDeadlineId, selectedService?.groupId]);

  const fieldRules = SERVICE_FIELD_RULES[service] ?? {};
  const isQaService = selectedService?.groupId === QA_GROUP_ID;
  const quantityOptions = !service ? [] : QUANTITY_STEPS;
  const hasSubject = !fieldRules.hideSubject;
  const useWordsInput = !!fieldRules.useWordsInput;
  // Quantity wording follows the selected service's real unit.
  const pageUnit = UNIT_NOUN[selectedService?.unit ?? ""] ?? "Page";

  // Until the visitor picks values the price is the "starts from" figure:
  // one page at the least-urgent (cheapest) deadline.
  const qaPageCount =
    questionCount && wordsPerQuestion
      ? nearestPageCount(
        Math.ceil((Number(questionCount) * Number(wordsPerQuestion)) / WORDS_PER_PAGE),
        QUANTITY_STEPS
      )
      : 1;
  const pageCount = isQaService ? qaPageCount : useWordsInput ? 1 : parseInt(pages) || 1;
  // Editing | Proofreading / Plagiarism Report price by an explicit word
  // count rather than page count * 250 (`form.append('filewords', ...)`'s
  // `$('#filewords').val()` branch).
  const explicitWords = useWordsInput && wordsInput ? Number(wordsInput) : undefined;

  // ModuleHelper's maths, with real inputs:
  //   selected_price = $currency[1].price / currency_value
  //   static_price_value = round(static_price / selected_price, 2)
  //   before_discount    = round(100 * value / (100 - row_discount), 2)
  const rate = pricing?.currencyRates.find((row) => row.country === config.priceCountry);

  const usdBase = Number(calculatorConstants.currency["1"].price);
  const selectedPrice = rate ? usdBase / rate.value : usdBase;
  const staticPrice = pricing?.staticPrice ?? 0;
  const discountPercent = pricing?.discountPercent ?? 0;

  const unitPrice = Math.round((staticPrice / selectedPrice) * 100) / 100;

  /**
   * Live quote from the customer panel (`/api/price`), which is where the real
   * per-selection maths lives — Joomla only ever renders a "starts from"
   * figure. Falls back to that figure until a service and deadline are picked,
   * or if the panel can't be reached.
   */
  const [quote, setQuote] = useState<PriceQuote | null>(null);

  useEffect(() => {
    if (!assignmentId || !urgency) {
      setQuote(null);
      return;
    }
    const controller = new AbortController();
    fetch("/api/price", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        assignmentId,
        page: pageCount,
        urgency,
        serviceGroupId: selectedService?.groupId,
        serviceName: selectedService?.label,
        // Real per-subject surcharge — omitted (not 0) until a subject is
        // actually picked, so the quote reflects "no subject chosen yet"
        // the same way the panel's own default does.
        addonPrice: selectedSubject?.addonPrice,
        words: explicitWords,
      }),
      signal: controller.signal,
    })
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => setQuote(data && !data.error ? data : null))
      .catch(() => setQuote(null));
    return () => controller.abort();
  }, [assignmentId, pageCount, urgency, selectedService, selectedSubject, explicitWords]);

  // The panel answers in USD; the template converts by multiplying by the
  // country's rate, so the same conversion is applied here.
  const conversion = rate?.value ?? 1;
  // `$_SESSION['order_currency']` — the ISO code, not the symbol.
  const currency = rate?.currency ?? "USD";

  const discountedPrice = quote ? quote.totalPrice * conversion : pageCount * unitPrice;
  const fullPrice = quote
    ? quote.totalPriceBeforeDiscount * conversion
    : (100 * discountedPrice) / (100 - discountPercent);
  const discountAmountDisplay = quote ? quote.discountPrice * conversion : null;

  // `turnitin_free_amount()`: a free Turnitin report worth $7.50 (converted)
  // is bundled into every order, folded into the displayed "You Save" total.
  const turnitinCost = 7.5 * conversion;
  const saveAmount = (discountAmountDisplay ?? 0) + turnitinCost;
    
  return (
    <div
      className={`${roboto.className} ${isHome
        ? "text-center rounded-[3px] bg-white shadow-[0_3px_6px_rgba(0,0,0,0.16)] w-full max-w-[360px] mx-auto lg:ml-auto lg:mr-0 shrink-0"
        : isSidebar
          ? "text-center rounded-[3px] bg-white shadow-[0_0_8px_rgba(0,0,0,0.2)]"
          : "text-center rounded-2xl bg-[#F5FFE9] border border-[#5C7A36] shadow-[0_3px_8px_rgba(0,0,0,0.16)] w-full max-w-[420px] mx-auto lg:max-w-none"
        }`}
    >
      <div className={isHome ? "" : isSidebar ? "px-5 pt-2.5" : "px-4 pt-3.5 sm:px-5"}>
        <h2
          className={
            isHome
              ? "px-2 pt-[10px] text-[26px] leading-[30px] font-bold text-slate-700 m-0"
              : isSidebar
                ? "text-[23px] leading-[28px] font-normal text-[#F58E0E] m-0"
                : "text-[22px] sm:text-[26px] leading-[28px] sm:leading-[32px] font-medium text-[#3E3E3E] m-0"
          }
        >
          {title}
        </h2>
        <p
          className={
            isHome
              ? "text-gray-400 text-[15px] leading-[20px]"
              : isSidebar
                ? "text-base leading-[20px] font-normal text-black mt-[11px] mb-5"
                : "text-[14px] sm:text-[15px] leading-[18px] font-normal text-[#616161] mt-1 mb-2"
          }
        >
          {subtitle}
        </p>
      </div>

      <form
        onSubmit={(e) => {
          e.preventDefault();
          window.location.href = config.orderCtaUrl;
        }}
        className={isHome ? "px-[18px] pt-[15px] pb-[15px]" : "p-[15px]"}
      >
        <div className={`relative ${isHome ? "" : "min-h-[236px]"}`}>
          <div className="mb-[15px]">
            <label htmlFor="ass_group_list" className="sr-only">
              Select Services
            </label>
            <select
              id="ass_group_list"
              name="assignment_service"
              value={service}
              onChange={(e) => setService(e.target.value)}
              className={SELECT_CLASS}
            >
              <option value="">
                Select Services
              </option>
              {serviceOptions.map((option) => (
                <option key={option.label} value={option.label}>
                  {option.label}
                </option>
              ))}
            </select>
            {/* The live form posts the numeric service id, which several
                labels share — so it travels separately from the label. */}
            <input type="hidden" name="group_id" value={selectedService?.groupId ?? ""} />
          </div>

          {hasSubject && (
            <div className="mb-[15px]">
              <label htmlFor="assignment_subject" className="sr-only">
                Select Subject
              </label>
              <select
                id="assignment_subject"
                name="subjectId"
                value={subjectId}
                onChange={(e) => setSubjectId(e.target.value)}
                className={SELECT_CLASS}
              >
                <option value="">
                  Select Subject
                </option>
                {subjectGroups.map(([group, groupSubjects]) => (
                  <optgroup key={group ?? "__ungrouped"} label={group ?? ""}>
                    {groupSubjects.map((subject) => (
                      <option key={subject.value} value={subject.value}>
                        {subject.label}
                      </option>
                    ))}
                  </optgroup>
                ))}
              </select>
            </div>
          )}

          {isQaService && (
            <div className="grid grid-cols-2 gap-2.5 mb-[15px]">
              <div>
                <label htmlFor="no_of_q" className="sr-only">
                  Number of Questions
                </label>
                <select
                  id="no_of_q"
                  name="no_of_q"
                  value={questionCount}
                  onChange={(e) => setQuestionCount(e.target.value)}
                  className={SELECT_CLASS}
                >
                  <option value="">Select</option>
                  {QUESTION_STEPS.map((count) => (
                    <option key={count} value={String(count)}>
                      {count} Questions
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label htmlFor="no_of_w" className="sr-only">
                  Words per Question
                </label>
                <select
                  id="no_of_w"
                  name="no_of_w"
                  value={wordsPerQuestion}
                  onChange={(e) => setWordsPerQuestion(e.target.value)}
                  className={SELECT_CLASS}
                >
                  <option value="">Select</option>
                  {WORDS_PER_QUESTION_STEPS.map((count) => (
                    <option key={count} value={String(count)}>
                      {count} Words/Question
                    </option>
                  ))}
                </select>
              </div>
            </div>
          )}

          <div className={`grid gap-2.5 mb-[15px] ${isQaService ? "grid-cols-1" : "grid-cols-2"}`}>
            {useWordsInput ? (
              <div>
                <label htmlFor="filewords" className="sr-only">
                  Number of Words
                </label>
                <input
                  id="filewords"
                  name="filewords"
                  type="number"
                  min={1}
                  step={1}
                  placeholder="Number of Words"
                  value={wordsInput}
                  onChange={(e) => setWordsInput(e.target.value)}
                  className={SELECT_CLASS}
                />
              </div>
            ) : !isQaService ? (
              <div>
                <label htmlFor="pages_count" className="sr-only">
                  Select {pageUnit}
                </label>
                <select
                  id="pages_count"
                  name="pages"
                  value={pages}
                  onChange={(e) => setPages(e.target.value)}
                  className={SELECT_CLASS}
                >
                  <option value="">
                    Select {pageUnit}
                  </option>
                  {quantityOptions.map((count) => (
                    <option key={count} value={String(count)}>
                      {count} {pageUnit}
                      {count > 1 ? "s" : ""}
                    </option>
                  ))}
                </select>
              </div>
            ) : null}
            <div>
              <label htmlFor="urgency" className="sr-only">
                Select Urgency
              </label>
              <select
                id="urgency"
                name="urgency"
                value={urgency}
                onChange={(e) => {
                  setUrgencyTouched(true);
                  setUrgency(e.target.value);
                }}
                className={SELECT_CLASS}
                disabled={!!selectedService && AUTO_LAST_URGENCY_GROUP_IDS.includes(selectedService.groupId)}
              >
                <option value="">
                  Select Urgency
                </option>
                {deadlineOptions.map((option) => (
                  <option key={option.id} value={String(option.id)}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {isSidebar ? (
            /* Real `.amount-banner` — one row, no "Prices Start From"
               label and no discount-icon callout, pixel-measured off the
               live `.sample-calculator` widget. */
            <div className="flex items-center justify-between border-t border-[#ececec] py-[15px]">
              <div className="text-left text-sm leading-4 text-[#707070]">
                <span className="inline-block rounded-[3px] bg-[#2db261] px-1.5 py-0.5 text-white">{discountPercent}% Off</span>{" "}
                <s>{currency} {fullPrice.toFixed(2)}</s>
              </div>
              <p className="m-0 text-xl leading-6 text-[#1d1d1d]">
                {currency} <span className="text-2xl">{discountedPrice.toFixed(2)}</span>
              </p>
            </div>
          ) : isHome ? (
            <div className="flex items-center justify-between border-t border-[#ececec] pb-2.5 pt-[15px] mb-3">
              <div className="text-left text-sm leading-4 font-medium text-[#707070]">
                <span className="rounded-[3px] bg-[#2db261] px-1.5 py-0.5 text-white font-semibold">{discountPercent}% Off</span>{" "}
                <s className="text-[#888888]">{currency} {fullPrice.toFixed(2)}</s>
              </div>
              <p className="m-0 text-xl sm:text-2xl leading-[22px] font-bold text-[#1d1d1d]">
                {currency} <span>{discountedPrice.toFixed(2)}</span>
              </p>
            </div>
          ) : (
            <div className="flex flex-col gap-[7px] border-t border-[#b1b1b1] pt-[15px]">
              <div className="flex items-center justify-between">
                <p className="m-0 text-sm leading-[18px] font-medium text-[#616161]">
                  <span className="text-[#1D1D1D]">Prices</span> Start From
                </p>
                <s className="text-sm leading-[18px] font-medium text-[#E20202]">{currency} {fullPrice.toFixed(2)}</s>
              </div>
              <div className="flex items-center justify-between">
                <div
                  className="flex items-center gap-2 rounded-[7px] p-[7px] text-[#616161] text-left"
                  style={{
                    background:
                      "linear-gradient(116.77deg, rgba(95,125,56,0.1) 5.38%, rgba(131,177,72,0.1) 80.76%)",
                  }}
                >
                  <Image src="/icons/offer-watch.gif" alt="" width={25} height={25} unoptimized className="h-[25px] w-[25px]" />
                  Discount
                  <p className="m-0 rounded-[3px] bg-[#2DB261] px-[7px] py-[3px] text-sm text-white">
                    {discountPercent}% Off
                  </p>
                </div>
                <p className="m-0 text-xl leading-6 text-[#1D1D1D]">
                  {currency} <span>{discountedPrice.toFixed(2)}</span>
                </p>
              </div>
            </div>
          )}

          {/* `turnitin_free_amount()`: a free Turnitin report is bundled
              into every order and folded into the displayed savings. */}
          {quote && (
            <p className="mb-3 text-left text-xs font-medium text-[#5C7A36]">
              You Save {currency} {saveAmount.toFixed(2)}
              <span className="text-[#707070] font-normal">
                {" "}
                (includes a free Turnitin Report worth {currency} {turnitinCost.toFixed(2)})
              </span>
            </p>
          )}
        </div>

        <button
          type="submit"
          className={
            isSidebar
              ? "con_btn w-full text-white font-normal text-[19px] leading-[22px] py-2 rounded-[3px] shadow transition-colors cursor-pointer block"
              : "con_btn w-full text-white font-medium text-xl leading-[22px] py-3 rounded-[3px] shadow transition-colors cursor-pointer mb-3 mt-1 block"
          }
          style={{ backgroundColor: isHome || isService ? "#F58E0E" : "#7F9C34", color: "#ffffff" }}
        >
          Order Now
        </button>
      </form>
      {isSidebar ? <div className="h-[10px]" /> : <br />}

      {/* Real `.footer-sidebar` row (Ph.D. Writers / FREE Plagiarism
          Report) — confirmed against the live `service.php`: the
          `.side-bar` widget's form (`isService`) closes right after its
          `.con_btn` with no `.footer-sidebar` following it at all — that
          row only exists on the homepage's own banner form. */}
      {!isService && (
        <div
          className={
            isHome
              ? "flex justify-between rounded-[3px] bg-[#f1f1f1] px-[15px] pt-[20px] pb-[1px] text-left shadow-[0_0_6px_rgba(0,0,0,0.16)]"
              : "flex justify-between border-t border-[#ececec] px-[15px] py-2.5 text-left"
          }
        >
          <div className="flex items-center gap-2">
            <Image src="/icons/sidebar-writers.svg" alt="" width={36} height={32} className="shrink-0" />
            <Link href="/writers" className="text-[15px] leading-[18px] font-normal text-black">
              <span className="block text-[18px] leading-[15px] font-normal text-[#0E1219]">Ph.D. Writers</span>
              <span className="block text-[13px] leading-[15px] font-normal text-[#0E1219]">For Best Assistance</span>
            </Link>
          </div>
          <div className="flex items-center gap-2">
            <Image src="/icons/sidebar-plagiarism.svg" alt="" width={30} height={30} className="shrink-0" />
            <Link href="/plagiarism-checker" className="text-[15px] leading-[18px] font-normal text-black">
              <span className="block w-fit bg-[#33cc6f] px-[5px] text-sm leading-4 font-normal uppercase text-white">
                Free
              </span>
              <span className="block text-[13px] leading-[15px] font-normal text-[#0E1219]">Plagiarism Report</span>
            </Link>
          </div>
        </div>
      )}
    </div>
  );
};
