// @File: src/pages/ServiceTerms.tsx
// @Desc: Service Terms / Terms of Service page. Renders the content of
//        /workspace/uploads/paste-text (2).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 }
  >;
}

// --- Content derived from /workspace/uploads/paste-text (2).txt ---------
const EFFECTIVE_DATE = "April 30, 2026";

const SECTIONS: Section[] = [
  {
    id: "introduction",
    number: "1",
    title: "Introduction",
    body: [
      {
        kind: "p",
        text: 'These Terms of Service ("Terms") govern the use of services provided by DoItEasy ("Company", "We", "Us"). By using our services, you agree to comply with these Terms.',
      },
      { kind: "p", text: "These Terms are compliant with:" },
      {
        kind: "ul",
        items: [
          "Saudi Arabia E-Commerce Law (2019)",
          "Consumer Protection regulations",
          "International best practices for IT and cloud services",
        ],
      },
    ],
  },
  {
    id: "scope-of-services",
    number: "2",
    title: "Scope of Services",
    body: [
      { kind: "p", text: "DoItEasy provides:" },
      {
        kind: "ul",
        items: [
          "Web Hosting (Shared, VPS, Dedicated)",
          "Cloud & SaaS Services",
          "Domain Registration & Management",
          "Managed IT & Support Services",
          "Communication services (Email, WhatsApp API, SMS)",
        ],
      },
      {
        kind: "p",
        text: "These services fall under electronic service provision governed by Saudi E-Commerce Law.",
      },
    ],
  },
  {
    id: "legal-compliance",
    number: "3",
    title: "Legal Compliance & Business Identity",
    body: [
      { kind: "p", text: "In compliance with Saudi regulations, we ensure:" },
      {
        kind: "ul",
        items: [
          "Clear business identification (name, contact, address)",
          "Valid commercial registration (if applicable)",
          "Transparent communication channels",
        ],
      },
      {
        kind: "note",
        text: "Service providers must disclose identity and contact details on their platform.",
      },
    ],
  },
  {
    id: "account-responsibility",
    number: "4",
    title: "Account Responsibility",
    body: [
      {
        kind: "ul",
        items: [
          "The client is fully responsible for account activity.",
          "You must maintain confidentiality of login credentials.",
          "Unauthorized use must be reported immediately.",
        ],
      },
    ],
  },
  {
    id: "acceptable-use",
    number: "5",
    title: "Acceptable Use Policy (AUP)",
    body: [
      { kind: "p", text: "You agree NOT to use DoItEasy services for:" },
      {
        kind: "ul",
        items: [
          "Spam or unsolicited email campaigns",
          "Phishing, fraud, or illegal activity",
          "Hosting malicious content or malware",
          "Abuse of network resources",
        ],
      },
      { kind: "p", text: "Violation may result in:" },
      {
        kind: "ul",
        items: ["Immediate suspension", "Termination without refund"],
      },
    ],
  },
  {
    id: "payment-billing",
    number: "6",
    title: "Payment & Billing",
    body: [
      {
        kind: "ul",
        items: [
          "All services are billed in advance unless stated otherwise.",
          "Prices include applicable VAT (Saudi Arabia: 15%).",
          "Late payments may result in suspension.",
        ],
      },
      {
        kind: "p",
        text: "We ensure transparent pricing including all fees before contract completion.",
      },
    ],
  },
  {
    id: "service-availability",
    number: "7",
    title: "Service Availability (SLA)",
    body: [
      {
        kind: "ul",
        items: [
          "We aim for high availability (e.g., 99.9%)",
          "Scheduled maintenance may occur with notice",
          "No guarantee of uninterrupted service",
        ],
      },
    ],
  },
  {
    id: "data-protection",
    number: "8",
    title: "Data Protection & Privacy",
    body: [
      {
        kind: "p",
        text: "We strictly comply with Saudi data protection obligations:",
      },
      {
        kind: "ul",
        items: [
          "Customer data is protected and used only for service delivery",
          "Data is NOT shared without consent",
          "Data is retained only as necessary",
        ],
      },
      {
        kind: "note",
        text: "Service providers must protect consumer data and privacy.",
      },
    ],
  },
  {
    id: "consumer-rights",
    number: "9",
    title: "Consumer Rights (Saudi Compliance)",
    body: [
      {
        kind: "p",
        text: "In accordance with Saudi law, customers have the right to:",
      },
      {
        kind: "ul",
        items: [
          "Clear service description before purchase",
          "Transparent pricing and billing",
          "Correct errors in electronic transactions",
          "Submit complaints and receive support",
        ],
      },
    ],
  },
  {
    id: "refund-cancellation",
    number: "10",
    title: "Refund & Cancellation Policy",
    body: [
      {
        kind: "ul",
        items: [
          "Refund eligibility depends on service type",
          "Domain services are non-refundable",
          "Hosting may include limited refund window (e.g., 7–14 days)",
        ],
      },
      {
        kind: "p",
        text: "Customers may cancel services via the client portal.",
      },
      {
        kind: "note",
        text: "For the full, detailed refund terms (eligibility windows, non-refundable services, chargebacks, exceptional cases), see our dedicated Refund Policy page at /refund-policy.",
      },
    ],
  },
  {
    id: "suspension-termination",
    number: "11",
    title: "Suspension & Termination",
    body: [
      {
        kind: "p",
        text: "We reserve the right to suspend or terminate services if:",
      },
      {
        kind: "ul",
        items: [
          "Terms are violated",
          "Abuse or illegal activity is detected",
          "Payment is overdue",
        ],
      },
      {
        kind: "p",
        text: "Saudi authorities may enforce penalties for violations including fines.",
      },
    ],
  },
  {
    id: "limitation-liability",
    number: "12",
    title: "Limitation of Liability",
    body: [
      { kind: "p", text: "DoItEasy is not liable for:" },
      {
        kind: "ul",
        items: [
          "Data loss due to client misconfiguration",
          "Service interruptions beyond control",
          "Third-party failures (datacenters, providers)",
        ],
      },
    ],
  },
  {
    id: "intellectual-property",
    number: "13",
    title: "Intellectual Property",
    body: [
      {
        kind: "ul",
        items: [
          "All systems, branding, and software belong to DoItEasy",
          "Clients retain ownership of their own data",
        ],
      },
    ],
  },
  {
    id: "support-communication",
    number: "14",
    title: "Support & Communication",
    body: [
      {
        kind: "ul",
        items: [
          "Support is provided via ticket system, chat, or email",
          "SLA response times may vary by plan",
          "AI-assisted support may be used",
        ],
      },
    ],
  },
  {
    id: "governing-law",
    number: "15",
    title: "Governing Law",
    body: [
      { kind: "p", text: "These Terms are governed by:" },
      {
        kind: "ul",
        items: [
          "Laws of the Kingdom of Saudi Arabia",
          "Applicable international digital commerce standards",
        ],
      },
      {
        kind: "p",
        text: "Saudi law ensures equal or higher consumer protection compared to traditional commerce.",
      },
    ],
  },
  {
    id: "changes-to-terms",
    number: "16",
    title: "Changes to Terms",
    body: [
      {
        kind: "p",
        text: "We may update these Terms at any time. Continued use of services implies acceptance of updates.",
      },
    ],
  },
];

const META_DESC =
  'These Terms of Service ("Terms") govern the use of services provided by DoItEasy. By using our services, you agree to comply with these Terms. Compliant with Saudi Arabia E-Commerce Law (2019) and international best practices.';

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

  // Set document title, meta description, canonical on mount.
  useEffect(() => {
    const prevTitle = document.title;
    document.title = "Service Terms | 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}/service-terms`;

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

  // Scroll-spy: update active section based on scroll position.
  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>
      {/* Print-friendly CSS: hide layout chrome when printing */}
      <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">Service Terms</span>
          </div>
          <h1 className="text-3xl md:text-5xl font-extrabold tracking-tight mb-3 truncate">
            Service Terms
          </h1>
          <p className="text-sm md:text-base text-white/85 max-w-3xl truncate">
            Please read these 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 Terms of Service (ToS)
                </h1>
                <p className="text-slate-600 text-sm md:text-base !mt-0 !mb-8">
                  These Terms outline your rights and responsibilities when
                  using DoItEasy services. They apply to all clients, whether
                  you are an individual or an organization.
                </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="/refund-policy"
                      className="text-[#0b6e3e] font-semibold hover:underline"
                    >
                      Refund Policy
                    </Link>{" "}
                    and{" "}
                    <Link
                      to="/privacy-center"
                      className="text-[#0b6e3e] font-semibold hover:underline"
                    >
                      Privacy Center
                    </Link>
                    .
                  </p>
                  <p>
                    If you have questions about these Terms, 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>
  );
}