// @File: src/pages/PrivacyCenter.tsx
// @Desc: Privacy Center page. Renders the content of
//        /workspace/uploads/paste-text (4).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,
  Mail,
  ShieldCheck,
} from "lucide-react";
import SiteLayout from "@/components/SiteLayout";

interface Sub {
  heading: string;
  items: string[];
}

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

const EFFECTIVE_DATE = "April 30, 2026";
const PRIVACY_EMAIL = "privacy@doiteasy.net";

const SECTIONS: Section[] = [
  {
    id: "overview",
    number: "1",
    title: "Overview",
    body: [
      {
        kind: "p",
        text: "DoItEasy is committed to protecting your personal data in accordance with:",
      },
      {
        kind: "ul",
        items: [
          "Saudi Arabia Personal Data Protection Law (PDPL)",
          "International privacy best practices",
        ],
      },
      {
        kind: "p",
        text: "This Privacy Center explains how we collect, use, store, and protect your data.",
      },
    ],
  },
  {
    id: "what-data-we-collect",
    number: "2",
    title: "What Data We Collect",
    body: [
      {
        kind: "p",
        text: "We collect only the data necessary to provide our services:",
      },
      {
        kind: "sub",
        subs: [
          {
            heading: "Account & Identity Data",
            items: [
              "Name, company name",
              "Email address, phone number",
              "Billing address and VAT information",
            ],
          },
          {
            heading: "Service Data",
            items: [
              "Hosting services, domains, IP addresses",
              "Server usage, logs, and system activity",
            ],
          },
          {
            heading: "Payment Data",
            items: [
              "Transaction records (no full card storage)",
              "Billing history",
            ],
          },
          {
            heading: "Support & Communication",
            items: [
              "Tickets, chat messages, AI interactions",
              "Email correspondence",
            ],
          },
          {
            heading: "Technical Data",
            items: [
              "IP address, browser, device info",
              "Cookies and session data",
            ],
          },
        ],
      },
    ],
  },
  {
    id: "how-we-use-data",
    number: "3",
    title: "How We Use Your Data",
    body: [
      { kind: "p", text: "We use your data strictly for:" },
      {
        kind: "ul",
        items: [
          "Service provisioning and management",
          "Billing and invoicing (WHMCS)",
          "Customer support and communication",
          "Security monitoring and fraud prevention",
          "Legal and regulatory compliance",
        ],
      },
      { kind: "note", text: "We do not sell or rent your data." },
    ],
  },
  {
    id: "legal-basis",
    number: "4",
    title: "Legal Basis (Saudi PDPL Compliance)",
    body: [
      { kind: "p", text: "We process personal data based on:" },
      {
        kind: "ul",
        items: [
          "Contractual necessity (service delivery)",
          "Legal obligations (tax, compliance)",
          "Legitimate interest (security, fraud prevention)",
          "User consent (marketing, cookies, AI usage where applicable)",
        ],
      },
    ],
  },
  {
    id: "data-sharing",
    number: "5",
    title: "Data Sharing & Third Parties",
    body: [
      { kind: "p", text: "We may share limited data with:" },
      {
        kind: "ul",
        items: [
          "Datacenter providers (e.g., hosting infrastructure)",
          "Payment gateways",
          "Domain registrars",
          "Communication providers (SMS, WhatsApp APIs)",
        ],
      },
      {
        kind: "p",
        text: "All third parties are required to maintain confidentiality and security.",
      },
    ],
  },
  {
    id: "international-transfers",
    number: "6",
    title: "International Data Transfers",
    body: [
      {
        kind: "p",
        text: "Your data may be processed outside Saudi Arabia when required for service delivery.",
      },
      { kind: "p", text: "In such cases:" },
      {
        kind: "ul",
        items: [
          "We ensure appropriate safeguards",
          "We comply with PDPL cross-border transfer requirements",
        ],
      },
    ],
  },
  {
    id: "data-retention",
    number: "7",
    title: "Data Retention",
    body: [
      { kind: "p", text: "We retain data only as long as necessary:" },
      {
        kind: "ul",
        items: [
          "Active accounts: full data retained",
          "Closed accounts: limited retention for legal/compliance",
          "Logs: retained for security and audit purposes",
        ],
      },
    ],
  },
  {
    id: "your-rights",
    number: "8",
    title: "Your Rights (Under Saudi PDPL)",
    body: [
      { kind: "p", text: "You have the right to:" },
      {
        kind: "ul",
        items: [
          "Access your personal data",
          "Request correction or updates",
          "Request deletion (where legally allowed)",
          "Withdraw consent",
          "Request a copy of your data",
        ],
      },
      {
        kind: "p",
        text: "Requests can be submitted via the client portal or support.",
      },
    ],
  },
  {
    id: "cookies",
    number: "9",
    title: "Cookies & Tracking",
    body: [
      { kind: "p", text: "We use cookies to:" },
      {
        kind: "ul",
        items: [
          "Maintain login sessions",
          "Improve performance and usability",
          "Analyze traffic and behavior",
        ],
      },
      {
        kind: "p",
        text: "You can control cookies via your browser settings.",
      },
    ],
  },
  {
    id: "security",
    number: "10",
    title: "Security Measures",
    body: [
      { kind: "p", text: "We implement strong security controls:" },
      {
        kind: "ul",
        items: [
          "Encrypted connections (HTTPS)",
          "Secure authentication (MFA supported)",
          "Access control and role-based permissions",
          "Continuous monitoring and logging",
        ],
      },
    ],
  },
  {
    id: "ai-processing",
    number: "11",
    title: "AI & Automated Processing",
    body: [
      { kind: "p", text: "DoItEasy may use AI systems for:" },
      {
        kind: "ul",
        items: [
          "Chat support assistance",
          "Automated replies and suggestions",
          "Service optimization",
        ],
      },
      { kind: "p", text: "AI systems:" },
      {
        kind: "ul",
        items: [
          "Do not make legally binding decisions",
          "Do not access sensitive data beyond necessity",
          "Are monitored for accuracy and compliance",
        ],
      },
    ],
  },
  {
    id: "breach-notification",
    number: "12",
    title: "Data Breach Notification",
    body: [
      { kind: "p", text: "In case of a data breach:" },
      {
        kind: "ul",
        items: [
          "We will investigate immediately",
          "Affected users will be notified if required",
          "Authorities will be informed as per Saudi regulations",
        ],
      },
    ],
  },
  {
    id: "childrens-data",
    number: "13",
    title: "Children's Data",
    body: [
      {
        kind: "p",
        text: "Our services are not intended for individuals under 18. We do not knowingly collect such data.",
      },
    ],
  },
  {
    id: "data-requests",
    number: "14",
    title: "Contact & Data Requests",
    body: [
      { kind: "p", text: "For privacy-related requests:" },
      {
        kind: "ul",
        items: [
          "Use the client portal (recommended)",
          `Or contact: ${PRIVACY_EMAIL}`,
        ],
      },
    ],
  },
  {
    id: "policy-updates",
    number: "15",
    title: "Updates to Privacy Policy",
    body: [
      {
        kind: "p",
        text: "We may update this Privacy Center from time to time. Updates will be published on this page.",
      },
    ],
  },
];

const META_DESC =
  "DoItEasy is committed to protecting your personal data in accordance with Saudi Arabia Personal Data Protection Law (PDPL) and international privacy best practices. Learn how we collect, use, store, and protect your data.";

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

  useEffect(() => {
    const prevTitle = document.title;
    document.title = "Privacy Center | 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}/privacy-center`;

    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; }
          h3 { font-size: 12pt; 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">Privacy Center</span>
          </div>
          <h1 className="text-3xl md:text-5xl font-extrabold tracking-tight mb-3 truncate">
            Privacy Center
          </h1>
          <p className="text-sm md:text-base text-white/85 max-w-3xl truncate">
            Your privacy, your control{" "}
            <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>
            <a
              href="#data-requests"
              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"
            >
              <ShieldCheck className="w-4 h-4" /> Submit a data request
            </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 — NOTE: no inner `overflow-y-auto` / `max-h`
                wrapper. A scrollable inner container here would trap the
                mouse-wheel and prevent the main page from scrolling
                when the cursor is over the TOC. We let the whole sidebar
                scroll with the page instead. */}
            <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 space-y-2">
                  <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>
                  <a
                    href={`mailto:${PRIVACY_EMAIL}`}
                    className="w-full inline-flex items-center justify-center gap-2 px-3 py-2 rounded-lg border border-[#0b6e3e] text-[#0b6e3e] text-sm font-semibold hover:bg-emerald-50 transition"
                  >
                    <Mail className="w-3.5 h-3.5" /> Email Privacy Team
                  </a>
                </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 Privacy Center
                </h1>
                <p className="text-slate-600 text-sm md:text-base !mt-0 !mb-8">
                  How we collect, use, store and protect your personal data,
                  aligned with Saudi Arabia's Personal Data Protection Law
                  (PDPL) and international privacy best practices.
                </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>
                          );
                        }
                        if (block.kind === "sub") {
                          return (
                            <div key={idx} className="space-y-4 mt-2">
                              {block.subs.map((sub, i) => (
                                <div key={i}>
                                  <h3 className="!text-base md:!text-lg !font-semibold text-slate-900 !mt-0 !mb-2">
                                    {sub.heading}
                                  </h3>
                                  <ul className="list-disc list-outside pl-5 space-y-1.5 marker:text-[#0b6e3e]">
                                    {sub.items.map((it, j) => (
                                      <li key={j}>{it}</li>
                                    ))}
                                  </ul>
                                </div>
                              ))}
                            </div>
                          );
                        }
                        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>
                ))}

                {/* Data request contact block */}
                <div className="mt-10 rounded-2xl border border-emerald-200 bg-emerald-50/60 p-6">
                  <div className="flex items-start gap-4">
                    <div className="w-10 h-10 rounded-full bg-[#0b6e3e] text-white flex items-center justify-center shrink-0">
                      <ShieldCheck className="w-5 h-5" />
                    </div>
                    <div className="flex-1">
                      <h3 className="!text-base md:!text-lg !font-bold text-slate-900 !mt-0 !mb-1">
                        Need to submit a data request?
                      </h3>
                      <p className="text-sm text-slate-700 !mt-0 !mb-3">
                        To access, correct, delete, export your data, or
                        withdraw consent, please contact our privacy team. Most
                        requests can be handled directly inside the client
                        portal.
                      </p>
                      <div className="flex flex-wrap gap-3">
                        <a
                          href={`mailto:${PRIVACY_EMAIL}`}
                          className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[#0b6e3e] text-white font-semibold text-sm hover:bg-[#0a4027] transition"
                        >
                          <Mail className="w-4 h-4" /> {PRIVACY_EMAIL}
                        </a>
                        <Link
                          to="/client"
                          className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-[#0b6e3e] text-[#0b6e3e] font-semibold text-sm hover:bg-white transition"
                        >
                          <ShieldCheck className="w-4 h-4" /> Open client portal
                        </Link>
                        <Link
                          to="/tickets"
                          className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-slate-300 text-slate-700 font-semibold text-sm hover:bg-white transition"
                        >
                          <FileText className="w-4 h-4" /> Submit a ticket
                        </Link>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="mt-10 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="/refund-policy"
                      className="text-[#0b6e3e] font-semibold hover:underline"
                    >
                      Refund Policy
                    </Link>
                    .
                  </p>
                  <p>
                    Questions about your privacy? Reach us via the{" "}
                    <Link
                      to="/contact"
                      className="text-[#0b6e3e] font-semibold hover:underline"
                    >
                      Contact page
                    </Link>{" "}
                    or open a{" "}
                    <Link
                      to="/tickets"
                      className="text-[#0b6e3e] font-semibold hover:underline"
                    >
                      support ticket
                    </Link>
                    .
                  </p>
                </div>
              </div>
            </div>
          </article>
        </div>
      </section>
    </SiteLayout>
  );
}