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. Acceptance of terms',
        content: `By accessing or using the Upepo Finance platform ("the Service"), you agree to be bound by these Terms and Conditions ("Terms"). If you are using the Service on behalf of an organisation, you represent that you have the authority to bind that organisation to these Terms.

If you do not agree to these Terms, you must not use the Service. These Terms govern your use of all Upepo Finance products, websites, and services.`,
    },
    {
        title: '2. Description of service',
        content: `Upepo Finance provides a cloud-based software platform for microfinance institutions, SACCOs, and community lenders. The Service includes loan management, savings management, client management, accounting, HR, and analytics modules, along with APIs and integrations as documented at help.upepofinance.com.

We reserve the right to modify, suspend, or discontinue any aspect of the Service at any time, with reasonable notice to subscribers.`,
    },
    {
        title: '3. Account registration',
        content: `You must provide accurate, complete, and current information when registering for an account. You are responsible for maintaining the confidentiality of your account credentials and for all activity that occurs under your account.

You must notify us immediately at security@upepofinance.com if you suspect unauthorised access to your account. We will not be liable for any loss resulting from unauthorised use of your credentials.

Each subscription is for use by a single organisation. You may not share subscriptions between legally distinct entities.`,
    },
    {
        title: '4. Subscription and payment',
        content: `**Plans and pricing:** Subscription plans and pricing are described at upepofinance.com/pricing. We reserve the right to change pricing with at least 30 days' notice to existing subscribers.

**Billing cycle:** Subscriptions are billed monthly or annually, in advance, depending on the plan selected. Annual subscriptions are non-refundable.

**Payment failure:** If payment fails, your account will enter a grace period of 7 days. After the grace period, access to new record creation will be suspended until payment is received. Your data will not be deleted.

**Taxes:** Prices are exclusive of VAT, withholding tax, and any other applicable taxes. You are responsible for paying all applicable taxes in your jurisdiction.`,
    },
    {
        title: '5. Acceptable use',
        content: `You agree not to use the Service to:

- Process data for any purpose that is illegal under applicable law
- Upload malicious code, viruses, or scripts designed to disrupt or damage the Service
- Attempt to gain unauthorised access to any part of the Service or its related systems
- Use the Service to facilitate money laundering, terrorist financing, or other financial crimes
- Reverse-engineer, decompile, or otherwise attempt to derive the source code of the platform
- Resell or sublicense access to the Service without our express written consent

We reserve the right to suspend or terminate accounts found to be in violation of these terms without refund.`,
    },
    {
        title: '6. Data ownership and processing',
        content: `**Your data:** All data you upload to the Service (client records, financial transactions, documents) remains your property. We process this data on your behalf as a data processor under the Kenya Data Protection Act 2019 and applicable data protection law.

**Data processing agreement:** By accepting these Terms, you enter into a data processing agreement with Upepo Finance. The key terms are: we process data only on your instructions, we implement appropriate security measures, we do not share your data with third parties except as required by law or as described in our Privacy Policy.

**Data portability:** You may export all your data at any time using the built-in export tools. We will also provide a full data export within 30 days of a written request.`,
    },
    {
        title: '7. Service availability and SLA',
        content: `We target 99.9% monthly uptime for the platform, excluding scheduled maintenance windows (notified at least 48 hours in advance) and force majeure events.

**Service credits:** If monthly uptime falls below 99.9%, subscribers on Professional and Enterprise plans are eligible for service credits as follows:
- 99.5%–99.9%: 5% credit on next invoice
- 99.0%–99.5%: 15% credit
- Below 99.0%: 25% credit

Credits are the sole remedy for service unavailability and will not exceed one month's subscription fee.`,
    },
    {
        title: '8. Intellectual property',
        content: `The Upepo Finance platform, including its software, design, documentation, and trademarks, is owned by Upepo Finance Limited and protected by intellectual property law. These Terms do not transfer any ownership of intellectual property to you.

You grant Upepo Finance a limited licence to use your organisation's name and logo to identify you as a customer on our website and marketing materials, unless you opt out by emailing marketing@upepofinance.com.`,
    },
    {
        title: '9. Limitation of liability',
        content: `To the maximum extent permitted by law, Upepo Finance shall not be liable for:

- Indirect, incidental, special, or consequential damages arising from your use of the Service
- Loss of profits, revenue, data, or goodwill
- Any damages arising from third-party integrations (M-Pesa, Airtel Money, etc.)
- Any interruption or loss of the Service

Our total aggregate liability for any claims arising under these Terms shall not exceed the total subscription fees paid by you in the 12 months preceding the claim.

Nothing in these Terms limits liability for death or personal injury caused by negligence, fraud, or any other liability that cannot be limited by law.`,
    },
    {
        title: '10. Termination',
        content: `**By you:** You may cancel your subscription at any time via Settings → Billing. Cancellation takes effect at the end of the current billing period.

**By us:** We may terminate your account immediately if you materially breach these Terms and fail to remedy the breach within 14 days of notice. We may also terminate accounts that are fraudulent, abusive, or pose a security risk.

**Effect of termination:** Upon termination, your access to the Service ceases. Your data is retained in read-only mode for 90 days, during which you may export it. After 90 days, data is permanently deleted.`,
    },
    {
        title: '11. Governing law and disputes',
        content: `These Terms are governed by the laws of Kenya. Any dispute arising from these Terms shall first be subject to good-faith negotiation between the parties. If unresolved after 30 days, disputes shall be submitted to binding arbitration under the rules of the Nairobi Centre for International Arbitration (NCIA), with proceedings conducted in English in Nairobi, Kenya.

Nothing in this clause prevents either party from seeking injunctive relief in any court of competent jurisdiction.`,
    },
    {
        title: '12. Changes to these terms',
        content: `We may update these Terms from time to time. When we make material changes, we will notify you by email and display a banner on the platform at least 30 days before the changes take effect. Continued use of the Service after the effective date constitutes acceptance of the updated Terms.`,
    },
    {
        title: '13. Contact',
        content: `For questions about these Terms, contact us at:

**Email:** legal@upepofinance.com
**Post:** Legal Team, Upepo Finance Limited, 14 Westlands Avenue, Nairobi, Kenya`,
    },
];

export default function Terms() {
    return (
        <PlatformLayout>
            <Seo
                title="Terms & Conditions"
                description="Read Upepo Finance's terms and conditions of service."
            />

            {/* 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">
                            Terms &amp; Conditions
                        </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="/privacy"
                            className="pf-btn-ghost rounded-xl px-4 py-2 text-sm"
                        >
                            Privacy Policy
                        </Link>
                        <Link
                            href="/cookies"
                            className="pf-btn-ghost rounded-xl px-4 py-2 text-sm"
                        >
                            Cookie Policy
                        </Link>
                    </div>
                </div>
            </section>
        </PlatformLayout>
    );
}
