<x-layouts.site>
    <x-slot:title>True Cost of a Loan</x-slot:title>
    <x-slot:description>Before you borrow: see the real total cost of any loan, interest, fees and the monthly burden, in your own currency.</x-slot:description>

    <div class="relative bg-mesh" x-data="loanCost()" 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="receipt" class="h-9 w-9" /></span>
                <h1 class="mt-4 font-display text-display-sm font-bold text-navy-900" data-hero-item>True Cost of a Loan</h1>
                <p class="mt-3 text-lg text-navy-600" data-hero-item>The lender shows you the monthly payment. We show you what it actually costs.</p>
                <div class="mt-5 flex justify-center" data-hero-item><x-currency-picker /></div>
                <x-tool-intro slug="loan-cost" title="True Cost of a Loan"
                    tagline="The lender shows the monthly payment. We show what the loan really costs you."
                    :steps="[
                        'Enter the loan amount, interest rate and term.',
                        'See the total interest and the true all-in cost.',
                        'Read the verdict on whether it is worth it.',
                        'Download the report before you sign anything.',
                    ]" />
            </div>

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

                    <div>
                        <div class="flex items-baseline justify-between">
                            <label class="text-sm font-semibold text-navy-700">Annual interest rate</label>
                            <span class="font-display text-xl font-extrabold text-wise-600" x-text="rate + '%'"></span>
                        </div>
                        <input type="range" min="3" max="120" step="0.5" x-model.number="rate" @input="recalc()" class="slider mt-2">
                        <p class="mt-1 text-xs text-navy-400">Bank ~13-25% · SACCO ~12% · mobile loans often 60-400% annualised</p>
                    </div>

                    <div>
                        <div class="flex items-baseline justify-between">
                            <label class="text-sm font-semibold text-navy-700">Repayment period</label>
                            <span class="font-display text-xl font-extrabold text-wise-600"><span x-text="termLabel()"></span></span>
                        </div>
                        <input type="range" min="1" max="84" step="1" x-model.number="months" @input="recalc()" class="slider mt-2">
                    </div>

                    <div>
                        <div class="flex items-baseline justify-between">
                            <label class="text-sm font-semibold text-navy-700">Upfront fees <span class="text-xs font-normal text-navy-400">(processing, insurance, excise…)</span></label>
                            <span class="font-display text-xl font-extrabold text-wise-600" x-text="fees + '%'"></span>
                        </div>
                        <input type="range" min="0" max="15" step="0.5" x-model.number="fees" @input="recalc()" class="slider mt-2">
                    </div>

                    {{-- Verdict --}}
                    <div class="rounded-2xl p-4 text-sm font-semibold leading-relaxed"
                         :class="verdict.tone === 'good' ? 'bg-emerald-50 text-emerald-800' : (verdict.tone === 'warn' ? 'bg-amber-50 text-amber-800' : 'bg-rose-50 text-rose-700')">
                        <span x-text="verdict.text"></span>
                    </div>
                </div>

                {{-- Results --}}
                <div class="space-y-6">
                    <div class="card overflow-hidden p-0">
                        <div class="bg-navy-900 bg-mesh-dark p-6 text-center">
                            <p class="text-sm font-semibold uppercase tracking-widest text-wise-300">This loan really costs</p>
                            <p class="mt-2 font-display text-4xl font-extrabold text-white" x-text="fmt(totalCost)"></p>
                            <p class="mt-1 text-sm text-navy-200">for <span class="font-bold text-wise-300" x-text="fmt(amount)"></span> in your pocket</p>
                        </div>
                        <div class="grid grid-cols-3 divide-x divide-navy-100 text-center">
                            <div class="p-4">
                                <p class="text-[11px] font-bold uppercase tracking-wide text-navy-400">Monthly payment</p>
                                <p class="mt-1 font-display font-extrabold text-navy-900" x-text="fmt(monthly)"></p>
                            </div>
                            <div class="p-4">
                                <p class="text-[11px] font-bold uppercase tracking-wide text-navy-400">Interest + fees</p>
                                <p class="mt-1 font-display font-extrabold text-rose-600" x-text="fmt(totalCost - amount)"></p>
                            </div>
                            <div class="p-4">
                                <p class="text-[11px] font-bold uppercase tracking-wide text-navy-400">Cost per 100</p>
                                <p class="mt-1 font-display font-extrabold text-navy-900" x-text="per100()"></p>
                            </div>
                        </div>
                    </div>

                    <div class="card p-6">
                        <h2 class="font-display font-bold text-navy-900">Where every coin goes</h2>
                        <div class="mx-auto mt-3 max-w-[15rem]"><canvas id="loanChart" height="220"></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">Take it to the negotiation.</p>
                        </div>
                        <button @click="busy = true; window.downloadToolPdf('loan-cost', 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: '', 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 analysis</h2>
                        <template x-if="!saved">
                            <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>
                        </template>
                        <p x-show="error" x-text="error" class="mt-2 text-sm font-medium text-rose-600"></p>
                        <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. Borrow with your eyes open.</p>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

            return {
                cf,
                amount: Math.round(200000 * cf),
                rate: 18,
                months: 24,
                fees: 3,
                monthly: 0,
                totalCost: 0,
                chart: null,
                verdict: { tone: 'good', text: '' },

                fmt(v) { return window.MW.fmt(v); },
                termLabel() {
                    const y = Math.floor(this.months / 12), m = this.months % 12;
                    return (y ? y + ' yr' + (y > 1 ? 's ' : ' ') : '') + (m ? m + ' mo' : (y ? '' : '0 mo'));
                },
                per100() {
                    const ratio = this.amount > 0 ? (this.totalCost / this.amount) * 100 : 0;
                    return Math.round(ratio);
                },

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

                recalc() {
                    const r = this.rate / 100 / 12;
                    const n = this.months;
                    this.monthly = r > 0
                        ? this.amount * r * Math.pow(1 + r, n) / (Math.pow(1 + r, n) - 1)
                        : this.amount / n;

                    const feeAmount = this.amount * this.fees / 100;
                    this.totalCost = this.monthly * n + feeAmount;

                    const premium = (this.totalCost - this.amount) / this.amount * 100;
                    this.verdict = premium < 15
                        ? { tone: 'good', text: 'Reasonable. You repay about ' + Math.round(premium) + '% on top, sane territory if the loan builds an asset or income.' }
                        : premium < 45
                            ? { tone: 'warn', text: 'Expensive. You repay ' + Math.round(premium) + '% on top of what you borrow. Negotiate the rate, shorten the term, or shop around.' }
                            : { tone: 'bad', text: 'Danger zone: you repay ' + Math.round(premium) + '% on top. Unless this is a true emergency, this loan eats your future. Walk away or restructure.' };

                    this.drawChart(feeAmount);
                },

                drawChart(feeAmount) {
                    const ctx = document.getElementById('loanChart');
                    if (!ctx || !window.Chart) return;
                    if (this.chart) this.chart.destroy();

                    this.chart = new Chart(ctx, {
                        type: 'doughnut',
                        data: {
                            labels: ['You receive', 'Interest', 'Fees'],
                            datasets: [{
                                data: [this.amount, Math.max(0, this.monthly * this.months - this.amount), feeAmount],
                                backgroundColor: ['#58b9e6', '#1c2b5f', '#f59e0b'],
                                borderWidth: 3,
                                borderColor: '#fff',
                            }],
                        },
                        options: {
                            cutout: '62%',
                            plugins: {
                                legend: { position: 'bottom', labels: { usePointStyle: true, boxHeight: 7, font: { size: 11 } } },
                                tooltip: { callbacks: { label: (i) => i.label + ': ' + window.MW.fmt(i.raw) } },
                            },
                        },
                    });
                },

                pdfPayload() {
                    return {
                        highlight: { value: this.fmt(this.totalCost), label: 'True total cost of borrowing ' + this.fmt(this.amount) },
                        sections: [
                            {
                                title: 'The loan',
                                rows: [
                                    ['Amount borrowed', this.fmt(this.amount)],
                                    ['Annual interest rate', this.rate + '%'],
                                    ['Term', this.termLabel()],
                                    ['Upfront fees', this.fees + '% (' + this.fmt(this.amount * this.fees / 100) + ')'],
                                ],
                            },
                            {
                                title: 'The truth',
                                rows: [
                                    ['Monthly payment', this.fmt(this.monthly)],
                                    ['Total you will repay', this.fmt(this.totalCost)],
                                    ['Interest + fees (the cost)', this.fmt(this.totalCost - this.amount)],
                                    ['You repay per 100 borrowed', String(this.per100())],
                                ],
                            },
                        ],
                        note: 'Golden rule: borrow for things that grow in value or earn income. Compare at least three offers, this PDF makes the comparison honest. moneywise.co.ke/tools/loan-cost',
                    };
                },

                savePlan(email = null) {
                    return fetch('{{ route('tools.save', 'loan-cost') }}', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
                        body: JSON.stringify({
                            email,
                            label: 'Loan cost analysis',
                            inputs: { amount: this.amount, rate: this.rate, months: this.months, fees: this.fees, currency: window.MW.code() },
                            outputs: { monthly: Math.round(this.monthly), totalCost: Math.round(this.totalCost) },
                        }),
                    });
                },
            };
        }
    </script>
    @endpush
</x-layouts.site>
