<x-layouts.site>
    <x-slot:title>Emergency Fund Calculator</x-slot:title>
    <x-slot:description>How many months could you survive if income stopped? Size your emergency fund to your real life and get a monthly plan to build it.</x-slot:description>

    <div class="bg-mesh" x-data="fundCalc()" 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="life-buoy" class="h-9 w-9" /></span>
                <h1 class="mt-4 font-display text-display-sm font-bold text-navy-900" data-hero-item>Emergency Fund Calculator</h1>
                <p class="mt-3 text-lg text-navy-600" data-hero-item>Life happens, job loss, sickness, that phone call. Let's size your cushion so it bends, not breaks, you.</p>
                <div class="mt-5 flex justify-center" data-hero-item><x-currency-picker /></div>
                <x-tool-intro slug="emergency-fund" title="Emergency Fund Calculator"
                    tagline="Size the safety cushion that keeps a bad month from becoming a crisis."
                    :steps="[
                        'Enter your essential monthly expenses.',
                        'Tell us how steady your income is.',
                        'Add what you have saved and what you can save monthly.',
                        'See your target and the date you\'ll be fully covered.',
                    ]" />
            </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 for="expenses" class="text-sm font-semibold text-navy-700">My essential monthly expenses</label>
                            <span class="font-display text-xl font-extrabold text-wise-600" x-text="fmt(expenses)"></span>
                        </div>
                        <input id="expenses" type="range" :min="Math.max(1, Math.round(5000 * cf))" :max="Math.round(300000 * cf)" :step="Math.max(1, Math.round(1000 * cf))" x-model.number="expenses" @input="recalc()" class="slider mt-2">
                        <p class="mt-1 text-xs text-navy-400">Rent, food, transport, fees, family support, survival mode, not lifestyle mode.</p>
                    </div>

                    <div>
                        <p class="text-sm font-semibold text-navy-700">How steady is your income?</p>
                        <div class="mt-2 grid grid-cols-3 gap-2">
                            <template x-for="opt in incomeTypes" :key="opt.months">
                                <button @click="months = opt.months; recalc()"
                                        :class="months === opt.months ? '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="opt.svg"></span>
                                    <p class="mt-1.5 text-xs font-bold text-navy-900" x-text="opt.label"></p>
                                    <p class="text-[11px] font-semibold text-navy-400" x-text="opt.months + ' months'"></p>
                                </button>
                            </template>
                        </div>
                    </div>

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

                    <div>
                        <div class="flex items-baseline justify-between">
                            <label for="monthly" class="text-sm font-semibold text-navy-700">I can put aside 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(50000 * cf)" :step="Math.max(1, Math.round(500 * cf))" x-model.number="monthly" @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 target cushion</p>
                        <p class="mt-2 font-display text-5xl font-extrabold text-navy-900" x-text="fmt(target)"></p>
                        <p class="mt-1 text-navy-500"><span x-text="months"></span> months × <span x-text="fmt(expenses)"></span></p>

                        {{-- Progress ring --}}
                        <div class="relative mx-auto mt-6 h-44 w-44">
                            <svg viewBox="0 0 120 120" class="h-full w-full -rotate-90">
                                <circle cx="60" cy="60" r="52" fill="none" stroke="#eef1f9" stroke-width="12"/>
                                <circle cx="60" cy="60" r="52" fill="none" stroke="url(#ringGrad)" stroke-width="12" stroke-linecap="round"
                                        stroke-dasharray="326.7"
                                        :stroke-dashoffset="326.7 - (326.7 * pct / 100)"
                                        style="transition: stroke-dashoffset .8s cubic-bezier(.21,.61,.35,1)"/>
                                <defs>
                                    <linearGradient id="ringGrad" x1="0%" y1="0%" x2="100%" y2="100%">
                                        <stop offset="0%" stop-color="#58b9e6"/>
                                        <stop offset="100%" stop-color="#2787b8"/>
                                    </linearGradient>
                                </defs>
                            </svg>
                            <div class="absolute inset-0 grid place-items-center">
                                <div>
                                    <p class="font-display text-3xl font-extrabold text-navy-900" x-text="pct + '%'"></p>
                                    <p class="text-xs font-semibold text-navy-400">funded</p>
                                </div>
                            </div>
                        </div>

                        <template x-if="gap > 0">
                            <div class="mt-5">
                                <p class="text-navy-600">Missing piece: <strong class="text-navy-900" x-text="fmt(gap)"></strong></p>
                                <p class="mt-2 rounded-2xl bg-wise-50 px-4 py-3 text-sm font-semibold text-navy-800">
                                    At <span x-text="fmt(monthly)"></span>/month you'll be fully covered by
                                    <span class="text-wise-700" x-text="readyDate"></span>
                                </p>
                            </div>
                        </template>
                        <template x-if="gap <= 0">
                            <p class="mt-5 flex items-center justify-center gap-2 rounded-2xl bg-emerald-50 px-4 py-3 font-semibold text-emerald-700">
                                <x-icon name="award" class="h-5 w-5 shrink-0" /> Fully funded! Your next move: put the surplus to work, try the growth visualiser.
                            </p>
                        </template>
                    </div>

                    <div class="card p-6">
                        <h2 class="font-display font-bold text-navy-900">Smart placement for this money</h2>
                        <ul class="mt-3 space-y-2.5 text-sm leading-relaxed text-navy-700">
                            <li class="flex gap-2.5"><x-icon name="check-circle" class="mt-0.5 h-4 w-4 shrink-0 text-emerald-500" /> Keep it in a <strong>money market fund</strong>, accessible in 2-4 days, earning real interest, away from impulse spending.</li>
                            <li class="flex gap-2.5"><x-icon name="check-circle" class="mt-0.5 h-4 w-4 shrink-0 text-emerald-500" /> Split a small float to mobile-money savings for true same-day emergencies.</li>
                            <li class="flex gap-2.5"><x-icon name="x" class="mt-0.5 h-4 w-4 shrink-0 text-rose-500" /> Not in shares or land, emergencies don't wait for the right price.</li>
                            <li class="flex gap-2.5"><x-icon name="x" class="mt-0.5 h-4 w-4 shrink-0 text-rose-500" /> Not in your everyday account, it will quietly become airtime and weekend plans.</li>
                        </ul>
                    </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 fund plan, printable.</p>
                        </div>
                        <button @click="busy = true; window.downloadToolPdf('emergency-fund', 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: '', 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>
                                <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>
                                <p x-show="error" x-text="error" class="mt-2 text-sm font-medium text-rose-600"></p>
                            </div>
                        </template>
                        <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" /> Plan saved! Set up that standing order today.</p>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

            return {
                cf,
                expenses: Math.round(40000 * cf),
                months: 6,
                saved: Math.round(20000 * cf),
                monthly: Math.round(5000 * cf),

                applyCurrency() {
                    const nf = window.MW.factor();
                    const r = nf / this.cf;
                    this.cf = nf;
                    this.expenses = Math.round(this.expenses * r);
                    this.saved = Math.round(this.saved * r);
                    this.monthly = Math.round(this.monthly * r);
                    this.recalc();
                },
                incomeTypes: [
                    { label: 'Stable salary', months: 3, 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="M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/><rect width="20" height="14" x="2" y="6" rx="2"/></svg>' },
                    { label: 'Mixed income', months: 6, 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="m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z"/><path d="m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z"/><path d="M7 21h10"/><path d="M12 3v18"/><path d="M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2"/></svg>' },
                    { label: 'Hustle/freelance', months: 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"><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>' },
                ],
                target: 0, gap: 0, pct: 0, readyDate: '',

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

                recalc() {
                    this.target = this.expenses * this.months;
                    this.gap = Math.max(0, this.target - this.saved);
                    this.pct = this.target > 0 ? Math.min(100, Math.round(this.saved / this.target * 100)) : 0;

                    const monthsToGo = this.monthly > 0 ? Math.ceil(this.gap / this.monthly) : 0;
                    const d = new Date();
                    d.setMonth(d.getMonth() + monthsToGo);
                    this.readyDate = d.toLocaleDateString('en-KE', { month: 'long', year: 'numeric' });
                },

                pdfPayload() {
                    return {
                        highlight: { value: this.fmt(this.target), label: 'Your emergency fund target, ' + this.months + ' months of essentials' },
                        sections: [
                            {
                                title: 'Where you stand',
                                rows: [
                                    ['Essential monthly expenses', this.fmt(this.expenses)],
                                    ['Months of cover needed', String(this.months)],
                                    ['Already saved', this.fmt(this.saved)],
                                    ['Funded so far', this.pct + '%'],
                                    ['Still to build', this.fmt(this.gap)],
                                ],
                            },
                            {
                                title: 'The plan',
                                rows: [
                                    ['Monthly contribution', this.fmt(this.monthly)],
                                    ['Fully covered by', this.gap > 0 ? this.readyDate : 'Already covered'],
                                ],
                            },
                        ],
                        note: 'Park this money in a money market fund with a small mobile-money float for same-day emergencies. Revisit whenever your expenses change: moneywise.co.ke/tools/emergency-fund',
                    };
                },

                savePlan(email = null) {
                    return fetch('{{ route('tools.save', 'emergency-fund') }}', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
                        body: JSON.stringify({
                            email,
                            label: 'Emergency fund plan',
                            inputs: { expenses: this.expenses, months: this.months, saved: this.saved, monthly: this.monthly, currency: window.MW.code() },
                            outputs: { target: this.target, gap: this.gap, pct: this.pct, readyDate: this.readyDate },
                        }),
                    }).then(() => window.celebrate?.());
                },
            };
        }
    </script>
    @endpush
</x-layouts.site>
