import Seo from '@/components/Seo';
import PlatformLayout from '@/Layouts/PlatformLayout';
import { Link } from '@inertiajs/react';
import { motion, useInView } from 'framer-motion';
import { useRef } from 'react';

const ease = [0.16, 1, 0.3, 1] as const;

function FadeUp({
    children,
    delay = 0,
    className,
}: {
    children: React.ReactNode;
    delay?: number;
    className?: string;
}) {
    const ref = useRef<HTMLDivElement>(null);
    const inView = useInView(ref, { once: true, margin: '-60px' });
    return (
        <motion.div
            ref={ref}
            initial={{ opacity: 0, y: 28 }}
            animate={inView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.65, delay, ease }}
            className={className}
        >
            {children}
        </motion.div>
    );
}

const sections = [
    {
        title: '1. Who we are',
        content: `Upepo Finance Limited ("Upepo Finance", "we", "us", or "our") is a company incorporated in Kenya (registration number PVT-XXXXXX), with registered offices at 14 Westlands Avenue, Nairobi, Kenya. We operate the Upepo Finance platform — a cloud-based operating system for microfinance institutions, SACCOs, and community lenders across East Africa.

This Privacy Policy explains how we collect, use, disclose, and safeguard information about you when you visit our website (upepofinance.com), use our platform, or interact with us in any way.`,
    },
    {
        title: '2. Information we collect',
        content: `**Account and profile data:** When you register for Upepo Finance, we collect your name, email address, phone number, organisation name, and country of operation.

**Billing information:** If you subscribe to a paid plan, we collect billing address and payment method details. Card numbers are processed by our payment processor (Stripe) and are never stored on our servers.

**Platform usage data:** We collect logs of your actions within the platform — pages visited, features used, reports generated — to improve the product and troubleshoot issues.

**End-borrower data:** When you use Upepo Finance to manage your loan portfolio, you upload client data (borrower names, national IDs, contact details, financial records). This data is stored on your behalf. You are the data controller for this information; we are the data processor.

**Communications:** If you contact our support team, we retain records of that correspondence.

**Technical data:** IP addresses, browser type, device type, and session data collected automatically when you use our website or platform.`,
    },
    {
        title: '3. How we use your information',
        content: `We use the information we collect to:

- Provision and operate your Upepo Finance account and tenant portal
- Process payments and manage your subscription
- Send transactional communications (account confirmations, password resets, invoices)
- Provide technical support and resolve issues
- Improve and develop new features of the platform
- Send product update notifications and newsletters (you may opt out at any time)
- Detect, investigate, and prevent fraudulent or unauthorised use
- Comply with applicable legal obligations`,
    },
    {
        title: '4. Legal basis for processing (GDPR & Kenya DPA)',
        content: `For users in the European Economic Area and users subject to the Kenya Data Protection Act 2019, we process your personal data under the following legal bases:

- **Contract performance:** Processing necessary to deliver the services you have subscribed to
- **Legitimate interests:** Platform security, fraud prevention, product improvement
- **Legal obligation:** Compliance with tax laws, anti-money laundering requirements, and regulatory reporting
- **Consent:** Marketing communications (you may withdraw consent at any time)`,
    },
    {
        title: '5. Data storage and security',
        content: `Your data is stored on servers located in Frankfurt, Germany (AWS EU-Central-1) with replication to a secondary availability zone. We encrypt all data at rest using AES-256 and all data in transit using TLS 1.3.

We maintain SOC 2 Type II controls and conduct annual penetration tests. Access to production databases is restricted to a small number of senior engineers and is logged and audited.

We do not sell your data to third parties. We do not use your data for advertising purposes.`,
    },
    {
        title: '6. Data sharing',
        content: `We share your data with:

- **Infrastructure providers:** AWS (hosting), Stripe (payments), Postmark (transactional email). Each is bound by data processing agreements.
- **Analytics:** We use privacy-preserving analytics (no cookies, no cross-site tracking) to understand aggregate platform usage.
- **Legal requirements:** We may disclose data if required to do so by a court order, law enforcement request, or regulatory authority with jurisdiction over our operations.

We do not share your end-borrower data with any third party except where required by law or as explicitly authorised by you.`,
    },
    {
        title: '7. Data retention',
        content: `We retain your account data for as long as your account is active. After account closure:

- Account profile data is deleted within 30 days
- Financial transaction records (invoices, subscription history) are retained for 7 years to meet tax obligations
- End-borrower data uploaded to your tenant portal is retained in read-only mode for 90 days after cancellation, then permanently deleted

You may request earlier deletion of your personal data by contacting privacy@upepofinance.com.`,
    },
    {
        title: '8. Your rights',
        content: `Under the Kenya Data Protection Act 2019 and GDPR (where applicable), you have the right to:

- **Access:** Request a copy of the personal data we hold about you
- **Rectification:** Ask us to correct inaccurate or incomplete data
- **Erasure:** Request deletion of your personal data (subject to legal retention requirements)
- **Portability:** Receive your data in a structured, machine-readable format
- **Restriction:** Ask us to temporarily stop processing your data
- **Object:** Object to processing based on legitimate interests

To exercise any of these rights, email privacy@upepofinance.com. We will respond within 30 days.`,
    },
    {
        title: '9. Cookies',
        content: `Our website uses a minimal set of cookies. We do not use advertising or cross-site tracking cookies. See our Cookie Policy for full details.`,
    },
    {
        title: '10. Changes to this policy',
        content: `We may update this Privacy Policy from time to time. When we make material changes, we will notify you by email and display a banner on the platform at least 14 days before the changes take effect. The date of the last update is shown at the top of this page.`,
    },
    {
        title: '11. Contact us',
        content: `For privacy enquiries, contact our Data Protection Officer at:

**Email:** privacy@upepofinance.com
**Post:** Data Protection Officer, Upepo Finance Limited, 14 Westlands Avenue, Nairobi, Kenya`,
    },
];

export default function Privacy() {
    return (
        <PlatformLayout>
            <Seo
                title="Privacy Policy"
                description="Read Upepo Finance's privacy policy — how we collect, use, and protect your data."
            />

            {/* Hero */}
            <section className="relative overflow-hidden pt-32 pb-16">
                <div className="pf-container relative z-10 mx-auto max-w-3xl text-center">
                    <FadeUp delay={0.1}>
                        <h1 className="pf-display text-foreground mb-4 text-4xl font-bold md:text-5xl">
                            Privacy Policy
                        </h1>
                    </FadeUp>
                    <FadeUp delay={0.2}>
                        <p className="text-muted-foreground text-sm">
                            Last updated: 1 January 2025
                        </p>
                    </FadeUp>
                </div>
            </section>

            {/* Table of contents + body */}
            <section className="pf-section">
                <div className="pf-container">
                    <div className="mx-auto grid max-w-5xl grid-cols-1 gap-12 lg:grid-cols-[240px_1fr]">
                        {/* TOC */}
                        <aside className="hidden lg:block">
                            <div className="sticky top-24">
                                <p className="text-muted-foreground mb-4 text-[10px] font-semibold tracking-widest uppercase">
                                    Contents
                                </p>
                                <nav className="space-y-1">
                                    {sections.map((s) => (
                                        <a
                                            key={s.title}
                                            href={`#${s.title.replace(/\s+/g, '-').toLowerCase()}`}
                                            className="text-muted-foreground hover:text-primary block py-0.5 text-xs transition-colors"
                                        >
                                            {s.title}
                                        </a>
                                    ))}
                                </nav>
                            </div>
                        </aside>

                        {/* Content */}
                        <div className="space-y-12">
                            {sections.map((section, i) => (
                                <FadeUp key={section.title} delay={i * 0.03}>
                                    <div
                                        id={section.title
                                            .replace(/\s+/g, '-')
                                            .toLowerCase()}
                                    >
                                        <h2 className="text-foreground mb-4 text-xl font-bold">
                                            {section.title}
                                        </h2>
                                        <div className="text-muted-foreground space-y-3 text-sm leading-relaxed">
                                            {section.content
                                                .split('\n\n')
                                                .map((para, pi) => (
                                                    <p key={pi}>
                                                        {para
                                                            .split(
                                                                /(\*\*[^*]+\*\*)/,
                                                            )
                                                            .map((part, ti) =>
                                                                part.startsWith(
                                                                    '**',
                                                                ) ? (
                                                                    <strong
                                                                        key={ti}
                                                                        className="text-foreground font-semibold"
                                                                    >
                                                                        {part.slice(
                                                                            2,
                                                                            -2,
                                                                        )}
                                                                    </strong>
                                                                ) : (
                                                                    part
                                                                ),
                                                            )}
                                                    </p>
                                                ))}
                                        </div>
                                        {i < sections.length - 1 && (
                                            <div className="border-border mt-12 border-t" />
                                        )}
                                    </div>
                                </FadeUp>
                            ))}
                        </div>
                    </div>
                </div>
            </section>

            {/* Related legal */}
            <section className="pf-section pf-section-tint">
                <div className="pf-container mx-auto max-w-3xl">
                    <p className="text-muted-foreground mb-4 text-sm font-semibold">
                        Related legal documents
                    </p>
                    <div className="flex flex-wrap gap-3">
                        <Link
                            href="/terms"
                            className="pf-btn-ghost rounded-xl px-4 py-2 text-sm"
                        >
                            Terms &amp; Conditions
                        </Link>
                        <Link
                            href="/cookies"
                            className="pf-btn-ghost rounded-xl px-4 py-2 text-sm"
                        >
                            Cookie Policy
                        </Link>
                    </div>
                </div>
            </section>
        </PlatformLayout>
    );
}
