<x-layouts.site>
    <x-slot:title>Retirement Readiness</x-slot:title>
    <x-slot:description>Will you join the 80% who retire poor, or the 20% who retire free? Get your readiness score and exact catch-up plan.</x-slot:description>

    <div class="relative bg-mesh" x-data="retireCalc()" x-init="recalc()" @currency-changed.window="applyCurrency()">
        <div class="container-site section">
            <div class="mx-auto max-w-2xl text-center" data-hero>
                <span class="icon-tile mx-auto h-20 w-20 bg-wise-400 text-navy-950 shadow-wise" data-hero-item><x-icon name="landmark" class="h-9 w-9" /></span>
                <h1 class="mt-4 font-display text-display-sm font-bold text-navy-900" data-hero-item>Retirement Readiness</h1>
                <p class="mt-3 text-lg text-navy-600" data-hero-item>80% of Africans retire poor. Three sliders show which side of that line you're on, and how to cross it.</p>
                <div class="mt-5 flex justify-center" data-hero-item><x-currency-picker /></div>
                <x-tool-intro slug="retirement" title="Retirement Readiness"
                    tagline="Find out if you're on track for the retirement you want, and the catch-up plan if not."
                    :steps="[
                        'Enter your age, income and what you have saved.',
                        'Add your current monthly contribution.',
                        'See your readiness score and any projected gap.',
                        'Get the exact monthly amount to stay on track.',
                    ]" />
            </div>

            <div class="mt-10 grid gap-6 lg:grid-cols-2">
                {{-- Inputs --}}
                <div class="card space-y-6 p-6 lg:sticky lg:top-24 lg:self-start">
                    <div class="grid grid-cols-2 gap-5">
                        <div>
                            <div class="flex items-baseline justify-between">
                                <label class="text-sm font-semibold text-navy-700">My age</label>
                                <span class="font-display text-xl font-extrabold text-wise-600" x-text="age"></span>
                            </div>
                            <input type="range" min="18" max="60" step="1" x-model.number="age" @input="recalc()" class="slider mt-2">
                        </div>
                        <div>
                            <div class="flex items-baseline justify-between">
                                <label class="text-sm font-semibold text-navy-700">Retire at</label>
                                <span class="font-display text-xl font-extrabold text-wise-600" x-text="retireAge"></span>
                            </div>
                            <input type="range" :min="age + 1" max="70" step="1" x-model.number="retireAge" @input="recalc()" class="slider mt-2">
                        </div>
                    </div>

                    <div>
                        <div class="flex items-baseline justify-between">
                            <label class="text-sm font-semibold text-navy-700">Saved for retirement so far <span class="text-xs font-normal text-navy-400">(pension + investments)</span></label>
                            <span class="font-display text-xl font-extrabold text-wise-600" x-text="fmt(saved)"></span>
                        </div>
                        <input type="range" min="0" :max="Math.round(20000000 * cf)" :step="Math.max(1, Math.round(50000 * cf))" x-model.number="saved" @input="recalc()" class="slider mt-2">
                    </div>

                    <div>
                        <div class="flex items-baseline justify-between">
                            <label class="text-sm font-semibold text-navy-700">Investing monthly for retirement</label>
                            <span class="font-display text-xl font-extrabold text-wise-600" x-text="fmt(monthly)"></span>
                        </div>
                        <input type="range" min="0" :max="Math.round(200000 * cf)" :step="Math.max(1, Math.round(1000 * cf))" x-model.number="monthly" @input="recalc()" class="slider mt-2">
                    </div>

                    <div>
                        <div class="flex items-baseline justify-between">
                            <label class="text-sm font-semibold text-navy-700">Monthly income I want at retirement <span class="text-xs font-normal text-navy-400">(today's money)</span></label>
                            <span class="font-display text-xl font-extrabold text-wise-600" x-text="fmt(income)"></span>
                        </div>
                        <input type="range" :min="Math.max(1, Math.round(20000 * cf))" :max="Math.round(500000 * cf)" :step="Math.max(1, Math.round(5000 * cf))" x-model.number="income" @input="recalc()" class="slider mt-2">
                    </div>

                    <div>
                        <div class="flex items-baseline justify-between">
                            <label class="text-sm font-semibold text-navy-700">Growth on investments</label>
                            <span class="font-display text-xl font-extrabold text-wise-600" x-text="rate + '%/yr'"></span>
                        </div>
                        <input type="range" min="6" max="16" step="0.5" x-model.number="rate" @input="recalc()" class="slider mt-2">
                    </div>
                </div>

                {{-- Results --}}
                <div class="space-y-6">
                    <div class="card p-8 text-center">
                        <p class="text-sm font-semibold uppercase tracking-widest text-navy-400">Your readiness score</p>
                        {{-- Gauge --}}
                        <div class="relative mx-auto mt-4 w-64">
                            <svg viewBox="0 0 200 120" class="w-full">
                                <path d="M 20 110 A 80 80 0 0 1 180 110" fill="none" stroke="#eef1f9" stroke-width="16" stroke-linecap="round"/>
                                <path d="M 20 110 A 80 80 0 0 1 180 110" fill="none" :stroke="readiness >= 100 ? '#10b981' : (readiness >= 60 ? '#58b9e6' : '#f43f5e')" stroke-width="16" stroke-linecap="round"
                                      stroke-dasharray="251.3"
                                      :stroke-dashoffset="251.3 - (251.3 * Math.min(readiness, 100) / 100)"
                                      style="transition: stroke-dashoffset .8s cubic-bezier(.21,.61,.35,1), stroke .4s"/>
                            </svg>
                            <div class="absolute inset-x-0 bottom-0 pb-1">
                                <span class="font-display text-5xl font-extrabold text-navy-900"><span x-text="Math.min(Math.round(readiness), 999)"></span>%</span>
                            </div>
                        </div>
                        <p class="mt-3 font-display text-lg font-bold" :class="readiness >= 100 ? 'text-emerald-600' : (readiness >= 60 ? 'text-wise-600' : 'text-rose-600')"
                           x-text="readiness >= 100 ? 'On track to retire free' : (readiness >= 60 ? 'Close, one push from freedom' : 'Heading for the 80%, let\'s fix that')"></p>

                        <div class="mx-auto mt-5 grid max-w-sm grid-cols-2 gap-3 text-center">
                            <div class="rounded-2xl bg-navy-50 p-3">
                                <p class="text-[11px] font-bold uppercase tracking-wide text-navy-400">You'll have</p>
                                <p class="mt-0.5 font-display font-extrabold text-navy-700" x-text="fmt(projected)"></p>
                            </div>
                            <div class="rounded-2xl bg-wise-50 p-3">
                                <p class="text-[11px] font-bold uppercase tracking-wide text-wise-600">You'll need</p>
                                <p class="mt-0.5 font-display font-extrabold text-wise-700" x-text="fmt(needed)"></p>
                            </div>
                        </div>

                        <template x-if="readiness < 100">
                            <p class="mt-4 rounded-2xl bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-800">
                                Close the gap: invest <span class="font-display font-extrabold" x-text="fmt(extraNeeded)"></span>/month more,
                                or retire <span class="font-display font-extrabold" x-text="yearsLater"></span> later.
                            </p>
                        </template>
                        <template x-if="readiness >= 100">
                            <p class="mt-4 flex items-center justify-center gap-2 rounded-2xl bg-emerald-50 px-4 py-3 text-sm font-semibold text-emerald-700">
                                <x-icon name="award" class="h-4 w-4" /> Surplus of <span class="font-display font-extrabold" x-text="fmt(projected - needed)"></span>, consider retiring earlier or giving bigger.
                            </p>
                        </template>
                    </div>

                    <div class="card p-6">
                        <h2 class="font-display font-bold text-navy-900">Your path to <span x-text="retireAge"></span></h2>
                        <div class="mt-3"><canvas id="retireChart" height="190"></canvas></div>
                    </div>

                    {{-- PDF --}}
                    <div class="card flex items-center justify-between gap-4 p-6" x-data="{ busy: false }">
                        <div>
                            <h2 class="flex items-center gap-2 font-display font-bold text-navy-900"><x-icon name="download" class="h-5 w-5 text-wise-600" /> PDF report</h2>
                            <p class="mt-1 text-sm text-navy-500">Your full retirement roadmap.</p>
                        </div>
                        <button @click="busy = true; window.downloadToolPdf('retirement', pdfPayload()).then(() => busy = false)"
                                class="btn-primary btn-sm shrink-0" :disabled="busy">
                            <span x-show="!busy">Download</span><span x-cloak x-show="busy">…</span>
                        </button>
                    </div>

                    {{-- Save --}}
                    <div class="card p-6" x-data="{ email: '', saved2: false, saving: false, error: '' }">
                        <h2 class="flex items-center gap-2 font-display font-bold text-navy-900"><x-icon name="mail" class="h-5 w-5 text-wise-600" /> Keep this plan</h2>
                        <template x-if="!saved2">
                            <div class="mt-3 flex gap-2">
                                @auth
                                    <button @click="saving = true; savePlan().then(() => { saved2 = true; saving = false })" class="btn-accent flex-1" :disabled="saving">
                                        <span x-show="!saving">Save to my dashboard</span><span x-cloak x-show="saving">Saving…</span>
                                    </button>
                                @else
                                    <input type="email" x-model="email" placeholder="you@example.com"
                                           class="min-w-0 flex-1 rounded-full border-navy-200 px-4 text-sm focus:border-wise-400 focus:ring-wise-400">
                                    <button @click="if (!email.includes('@')) { error = 'Enter a valid email'; return }; error = ''; saving = true; savePlan(email).then(() => { saved2 = true; saving = false })"
                                            class="btn-accent shrink-0" :disabled="saving">
                                        <span x-show="!saving">Email me my plan</span><span x-cloak x-show="saving">Sending…</span>
                                    </button>
                                @endauth
                            </div>
                        </template>
                        <p x-show="error" x-text="error" class="mt-2 text-sm font-medium text-rose-600"></p>
                        <template x-if="saved2">
                            <p class="mt-2 flex items-center gap-1.5 font-semibold text-emerald-600"><x-icon name="check-circle" class="h-4 w-4" /> Saved, future you says asante.</p>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        function retireCalc() {
            const cf = window.MW.factor();
            const INFLATION = 0.07;
            const WITHDRAW = 0.05; // sustainable annual withdrawal

            return {
                cf,
                age: 30,
                retireAge: 60,
                saved: Math.round(500000 * cf),
                monthly: Math.round(10000 * cf),
                income: Math.round(80000 * cf),
                rate: 11,
                projected: 0,
                needed: 0,
                readiness: 0,
                extraNeeded: 0,
                yearsLater: 0,
                chart: null,

                fmt(v) { return window.MW.fmt(v); },

                applyCurrency() {
                    const nf = window.MW.factor();
                    const r = nf / this.cf;
                    this.cf = nf;
                    this.saved = Math.round(this.saved * r);
                    this.monthly = Math.round(this.monthly * r);
                    this.income = Math.round(this.income * r);
                    this.recalc();
                },

                project(years, monthly) {
                    const r = this.rate / 100 / 12;
                    let v = this.saved;
                    const series = [v];
                    for (let m = 1; m <= years * 12; m++) {
                        v = v * (1 + r) + monthly;
                        if (m % 12 === 0) series.push(v);
                    }
                    return series;
                },

                neededAt(years) {
                    // Desired income inflated to retirement, funded at a safe withdrawal rate
                    const futureIncome = this.income * Math.pow(1 + INFLATION, years);
                    return futureIncome * 12 / WITHDRAW;
                },

                recalc() {
                    if (this.retireAge <= this.age) this.retireAge = this.age + 1;
                    const years = this.retireAge - this.age;

                    const series = this.project(years, this.monthly);
                    this.projected = series[years];
                    this.needed = this.neededAt(years);
                    this.readiness = this.needed > 0 ? this.projected / this.needed * 100 : 0;

                    // Extra monthly to close the gap
                    const r = this.rate / 100 / 12;
                    const n = years * 12;
                    const gap = Math.max(0, this.needed - this.projected);
                    this.extraNeeded = n > 0 ? gap * r / (Math.pow(1 + r, n) - 1) : gap;

                    // Or how many more working years close it
                    let later = 0;
                    while (later < 25) {
                        const y = years + later;
                        if (this.project(y, this.monthly)[y] >= this.neededAt(y)) break;
                        later++;
                    }
                    this.yearsLater = later >= 25 ? '25+ years' : later + ' year' + (later === 1 ? '' : 's');

                    this.drawChart(series, years);
                },

                drawChart(series, years) {
                    const ctx = document.getElementById('retireChart');
                    if (!ctx || !window.Chart) return;
                    if (this.chart) this.chart.destroy();

                    const labels = [];
                    const neededLine = [];
                    for (let y = 0; y <= years; y++) {
                        labels.push('Age ' + (this.age + y));
                        neededLine.push(Math.round(this.neededAt(years)));
                    }

                    this.chart = new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels,
                            datasets: [
                                {
                                    label: 'Your pot',
                                    data: series.map(v => Math.round(v)),
                                    fill: true,
                                    borderColor: window.brand.sky,
                                    backgroundColor: 'rgba(88, 185, 230, 0.16)',
                                    tension: 0.35, pointRadius: 0, borderWidth: 3,
                                },
                                {
                                    label: 'Freedom line',
                                    data: neededLine,
                                    borderColor: '#10b981',
                                    borderDash: [6, 5],
                                    pointRadius: 0, borderWidth: 2.5,
                                },
                            ],
                        },
                        options: {
                            plugins: {
                                legend: { position: 'bottom', labels: { usePointStyle: true, boxHeight: 7 } },
                                tooltip: { callbacks: { label: (i) => i.dataset.label + ': ' + window.MW.fmt(i.raw) } },
                            },
                            scales: {
                                y: { ticks: { callback: (v) => v >= 1000000 ? (v / 1000000).toFixed(1) + 'M' : window.brand.num.format(v / 1000) + 'k' } },
                                x: { ticks: { maxTicksLimit: 8 } },
                            },
                        },
                    });
                },

                pdfPayload() {
                    return {
                        highlight: { value: Math.min(Math.round(this.readiness), 999) + '%', label: 'Retirement readiness at age ' + this.retireAge },
                        sections: [
                            {
                                title: 'Where you are',
                                rows: [
                                    ['Age today / retiring at', this.age + ' / ' + this.retireAge],
                                    ['Saved so far', this.fmt(this.saved)],
                                    ['Investing monthly', this.fmt(this.monthly)],
                                    ['Target income (today\'s money)', this.fmt(this.income) + '/month'],
                                ],
                            },
                            {
                                title: 'The verdict',
                                rows: [
                                    ['Projected pot at retirement', this.fmt(this.projected)],
                                    ['Pot needed for your income', this.fmt(this.needed)],
                                    ['Readiness', Math.round(this.readiness) + '%'],
                                    ['To close the gap', this.readiness >= 100 ? 'Already closed' : this.fmt(this.extraNeeded) + '/month more, or retire ' + this.yearsLater + ' later'],
                                ],
                            },
                        ],
                        note: 'Assumes ' + this.rate + '% annual growth, 7% inflation and a 5% sustainable withdrawal rate. Revisit yearly: moneywise.co.ke/tools/retirement',
                    };
                },

                savePlan(email = null) {
                    return fetch('{{ route('tools.save', 'retirement') }}', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
                        body: JSON.stringify({
                            email,
                            label: 'Retirement plan',
                            inputs: { age: this.age, retireAge: this.retireAge, saved: this.saved, monthly: this.monthly, income: this.income, rate: this.rate, currency: window.MW.code() },
                            outputs: { projected: Math.round(this.projected), needed: Math.round(this.needed), readiness: Math.round(this.readiness) },
                        }),
                    }).then(() => window.celebrate?.());
                },
            };
        }
    </script>
    @endpush
</x-layouts.site>
