"use client";

import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { useScrollSpy } from "@/hooks/useScrollSpy";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";

const sections = [
    { id: "summary",       title: "Plain English Summary" },
    { id: "acceptance",    title: "1. Acceptance of Terms" },
    { id: "purpose",       title: "2. Purpose of the Website" },
    { id: "accounts",      title: "3. User Accounts" },
    { id: "payments",      title: "4. Payments & Refunds" },
    { id: "registrations", title: "5. Registrations & Tickets" },
    { id: "acceptable",    title: "6. Acceptable Use" },
    { id: "communication", title: "7. Communication" },
    { id: "intellectual",  title: "8. Intellectual Property" },
    { id: "liability",     title: "9. Limitation of Liability" },
    { id: "forcemajeure",  title: "10. Force Majeure" },
    { id: "termination",   title: "11. Termination of Access" },
    { id: "law",           title: "12. Governing Law" },
    { id: "contact",       title: "13. Contact" },
];

export default function TermsOfUsePage() {
    const activeId = useScrollSpy(sections.map((s) => s.id));
    const { settings } = useSiteSettings();

    const orgName       = settings.org_name          || "Hope Family Church";
    const orgEmail      = settings.org_email         || "admin@hopehenley.co.za";
    const websiteUrl    = settings.legal_website_url || "events.hopehenley.co.za";
    const operatorName  = settings.legal_operator_name || "Joshua Oosthuizen on behalf of Hope Family Church, Henley-on-Klip, South Africa";
    const effectiveDate = settings.legal_effective_date || "April 2026";

    return (
        <div className="min-h-screen flex flex-col bg-gray-50">
            <Navbar />
            <main className="flex-1 max-w-6xl mx-auto px-6 py-12 grid grid-cols-1 lg:grid-cols-[250px_1fr] gap-10">
                {/* Sidebar */}
                <aside className="hidden lg:block text-sm text-gray-600 space-y-2 self-start sticky top-24 h-fit">
                <h3 className="font-semibold text-gray-800 mb-3">On this page</h3>
                    <ul className="space-y-2 border-l border-gray-300 pl-3">
                        {sections.map((section) => (
                            <li key={section.id}>
                                <a
                                    href={`#${section.id}`}
                                    className={`block hover:text-blue-600 transition-colors ${
                                        activeId === section.id ? "text-blue-600 font-semibold" : ""
                                    }`}
                                >
                                    {section.title}
                                </a>
                            </li>
                        ))}
                    </ul>
                </aside>

                {/* Main Content */}
                <article className="bg-white rounded-2xl shadow p-8 text-gray-700 leading-relaxed">
                    <h1 className="text-4xl font-bold text-blue-700 mb-2">Terms of Use</h1>
                    <p className="text-sm text-gray-500 mb-6">Effective Date: {effectiveDate}</p>

                    <div className="border-l-4 border-blue-600 pl-4 mb-8 text-gray-700">
                        <p>
                            <strong>Website:</strong>{" "}
                            <a href={`https://${websiteUrl}`} className="text-blue-600 hover:underline">
                                {websiteUrl}
                            </a>
                        </p>
                        <p><strong>Owned and operated by:</strong> {operatorName}</p>
                    </div>

                    <section id="summary" className="mb-10">
                        <h2 className="text-2xl font-semibold text-blue-600 mb-4">🟢 Plain English Summary</h2>
                        <p>Welcome to {orgName}! This site helps you book and pay for events hosted or supported by {orgName}.</p>
                        <p>By using it, you agree to:</p>
                        <ul className="list-disc ml-6 space-y-1">
                            <li>Use the platform responsibly and only for legitimate event participation.</li>
                            <li>Provide accurate information during registration and payments.</li>
                            <li>Keep your login details safe.</li>
                            <li>Respect that under 18s need parental permission to register.</li>
                            <li>Understand that all payments go through Yoco, and we don&apos;t store your card details.</li>
                            <li>Accept that we may contact you via email and/or WhatsApp (based on your preference) about events you register for, your tickets, and account security alerts.</li>
                            <li>Understand that registrations are personal to you and non-transferable.</li>
                            <li>If we cancel an event, you&apos;ll get a full refund on request or your registration moved to the new date.</li>
                        </ul>
                        <p className="mt-2">If you disagree with these terms, please don&apos;t use the site.</p>
                    </section>

                    {sections.slice(1).map((section) => (
                        <Section key={section.id} id={section.id} title={section.title}
                            orgName={orgName} orgEmail={orgEmail} />
                    ))}
                </article>
            </main>
            <Footer />
        </div>
    );
}

function Section({
    id, title, orgName, orgEmail,
}: {
    id: string;
    title: string;
    orgName: string;
    orgEmail: string;
}) {
    const content: Record<string, string[]> = {
        acceptance: [
            `By accessing or using the platform, you agree to be bound by these Terms of Use and any policies referenced herein.`,
            `${orgName} ('we', 'our', or 'us') reserves the right to modify these terms at any time. Updated versions will be posted on this page with a new effective date.`,
        ],
        purpose: [
            `The platform is designed to:`,
            `• Allow users to view, register, and pay for events hosted or co-hosted by ${orgName}.`,
            `• Manage event registration details, communication, and participation records.`,
            `The site may also provide updates or communication related to events.`,
        ],
        accounts: [
            "You must create an account to register for certain events or access restricted features.",
            "You are responsible for keeping your password secure.",
            "Passwords are encrypted and not accessible to any staff member.",
            "Users under the age of 18 must only register or create an account with the consent and supervision of a parent or guardian.",
            "You agree to provide accurate, current, and complete information when creating your account.",
            `Accounts may also be created on your behalf by an administrator (e.g. for walk-in event registration). In this case, you will receive a WhatsApp message with an activation link if your mobile number is provided.`,
        ],
        payments: [
            "Payments are processed securely through Yoco, a third-party payment processor.",
            `${orgName} does not store or process credit card information.`,
            "Payment confirmations and receipts are issued electronically.",
            "All prices are listed in South African Rand (ZAR) unless stated otherwise.",
            "Where an event permits it, partial payments may be made. A minimum payment of R15 applies per transaction. The outstanding balance must be settled before your registration can be considered fully paid.",
            "Early-bird pricing: Certain events offer reduced 'early-bird' prices for a limited time or while a limited number of places are available. Early-bird prices are locked in at the time of registration, provided that payment is completed before the stated early-bird deadline. If payment is not completed before the deadline, the early-bird price is forfeited and the standard price applies. Early-bird availability is subject to both time limits and stock limits; once the allocated places are filled, the early-bird tier closes regardless of the deadline. By registering at an early-bird price, you acknowledge these conditions.",
            `Refund Policy: Refunds are handled on a per-event basis. As a baseline, if you are unable to attend an event you have paid for, please contact us at ${orgEmail} at least 48 hours before the event. Refund requests at this stage are at the discretion of the event organiser. No refunds will be issued for no-shows. Any event-specific refund terms will be communicated at the time of registration and take precedence over this baseline.`,
        ],
        registrations: [
            `Registrations and tickets are personal to the registered individual and are non-transferable unless explicitly authorised by ${orgName} in writing.`,
            "You may not sell, gift, or pass on your registration to another person without written authorisation.",
            "You may cancel your own registration at any time before any payment has been made. Once a payment has been recorded against your registration, cancellation must be requested through the organisation. Please contact us to arrange this.",
            `If ${orgName} cancels or significantly postpones an event, affected registrants will be notified by email. In this case, a full refund will be issued upon request, or your registration may be transferred to the rescheduled or replacement event — whichever you prefer. Refund requests for organiser-initiated cancellations must be submitted to ${orgEmail} within 30 days of the cancellation notice.`,
        ],
        acceptable: [
            "You agree not to:",
            "• Use the website for any unlawful or fraudulent purpose.",
            "• Impersonate another person or misrepresent your identity.",
            "• Interfere with or disrupt the operation of the site.",
            "• Attempt to gain unauthorised access to our systems.",
            "• Resell, tout, or transfer your registration or tickets without written authorisation.",
            "• Use automated tools, bots, or scrapers to access or extract data from the site.",
        ],
        communication: [
            "By registering, you consent to receive communications related to your registrations, payments, tickets, and account security.",
            "Depending on your notification preference, these may be delivered via email and/or WhatsApp. You can update your preference at any time from the Profile & Security page in your account.",
            "Certain communications are required for the operation of the platform and cannot be opted out of entirely — these include payment confirmations, ticket delivery, and account security alerts (e.g. new login notifications, password resets, and account closure confirmations). Security alerts are always sent via email; WhatsApp delivery is additional when you have opted in.",
            "For accounts without a valid email address (e.g. walk-in or at-the-door registrations), these required communications will be delivered via WhatsApp if a mobile number is on file.",
            "WhatsApp messages are delivered via WAWP, a third-party WhatsApp Business API provider. By enabling WhatsApp notifications, you consent to your mobile number being used to send you messages via this service.",
        ],
        intellectual: [
            `All content on the platform, including text, graphics, and logos, is owned by ${orgName} unless otherwise stated.`,
            "You may not copy, modify, or distribute any content without written permission.",
            `By submitting any content through the platform (such as attendee details or form responses), you grant ${orgName} a limited licence to use that content solely for the purpose of managing your event registration.`,
        ],
        liability: [
            `${orgName} provides this platform on an 'as is' basis. We make no guarantees regarding uninterrupted access or error-free performance.`,
            "We are not liable for any loss or damages arising from:",
            "• Technical failures; or",
            "• Misuse of the platform.",
            "Liability for event cancellations or schedule changes is addressed under section 5 (Registrations & Tickets) and section 10 (Force Majeure).",
        ],
        forcemajeure: [
            `${orgName} shall not be liable for any failure or delay in performing its obligations where such failure or delay results from causes beyond its reasonable control, including but not limited to: acts of God, natural disasters, government restrictions or regulations, public health emergencies, venue closures, or any other event outside our reasonable control ('force majeure event').`,
            `In the event of a force majeure event affecting a scheduled event, ${orgName} will endeavour to reschedule or provide reasonable alternatives where possible. Refunds in force majeure circumstances will be handled at our discretion and communicated to affected registrants as soon as reasonably practicable.`,
        ],
        termination: [
            "We may suspend or terminate access to your account if we believe you have violated these Terms of Use or engaged in behaviour harmful to others or the organisation.",
            `You may delete your own account at any time from the Profile & Security page in your account, or by contacting ${orgEmail}. Upon deletion, your personal data will be handled in accordance with our Privacy Policy.`,
            "Certain data may be retained for legal or financial record-keeping purposes even after account deletion.",
        ],
        law: [
            "These Terms of Use are governed by the laws of the Republic of South Africa.",
        ],
        contact: [
            "For questions or concerns about these Terms, contact:",
            `📧 ${orgEmail}`,
        ],
    };

    return (
        <section id={id} className="mb-10 scroll-mt-24">
            <h3 className="text-xl font-semibold text-blue-600 mb-3">{title}</h3>
            {content[id]?.map((line, i) => {
                if (line.includes("@") && !line.startsWith("•") && (line.includes("📧") || line.endsWith(orgEmail))) {
                    const email = orgEmail;
                    const parts = line.split(email);
                    return (
                        <p key={i} className="mb-2">
                            {parts[0]}
                            <a href={`mailto:${email}`} className="text-blue-600 hover:underline">
                                {email}
                            </a>
                            {parts[1] || ""}
                        </p>
                    );
                }
                return (
                    <p key={i} className="mb-2">
                        {line}
                    </p>
                );
            })}
        </section>
    );
}