// @File: src/pages/RefundPolicy.tsx
// @Desc: Refund Policy page. Renders the content of
//        /workspace/uploads/paste-text (3).txt as well-formatted sections
//        with a sticky TOC on large screens and a mobile jump-to dropdown.
//        Provides a Print / Download PDF button using window.print().
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Printer, ChevronDown, Download, FileText, Clock } from "lucide-react";
import SiteLayout from "@/components/SiteLayout";

interface Section {
  id: string;
  number: string;
  title: string;
  body: Array<
    | { kind: "p"; text: string }
    | { kind: "ul"; items: string[] }
    | { kind: "note"; text: string }
  >;
}

const EFFECTIVE_DATE = "April 30, 2026";

const SECTIONS: Section[] = [
  {
    id: "overview",
    number: "1",
    title: "Overview",
    body: [
      {
        kind: "p",
        text: "This Refund Policy governs all payments made to DoItEasy for digital services, including hosting, cloud, domains, and managed services.",
      },
      {
        kind: "p",
        text: "By purchasing our services, you agree to this policy.",
      },
    ],
  },
  {
    id: "eligibility",
    number: "2",
    title: "Eligibility for Refunds (New Subscriptions Only)",
    body: [
      {
        kind: "p",
        text: "Refunds apply only to new service subscriptions and are subject to the following conditions:",
      },
      {
        kind: "ul",
        items: [
          "Refund requests must be submitted within 7 days (recommended: 7–14 days based on your business model) from the initial purchase date",
          "The service must be first-time activation (not a renewal, upgrade, or migration)",
          "The service must not have been fully consumed, abused, or heavily utilized",
        ],
      },
      {
        kind: "p",
        text: "After this period, the service is considered accepted and non-refundable.",
      },
    ],
  },
  {
    id: "non-refundable",
    number: "3",
    title: "Non-Refundable Services",
    body: [
      {
        kind: "p",
        text: "The following services are strictly non-refundable:",
      },
      {
        kind: "ul",
        items: [
          "Domain registration, transfer, or renewal",
          "SSL certificates",
          "Software licenses",
          "Setup fees or one-time configuration services",
          "Dedicated servers and custom infrastructure deployments",
          "Third-party services or API-based services (e.g., WhatsApp API, SMS, external integrations)",
        ],
      },
      {
        kind: "note",
        text: "This aligns with global digital service practices and irreversible provisioning costs.",
      },
    ],
  },
  {
    id: "renewals",
    number: "4",
    title: "No Refunds for Renewals",
    body: [
      {
        kind: "ul",
        items: [
          "All renewal payments are non-refundable",
          "It is the client's responsibility to cancel services before the renewal date",
        ],
      },
      {
        kind: "p",
        text: "This complies with standard SaaS subscription models and Saudi e-commerce transparency requirements.",
      },
    ],
  },
  {
    id: "service-violations",
    number: "5",
    title: "Service Violations (Strict Policy)",
    body: [
      {
        kind: "p",
        text: "No refunds will be issued if the service is suspended or terminated due to violations, including:",
      },
      {
        kind: "ul",
        items: [
          "Spam or bulk email abuse",
          "Hosting phishing or malicious content",
          "Network abuse or attacks",
          "Violation of Acceptable Use Policy (AUP)",
        ],
      },
      {
        kind: "p",
        text: "This includes cases where:",
      },
      {
        kind: "ul",
        items: [
          "IP addresses are blacklisted",
          "Abuse complaints are received from providers (e.g., Hetzner, OVH)",
        ],
      },
    ],
  },
  {
    id: "cancellation",
    number: "6",
    title: "Cancellation Policy",
    body: [
      {
        kind: "ul",
        items: [
          "Clients may cancel services at any time via the client portal",
          "Cancellation does not automatically guarantee a refund",
          "Services remain active until the end of the billing cycle unless terminated earlier",
        ],
      },
    ],
  },
  {
    id: "refund-method",
    number: "7",
    title: "Refund Method",
    body: [
      {
        kind: "ul",
        items: [
          "Approved refunds will be issued using the original payment method where possible",
          "Processing time: 5–14 business days depending on payment provider",
          "Any transaction fees or gateway charges may be deducted",
        ],
      },
    ],
  },
  {
    id: "chargebacks",
    number: "8",
    title: "Chargebacks & Disputes",
    body: [
      {
        kind: "p",
        text: "Initiating a chargeback without contacting DoItEasy first may result in:",
      },
      {
        kind: "ul",
        items: [
          "Immediate service suspension",
          "Account termination",
        ],
      },
      {
        kind: "p",
        text: "We encourage resolving disputes through our support channels.",
      },
    ],
  },
  {
    id: "saudi-compliance",
    number: "9",
    title: "Compliance with Saudi Regulations",
    body: [
      {
        kind: "p",
        text: "In accordance with Saudi Arabia E-Commerce Law:",
      },
      {
        kind: "ul",
        items: [
          "Customers have the right to clear refund terms before purchase",
          "Digital services may be exempt from refunds once delivered or activated",
          "Providers may define fair usage and refund conditions transparently",
        ],
      },
    ],
  },
  {
    id: "exceptional-cases",
    number: "10",
    title: "Exceptional Cases",
    body: [
      {
        kind: "p",
        text: "Refunds may be considered outside this policy only if:",
      },
      {
        kind: "ul",
        items: [
          "There is a proven technical failure from our side",
          "The service was not delivered as described",
          "A billing error occurred",
        ],
      },
      {
        kind: "note",
        text: "Such cases are reviewed individually by management.",
      },
    ],
  },
  {
    id: "policy-updates",
    number: "11",
    title: "Policy Updates",
    body: [
      {
        kind: "p",
        text: "DoItEasy reserves the right to update this policy at any time. Updates will be published on the website.",
      },
    ],
  },
];

const META_DESC =
  "This Refund Policy governs all payments made to DoItEasy for digital services, including hosting, cloud, domains, and managed services. Review eligibility, non-refundable items, and our compliance with Saudi regulations.";

export default function RefundPolicy() {
  const [active, setActive] = useState<string>(SECTIONS[0].id);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    const prevTitle = document.title;
    document.title = "Refund Policy | DoItEasy";

    const ensureMeta = (name: string) => {
      let el = document.querySelector<HTMLMetaElement>(`meta[name="${name}"]`);
      if (!el) {
        el = document.createElement("meta");
        el.name = name;
        document.head.appendChild(el);
      }
      return el;
    };
    const descEl = ensureMeta("description");
    const prevDesc = descEl.content;
    descEl.content = META_DESC.slice(0, 160);

    let canonical = document.querySelector<HTMLLinkElement>(
      'link[rel="canonical"]'
    );
    const created = !canonical;
    if (!canonical) {
      canonical = document.createElement("link");
      canonical.rel = "canonical";
      document.head.appendChild(canonical);
    }
    const prevHref = canonical.href;
    canonical.href = `${window.location.origin}/refund-policy`;

    return () => {
      document.title = prevTitle;
      descEl.content = prevDesc;
      if (created && canonical?.parentNode) {
        canonical.parentNode.removeChild(canonical);
      } else if (canonical) {
        canonical.href = prevHref;
      }
    };
  }, []);

  useEffect(() => {
    const handler = () => {
      const offsets = SECTIONS.map((s) => {
        const el = document.getElementById(s.id);
        if (!el) return { id: s.id, top: Number.POSITIVE_INFINITY };
        return { id: s.id, top: el.getBoundingClientRect().top };
      });
      const above = offsets.filter((o) => o.top <= 140);
      const current = above.length ? above[above.length - 1].id : SECTIONS[0].id;
      setActive(current);
    };
    window.addEventListener("scroll", handler, { passive: true });
    handler();
    return () => window.removeEventListener("scroll", handler);
  }, []);

  const jumpTo = (id: string) => {
    const el = document.getElementById(id);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 100;
      window.scrollTo({ top, behavior: "smooth" });
    }
    setMobileOpen(false);
  };

  const handlePrint = () => window.print();

  const activeLabel = useMemo(() => {
    const s = SECTIONS.find((x) => x.id === active) || SECTIONS[0];
    return `${s.number}. ${s.title}`;
  }, [active]);

  return (
    <SiteLayout>
      <style>{`
        @media print {
          header, footer, .no-print { display: none !important; }
          main { margin: 0 !important; padding: 0 !important; }
          .print-container { max-width: 100% !important; }
          .prose { font-size: 11pt; line-height: 1.55; }
          h1 { font-size: 20pt; }
          h2 { font-size: 14pt; page-break-after: avoid; }
          section { page-break-inside: avoid; }
          a { color: inherit; text-decoration: none; }
          body { background: white !important; }
        }
      `}</style>

      {/* HERO */}
      <section className="relative bg-gradient-to-br from-[#0b6e3e] via-[#0e5a35] to-[#083a22] text-white overflow-hidden no-print">
        <div className="absolute inset-0 opacity-10 pointer-events-none">
          <div className="absolute -top-32 -left-20 w-96 h-96 rounded-full bg-[#f5c400] blur-3xl" />
          <div className="absolute -bottom-40 -right-20 w-[500px] h-[500px] rounded-full bg-white blur-3xl" />
        </div>
        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 md:py-20">
          <div className="flex items-center gap-2 text-xs text-white/70 mb-4">
            <Link to="/" className="hover:text-white">
              Home
            </Link>
            <span>/</span>
            <span className="text-white">Refund Policy</span>
          </div>
          <h1 className="text-3xl md:text-5xl font-extrabold tracking-tight mb-3 truncate">
            Refund Policy
          </h1>
          <p className="text-sm md:text-base text-white/85 max-w-3xl truncate">
            Please read our refund terms carefully{" "}
            <span className="mx-1 text-[#f5c400]">✦</span> Effective{" "}
            {EFFECTIVE_DATE}
          </p>
          <div className="mt-6 flex flex-wrap gap-3">
            <button
              type="button"
              onClick={handlePrint}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[#f5c400] text-slate-900 font-semibold text-sm hover:bg-yellow-400 transition shadow-md"
            >
              <Printer className="w-4 h-4" /> Print / Download PDF
            </button>
            <a
              href="#toc"
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border-2 border-white/40 !bg-transparent hover:!bg-white/10 text-white font-semibold text-sm transition"
            >
              <FileText className="w-4 h-4" /> Jump to sections
            </a>
          </div>
        </div>
      </section>

      {/* BODY */}
      <section className="bg-slate-50 py-10 md:py-14 print-container">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 grid grid-cols-1 lg:grid-cols-12 gap-8">
          {/* Mobile jump-to dropdown */}
          <div className="lg:hidden col-span-1 no-print">
            <div className="bg-white rounded-xl border border-slate-200 shadow-sm">
              <button
                type="button"
                onClick={() => setMobileOpen((v) => !v)}
                className="w-full flex items-center justify-between px-4 py-3 text-sm font-semibold text-slate-800"
              >
                <span className="flex items-center gap-2">
                  <FileText className="w-4 h-4 text-[#0b6e3e]" />
                  Jump to section:{" "}
                  <span className="text-[#0b6e3e]">{activeLabel}</span>
                </span>
                <ChevronDown
                  className={`w-4 h-4 transition ${
                    mobileOpen ? "rotate-180" : ""
                  }`}
                />
              </button>
              {mobileOpen && (
                <div className="border-t border-slate-100 max-h-72 overflow-y-auto">
                  {SECTIONS.map((s) => (
                    <button
                      key={s.id}
                      type="button"
                      onClick={() => jumpTo(s.id)}
                      className={`w-full text-left px-4 py-2 text-sm hover:bg-slate-50 transition ${
                        active === s.id
                          ? "text-[#0b6e3e] font-semibold bg-emerald-50"
                          : "text-slate-700"
                      }`}
                    >
                      {s.number}. {s.title}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Sticky TOC (desktop) */}
          <aside
            id="toc"
            className="hidden lg:block lg:col-span-4 xl:col-span-3 no-print"
          >
            {/* Sticky TOC — no inner `overflow-y-auto` wrapper so the
                mouse-wheel is never trapped inside the sidebar. */}
            <div className="sticky top-24">
              <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-5">
                <h3 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-3 flex items-center gap-2">
                  <FileText className="w-3.5 h-3.5" /> Table of Contents
                </h3>
                <nav className="space-y-1 pr-2">
                  {SECTIONS.map((s) => (
                    <button
                      key={s.id}
                      type="button"
                      onClick={() => jumpTo(s.id)}
                      className={`w-full text-left px-3 py-2 rounded-lg text-sm transition ${
                        active === s.id
                          ? "bg-emerald-50 text-[#0b6e3e] font-semibold border-l-2 border-[#0b6e3e]"
                          : "text-slate-600 hover:bg-slate-50 hover:text-slate-900 border-l-2 border-transparent"
                      }`}
                    >
                      <span className="text-xs font-mono text-slate-400 mr-2">
                        {s.number}.
                      </span>
                      {s.title}
                    </button>
                  ))}
                </nav>
                <div className="border-t border-slate-100 mt-4 pt-4">
                  <button
                    type="button"
                    onClick={handlePrint}
                    className="w-full inline-flex items-center justify-center gap-2 px-3 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#0a4027] transition"
                  >
                    <Download className="w-3.5 h-3.5" /> Download PDF
                  </button>
                </div>
              </div>
            </div>
          </aside>

          {/* Main content */}
          <article className="col-span-1 lg:col-span-8 xl:col-span-9">
            <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 md:p-10">
              <div className="flex items-center gap-2 text-xs text-slate-500 mb-6 pb-4 border-b border-slate-100">
                <Clock className="w-3.5 h-3.5" />
                Last updated: <strong>{EFFECTIVE_DATE}</strong>
              </div>

              <div className="prose prose-slate max-w-4xl">
                <h1 className="text-2xl md:text-3xl font-extrabold text-slate-900 !mb-2">
                  DoItEasy Refund Policy
                </h1>
                <p className="text-slate-600 text-sm md:text-base !mt-0 !mb-8">
                  This policy explains when refunds apply, which services are
                  non-refundable, and how to request a refund. It applies to all
                  clients of DoItEasy, whether individuals or organizations.
                </p>

                {SECTIONS.map((section) => (
                  <section
                    key={section.id}
                    id={section.id}
                    className="scroll-mt-28 mb-10"
                  >
                    <h2 className="!text-xl md:!text-2xl !font-bold text-slate-900 !mb-3 flex items-baseline gap-3">
                      <span className="text-[#0b6e3e] font-mono text-base md:text-lg">
                        {section.number}.
                      </span>
                      <span>{section.title}</span>
                    </h2>
                    <div className="space-y-3 text-slate-700 leading-relaxed text-sm md:text-base">
                      {section.body.map((block, idx) => {
                        if (block.kind === "p") {
                          return <p key={idx}>{block.text}</p>;
                        }
                        if (block.kind === "ul") {
                          return (
                            <ul
                              key={idx}
                              className="list-disc list-outside pl-5 space-y-1.5 marker:text-[#0b6e3e]"
                            >
                              {block.items.map((it, i) => (
                                <li key={i}>{it}</li>
                              ))}
                            </ul>
                          );
                        }
                        return (
                          <div
                            key={idx}
                            className="border-l-4 border-[#f5c400] bg-yellow-50 rounded-r-lg px-4 py-3 text-sm text-slate-700 italic"
                          >
                            {block.text}
                          </div>
                        );
                      })}
                    </div>
                  </section>
                ))}

                <div className="mt-12 pt-6 border-t border-slate-100 text-sm text-slate-500 space-y-3">
                  <p>
                    See also our{" "}
                    <Link
                      to="/service-terms"
                      className="text-[#0b6e3e] font-semibold hover:underline"
                    >
                      Service Terms
                    </Link>{" "}
                    and{" "}
                    <Link
                      to="/privacy-center"
                      className="text-[#0b6e3e] font-semibold hover:underline"
                    >
                      Privacy Center
                    </Link>
                    .
                  </p>
                  <p>
                    Questions about a refund? Please contact us via our{" "}
                    <Link
                      to="/contact"
                      className="text-[#0b6e3e] font-semibold hover:underline"
                    >
                      Contact page
                    </Link>{" "}
                    or submit a{" "}
                    <Link
                      to="/tickets"
                      className="text-[#0b6e3e] font-semibold hover:underline"
                    >
                      support ticket
                    </Link>
                    .
                  </p>
                </div>
              </div>
            </div>
          </article>
        </div>
      </section>
    </SiteLayout>
  );
}