<x-layouts.site>
    <x-slot:title>Compound Growth Visualiser</x-slot:title>
    <x-slot:description>See what consistent monthly investing becomes over time, and the true cost of waiting. Free interactive compound interest visualiser.</x-slot:description>

    <div class="bg-mesh" x-data="growthCalc()" 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="trending-up" class="h-9 w-9" /></span>
                <h1 class="mt-4 font-display text-display-sm font-bold text-navy-900" data-hero-item>Compound Growth Visualiser</h1>
                <p class="mt-3 text-lg text-navy-600" data-hero-item>The eighth wonder of the world, on three sliders. Watch your money make money.</p>
                <div class="mt-5 flex justify-center" data-hero-item><x-currency-picker /></div>
                <x-tool-intro slug="compound-growth" title="Compound Growth Visualiser"
                    tagline="Watch how a little, invested regularly, quietly becomes a lot over time."
                    :steps="[
                        'Set how much you can invest monthly, plus any starting amount.',
                        'Choose how many years to stay invested.',
                        'Pick where the money works: money market, bonds or equities.',
                        'Watch it grow, and toggle the today\'s-money view for inflation.',
                    ]" />
            </div>

            <div class="mt-10 grid gap-6 lg:grid-cols-[1fr,1.2fr]">
                {{-- Inputs --}}
                <div class="space-y-6 lg:sticky lg:top-24 lg:self-start">
                    <div class="card space-y-7 p-6">
                        <div>
                            <div class="flex items-baseline justify-between">
                                <label for="monthly" class="text-sm font-semibold text-navy-700">I can invest monthly</label>
                                <span class="font-display text-xl font-extrabold text-wise-600" x-text="fmt(monthly)"></span>
                            </div>
                            <input id="monthly" type="range" :min="Math.max(1, Math.round(500 * cf))" :max="Math.round(100000 * cf)" :step="Math.max(1, Math.round(500 * cf))" x-model.number="monthly" @input="recalc()" class="slider mt-2">
                        </div>

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

                        <div>
                            <div class="flex items-baseline justify-between">
                                <label for="years" class="text-sm font-semibold text-navy-700">For how long</label>
                                <span class="font-display text-xl font-extrabold text-wise-600"><span x-text="years"></span> years</span>
                            </div>
                            <input id="years" type="range" min="1" max="40" step="1" x-model.number="years" @input="recalc()" class="slider mt-2">
                        </div>

                        <div>
                            <p class="text-sm font-semibold text-navy-700">Where the money works</p>
                            <div class="mt-2 grid grid-cols-3 gap-2">
                                <template x-for="preset in presets" :key="preset.label">
                                    <button @click="rate = preset.rate; recalc()"
                                            :class="rate === preset.rate ? 'ring-wise-500 bg-wise-50 shadow-wise' : 'ring-navy-100'"
                                            class="rounded-2xl bg-white p-3 text-center ring-2 transition">
                                        <span class="mx-auto grid h-9 w-9 place-items-center rounded-xl bg-wise-50 text-wise-600" x-html="preset.svg"></span>
                                        <p class="mt-1.5 text-xs font-bold text-navy-900" x-text="preset.label"></p>
                                        <p class="text-[11px] font-semibold text-navy-400" x-text="'~' + preset.rate + '%/yr'"></p>
                                    </button>
                                </template>
                            </div>
                            <div class="mt-3 flex items-center gap-3">
                                <input type="range" min="1" max="25" step="0.5" x-model.number="rate" @input="recalc()" class="slider flex-1">
                                <span class="w-14 text-right font-display font-extrabold text-wise-600" x-text="rate + '%'"></span>
                            </div>
                            <p class="mt-1 text-xs text-navy-400">Indicative returns, before fees and tax. Not a promise, a planning tool.</p>
                        </div>

                        {{-- Inflation reality check --}}
                        <label class="flex cursor-pointer items-center justify-between rounded-2xl bg-navy-50 px-4 py-3">
                            <span class="flex items-center gap-2.5 text-sm font-semibold text-navy-800">
                                <x-icon name="hourglass" class="h-4 w-4 text-wise-600" />
                                Show in today's money <span class="text-xs font-normal text-navy-400">(7% inflation)</span>
                            </span>
                            <input type="checkbox" x-model="inflation" @change="recalc()"
                                   class="h-5 w-9 cursor-pointer appearance-none rounded-full bg-navy-200 transition-colors checked:bg-wise-500 relative
                                          before:absolute before:left-0.5 before:top-0.5 before:h-4 before:w-4 before:rounded-full before:bg-white before:transition-transform checked:before:translate-x-4">
                        </label>
                    </div>

                    {{-- Cost of waiting --}}
                    <div class="card bg-navy-900 bg-mesh-dark p-6 ring-0">
                        <h2 class="flex items-center gap-2 font-display font-bold text-white"><x-icon name="hourglass" class="h-5 w-5 text-amber-300" /> The cost of waiting</h2>
                        <p class="mt-2 text-sm leading-relaxed text-navy-200">
                            If you wait <strong class="text-wise-300">5 years</strong> to start, your final pot shrinks by
                        </p>
                        <p class="mt-1 font-display text-3xl font-extrabold text-amber-300" x-text="fmt(waitCost)"></p>
                        <p class="mt-1 text-xs text-navy-300">Same monthly amount, same returns, just started later. Time is the ingredient money can't buy back.</p>
                    </div>
                </div>

                {{-- Results --}}
                <div class="space-y-6">
                    <div class="card p-6 text-center">
                        <p class="text-sm font-semibold uppercase tracking-widest text-navy-400">In <span x-text="years"></span> years you'd have</p>
                        <p class="mt-2 font-display text-5xl font-extrabold text-navy-900" x-text="fmt(futureValue)"></p>
                        <p x-show="inflation" x-cloak class="mt-1 text-sm font-bold text-amber-600">
                            ≈ <span x-text="fmt(realValue)"></span> in today's buying power
                        </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 put in</p>
                                <p class="mt-0.5 font-display font-extrabold text-navy-700" x-text="fmt(contributed)"></p>
                            </div>
                            <div class="rounded-2xl bg-wise-50 p-3">
                                <p class="text-[11px] font-bold uppercase tracking-wide text-wise-600">Growth earned</p>
                                <p class="mt-0.5 font-display font-extrabold text-wise-600" x-text="fmt(futureValue - contributed)"></p>
                            </div>
                        </div>
                        <p class="mt-4 flex items-center justify-center gap-1.5 text-sm text-navy-500" x-show="futureValue > contributed * 2">
                            <x-icon name="sparkles" class="h-4 w-4 text-wise-500" />
                            More than <strong x-text="Math.floor(futureValue / Math.max(contributed,1))"></strong>&times; what you put in, that's compounding.
                        </p>
                    </div>

                    <div class="card p-6">
                        <h2 class="font-display font-bold text-navy-900">Your money, working</h2>
                        <div class="mt-3"><canvas id="growthChart" height="230"></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 projection, printable and shareable.</p>
                        </div>
                        <button @click="busy = true; window.downloadToolPdf('compound-growth', 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 plan --}}
                    <div class="card p-6" x-data="{ email: '', saved: 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 projection</h2>
                        <template x-if="!saved">
                            <div>
                                <div class="mt-3 flex gap-2">
                                    @auth
                                        <button @click="saving = true; savePlan().then(() => { saved = 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(() => { saved = true; saving = false })"
                                                class="btn-accent shrink-0" :disabled="saving">
                                            <span x-show="!saving">Email me this</span><span x-cloak x-show="saving">Sending…</span>
                                        </button>
                                    @endauth
                                </div>
                                <p x-show="error" x-text="error" class="mt-2 text-sm font-medium text-rose-600"></p>
                            </div>
                        </template>
                        <template x-if="saved">
                            <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! Now make it real, start this month.</p>
                        </template>
                    </div>
                </div>
            </div>

            {{-- Bridge --}}
            <div class="mt-10 text-center" data-reveal>
                <p class="text-navy-600">Inspired? Learn exactly <em>where</em> to invest for your goals.</p>
                <a href="{{ route('learn') }}" class="btn-primary mt-4">Explore the Investable course</a>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        function growthCalc() {
            const cf = window.MW.factor();

            return {
                cf,
                monthly: Math.round(5000 * cf),
                initial: 0,
                years: 10,
                rate: 9,

                applyCurrency() {
                    const nf = window.MW.factor();
                    const r = nf / this.cf;
                    this.cf = nf;
                    this.monthly = Math.round(this.monthly * r);
                    this.initial = Math.round(this.initial * r);
                    this.recalc();
                },
                presets: [
                    { label: 'Money market', rate: 9, svg: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="h-5 w-5"><line x1="3" x2="21" y1="22" y2="22"/><line x1="6" x2="6" y1="18" y2="11"/><line x1="10" x2="10" y1="18" y2="11"/><line x1="14" x2="14" y1="18" y2="11"/><line x1="18" x2="18" y1="18" y2="11"/><polygon points="12 2 20 7 4 7"/></svg>' },
                    { label: 'Bonds', rate: 13, svg: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="h-5 w-5"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></svg>' },
                    { label: 'Equities', rate: 15, svg: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="h-5 w-5"><path d="M3 3v18h18"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/></svg>' },
                ],
                futureValue: 0,
                contributed: 0,
                waitCost: 0,
                inflation: false,
                inflationRate: 7,
                realValue: 0,
                chart: null,

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

                project(months, initial) {
                    const r = this.rate / 100 / 12;
                    let value = initial;
                    const series = [value];
                    for (let m = 1; m <= months; m++) {
                        value = value * (1 + r) + this.monthly;
                        series.push(value);
                    }
                    return series;
                },

                recalc() {
                    const months = this.years * 12;
                    const series = this.project(months, this.initial);

                    this.futureValue = series[months];
                    this.contributed = this.initial + this.monthly * months;
                    this.realValue = this.futureValue / Math.pow(1 + this.inflationRate / 100, this.years);

                    // Cost of waiting 5 years: invest for (years - 5), not delayed contributions
                    const lateMonths = Math.max(0, (this.years - 5) * 12);
                    const lateSeries = this.project(lateMonths, this.initial);
                    this.waitCost = Math.max(0, this.futureValue - lateSeries[lateMonths]);

                    this.drawChart(series);
                },

                pdfPayload() {
                    return {
                        highlight: { value: window.MW.fmt(this.futureValue), label: 'Projected value after ' + this.years + ' years at ' + this.rate + '% per year' },
                        sections: [
                            {
                                title: 'Your inputs',
                                rows: [
                                    ['Monthly investment', this.fmt(this.monthly)],
                                    ['Starting amount', this.fmt(this.initial)],
                                    ['Time horizon', this.years + ' years'],
                                    ['Assumed annual return', this.rate + '%'],
                                ],
                            },
                            {
                                title: 'The outcome',
                                rows: [
                                    ['Total you put in', this.fmt(this.contributed)],
                                    ['Growth earned', this.fmt(this.futureValue - this.contributed)],
                                    ['In today\'s buying power (7% inflation)', this.fmt(this.realValue)],
                                    ['Cost of waiting 5 years to start', this.fmt(this.waitCost)],
                                ],
                            },
                        ],
                        note: 'Compounding rewards time more than timing. Automate the monthly amount and let the years do the heavy lifting: moneywise.co.ke/tools/compound-growth',
                    };
                },

                drawChart(series) {
                    const ctx = document.getElementById('growthChart');
                    if (!ctx || !window.Chart) return;

                    const yearlyValue = [], yearlyContrib = [], yearlyReal = [], labels = [];
                    for (let y = 0; y <= this.years; y++) {
                        labels.push('Yr ' + y);
                        yearlyValue.push(Math.round(series[y * 12]));
                        yearlyContrib.push(Math.round(this.initial + this.monthly * y * 12));
                        yearlyReal.push(Math.round(series[y * 12] / Math.pow(1 + this.inflationRate / 100, y)));
                    }

                    if (this.chart) this.chart.destroy();

                    const datasets = [
                        {
                            label: 'Total value',
                            data: yearlyValue,
                            fill: true,
                            borderColor: window.brand.sky,
                            backgroundColor: 'rgba(88, 185, 230, 0.18)',
                            tension: 0.35, pointRadius: 0, borderWidth: 3,
                        },
                        {
                            label: 'What you put in',
                            data: yearlyContrib,
                            borderColor: window.brand.navyLight,
                            borderDash: [6, 5],
                            tension: 0.2, pointRadius: 0, borderWidth: 2.5,
                        },
                    ];

                    if (this.inflation) {
                        datasets.push({
                            label: "Today's buying power",
                            data: yearlyReal,
                            borderColor: '#f59e0b',
                            borderDash: [3, 4],
                            tension: 0.35, pointRadius: 0, borderWidth: 2.5,
                        });
                    }

                    this.chart = new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels,
                            datasets,
                        },
                        options: {
                            animation: { duration: 600 },
                            plugins: {
                                legend: { position: 'bottom', labels: { usePointStyle: true, boxHeight: 7 } },
                                tooltip: { callbacks: { label: (i) => i.dataset.label + ': ' + window.brand.kes.format(i.raw) } },
                            },
                            scales: {
                                y: { ticks: { callback: (v) => v >= 1000000 ? (v / 1000000).toFixed(1) + 'M' : window.brand.num.format(v / 1000) + 'k' } },
                                x: { ticks: { maxTicksLimit: 9 } },
                            },
                        },
                    });
                },

                savePlan(email = null) {
                    return fetch('{{ route('tools.save', 'compound-growth') }}', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
                        body: JSON.stringify({
                            email,
                            label: 'Growth projection',
                            inputs: { monthly: this.monthly, initial: this.initial, years: this.years, rate: this.rate, currency: window.MW.code() },
                            outputs: { futureValue: Math.round(this.futureValue), contributed: this.contributed },
                        }),
                    }).then(() => window.celebrate?.());
                },
            };
        }
    </script>
    @endpush
</x-layouts.site>
