<x-layouts.site>
    <x-slot:title>Budget Builder</x-slot:title>
    <x-slot:description>Build a monthly budget that survives real African life. Add your own line items across essentials, future-you and lifestyle, see where every shilling goes, and get a plan you'll actually follow.</x-slot:description>

    <div class="bg-mesh" x-data="budgetTool()" 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="calculator" class="h-9 w-9" /></span>
                <h1 class="mt-4 font-display text-display-sm font-bold text-navy-900" data-hero-item>Budget Builder</h1>
                <p class="mt-3 text-lg text-navy-600" data-hero-item>Give every shilling a job. Add your own line items across <strong>essentials</strong>, <strong>future-you</strong> and <strong>lifestyle</strong>, and watch it balance live.</p>
                <div class="mt-5 flex justify-center" data-hero-item><x-currency-picker /></div>
                <x-tool-intro slug="budget" title="Budget Builder"
                    tagline="Plan your month so every shilling has a job across essentials, future-you and lifestyle, and watch it balance instantly."
                    :steps="[
                        'Set your monthly take-home income.',
                        'Add or edit line items under each bucket.',
                        'Watch the balance, donut and Money-Wise split update live.',
                        'Download the PDF, or save your budget to your dashboard.',
                    ]" />
            </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">
                    {{-- Income --}}
                    <div>
                        <div class="flex items-baseline justify-between">
                            <label for="income" class="text-sm font-semibold text-navy-700">Monthly take-home income</label>
                            <span class="font-display text-xl font-extrabold text-wise-600" x-text="fmt(income)"></span>
                        </div>
                        <input id="income" type="range" :min="Math.max(1, Math.round(5000 * cf))" :max="Math.round(500000 * cf)" :step="Math.max(1, Math.round(1000 * cf))" x-model.number="income" @input="recalc()" class="slider mt-2">
                        <p class="mt-1 text-xs text-navy-400">What actually lands in your account each month, after tax.</p>
                    </div>

                    {{-- Buckets with add/remove line items --}}
                    <template x-for="group in groups" :key="group.key">
                        <div class="rounded-2xl p-4" :style="`background:${group.tint}`">
                            <div class="flex items-center justify-between">
                                <p class="flex items-center gap-2 font-display text-sm font-bold" :style="`color:${group.color}`">
                                    <span class="h-2.5 w-2.5 rounded-full" :style="`background:${group.color}`"></span>
                                    <span x-text="group.label"></span>
                                </p>
                                <span class="font-display text-sm font-extrabold" :style="`color:${group.color}`" x-text="fmt(bucketTotal(group))"></span>
                            </div>

                            <div class="mt-3 space-y-2">
                                <template x-for="item in group.items" :key="item.id">
                                    <div class="flex items-center gap-2">
                                        <input type="text" x-model="item.label" placeholder="Item name"
                                               class="min-w-0 flex-1 rounded-xl border-navy-200 bg-white/80 px-3 py-1.5 text-sm text-navy-800 focus:border-wise-400 focus:ring-wise-400">
                                        <input type="number" min="0" inputmode="numeric" x-model.number="item.amount" @input="recalc()"
                                               class="w-28 rounded-xl border-navy-200 bg-white/80 px-3 py-1.5 text-right text-sm font-semibold text-navy-900 focus:border-wise-400 focus:ring-wise-400">
                                        <button type="button" @click="removeItem(group, item.id)"
                                                class="grid h-8 w-8 shrink-0 place-items-center rounded-lg text-navy-300 transition hover:bg-rose-50 hover:text-rose-500"
                                                aria-label="Remove item">
                                            <x-icon name="x" class="h-4 w-4" />
                                        </button>
                                    </div>
                                </template>
                            </div>

                            <button type="button" @click="addItem(group)"
                                    class="mt-2.5 inline-flex items-center gap-1.5 text-sm font-semibold transition hover:opacity-80" :style="`color:${group.color}`">
                                <x-icon name="plus" class="h-4 w-4" /> Add item
                            </button>
                        </div>
                    </template>

                    <button type="button" @click="resetDefaults()" class="text-xs font-semibold text-navy-400 transition hover:text-navy-700">
                        Reset to the starter budget
                    </button>
                </div>

                {{-- Results --}}
                <div class="space-y-6">
                    {{-- Headline: surplus / deficit --}}
                    <div class="card p-8 text-center">
                        <template x-if="remaining >= 0">
                            <div>
                                <p class="text-sm font-semibold uppercase tracking-widest text-navy-400">Left to allocate</p>
                                <p class="mt-2 font-display text-5xl font-extrabold text-emerald-600" x-text="fmt(remaining)"></p>
                                <p class="mt-2 text-navy-500"><span x-text="fmt(totalExpenses)"></span> planned of <span x-text="fmt(income)"></span></p>
                                <template x-if="remaining > 0">
                                    <p class="mt-4 rounded-2xl bg-emerald-50 px-4 py-3 text-sm font-semibold text-emerald-700">
                                        You have <span x-text="fmt(remaining)"></span> unspent. Give it a job, push it to savings, investments or debt before it disappears.
                                    </p>
                                </template>
                                <template x-if="remaining === 0">
                                    <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="check-circle" class="h-5 w-5 shrink-0" /> Every shilling has a job. That's a zero-based budget done right.
                                    </p>
                                </template>
                            </div>
                        </template>
                        <template x-if="remaining < 0">
                            <div>
                                <p class="text-sm font-semibold uppercase tracking-widest text-navy-400">Over budget by</p>
                                <p class="mt-2 font-display text-5xl font-extrabold text-rose-600" x-text="fmt(Math.abs(remaining))"></p>
                                <p class="mt-2 text-navy-500"><span x-text="fmt(totalExpenses)"></span> planned of <span x-text="fmt(income)"></span></p>
                                <p class="mt-4 flex items-center justify-center gap-2 rounded-2xl bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">
                                    <x-icon name="alert-triangle" class="h-5 w-5 shrink-0" /> You're spending more than you earn. Trim lifestyle first, then revisit the essentials.
                                </p>
                            </div>
                        </template>

                        {{-- Donut: where the money goes --}}
                        <div class="relative mx-auto mt-6 h-48 w-48" x-show="totalExpenses > 0">
                            <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="14"/>
                                <template x-for="seg in donut" :key="seg.key">
                                    <circle cx="60" cy="60" r="52" fill="none" :stroke="seg.color" stroke-width="14"
                                            :stroke-dasharray="seg.dash" :stroke-dashoffset="seg.offset"
                                            style="transition:stroke-dasharray .7s cubic-bezier(.21,.61,.35,1)"/>
                                </template>
                            </svg>
                            <div class="absolute inset-0 grid place-items-center">
                                <div>
                                    <p class="font-display text-2xl font-extrabold text-navy-900" x-text="futureRate + '%'"></p>
                                    <p class="text-[11px] font-semibold text-navy-400">to future-you</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- Bucket breakdown vs the Money-Wise framework --}}
                    <div class="card p-6">
                        <h2 class="font-display font-bold text-navy-900">The Money-Wise split</h2>
                        <p class="mt-1 text-sm text-navy-500">How your plan compares to a healthy balance.</p>
                        <div class="mt-4 space-y-4">
                            <template x-for="group in groups" :key="'bar-' + group.key">
                                <div>
                                    <div class="flex items-center justify-between text-sm">
                                        <span class="font-semibold text-navy-800" x-text="group.label"></span>
                                        <span class="font-semibold" :class="group.ok ? 'text-emerald-600' : 'text-amber-600'">
                                            <span x-text="incomePct[group.key] + '%'"></span>
                                            <span class="text-navy-400" x-text="'· aim ' + group.targetLabel"></span>
                                        </span>
                                    </div>
                                    <div class="mt-1.5 h-2.5 overflow-hidden rounded-full bg-navy-50">
                                        <div class="h-full rounded-full transition-all duration-700" :style="`width:${Math.min(100, incomePct[group.key])}%;background:${group.color}`"></div>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <p class="mt-4 flex items-start gap-2 rounded-2xl bg-navy-50 px-4 py-3 text-sm text-navy-700">
                            <x-icon name="sparkles" class="mt-0.5 h-4 w-4 shrink-0 text-wise-600" />
                            <span x-text="verdict"></span>
                        </p>
                    </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 monthly budget, printable.</p>
                        </div>
                        <button @click="busy = true; window.downloadToolPdf('budget', 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 budget</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 budget</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" /> Budget saved! Set up your standing orders to match it.</p>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        function budgetTool() {
            const cf = window.MW.factor();
            const r = (v) => Math.round(v);
            let _seq = 0;

            const starter = (factor) => {
                const mk = (label, amount) => ({ id: ++_seq, label, amount: Math.round(amount * factor) });
                return [
                    {
                        key: 'essentials', label: 'Essentials', color: '#1c2b5f', tint: 'rgba(28,43,95,0.05)',
                        target: 50, targetLabel: '≤50%', ok: true,
                        items: [ mk('Housing & utilities', 18000), mk('Food & groceries', 15000), mk('Transport', 8000), mk('Family support', 5000) ],
                    },
                    {
                        key: 'future', label: 'Future-you', color: '#2787b8', tint: 'rgba(39,135,184,0.07)',
                        target: 20, targetLabel: '≥20%', ok: true,
                        items: [ mk('Debt repayments', 6000), mk('Savings & emergency fund', 5000), mk('Investments', 4000), mk('Giving', 3000) ],
                    },
                    {
                        key: 'lifestyle', label: 'Lifestyle', color: '#f59e0b', tint: 'rgba(245,158,11,0.08)',
                        target: 30, targetLabel: '≤30%', ok: true,
                        items: [ mk('Lifestyle, fun & subscriptions', 6000) ],
                    },
                ];
            };

            return {
                cf,
                income: r(80000 * cf),
                groups: starter(cf),

                totalExpenses: 0, remaining: 0, futureRate: 0,
                incomePct: { essentials: 0, future: 0, lifestyle: 0 },
                donut: [],
                verdict: '',

                fmt(v) { return window.MW.fmt(v); },
                bucketTotal(g) { return g.items.reduce((s, i) => s + (Number(i.amount) || 0), 0); },

                addItem(group) {
                    group.items.push({ id: ++_seq, label: '', amount: 0 });
                    this.recalc();
                },
                removeItem(group, id) {
                    group.items = group.items.filter((i) => i.id !== id);
                    this.recalc();
                },
                resetDefaults() {
                    this.groups = starter(this.cf);
                    this.recalc();
                },

                applyCurrency() {
                    const nf = window.MW.factor();
                    const ratio = nf / this.cf;
                    this.cf = nf;
                    this.income = r(this.income * ratio);
                    for (const g of this.groups) {
                        for (const i of g.items) i.amount = r((Number(i.amount) || 0) * ratio);
                    }
                    this.recalc();
                },

                recalc() {
                    const b = {};
                    for (const g of this.groups) b[g.key] = this.bucketTotal(g);
                    this.totalExpenses = Object.values(b).reduce((s, v) => s + v, 0);
                    this.remaining = this.income - this.totalExpenses;

                    const inc = this.income || 1;
                    this.incomePct = {
                        essentials: Math.round((b.essentials || 0) / inc * 100),
                        future: Math.round((b.future || 0) / inc * 100),
                        lifestyle: Math.round((b.lifestyle || 0) / inc * 100),
                    };
                    this.futureRate = this.incomePct.future;

                    // target checks (find groups by key, robust to reordering)
                    for (const g of this.groups) {
                        const pct = this.incomePct[g.key] ?? 0;
                        g.ok = g.key === 'future' ? pct >= g.target : pct <= g.target;
                    }

                    // donut: each bucket sized to its share of total spending
                    const C = 326.726; // 2 * pi * r (r = 52)
                    const total = this.totalExpenses || 1;
                    const palette = { essentials: '#1c2b5f', future: '#2787b8', lifestyle: '#f59e0b' };
                    let acc = 0;
                    this.donut = this.groups
                        .filter((g) => b[g.key] > 0)
                        .map((g) => {
                            const len = (b[g.key] / total) * C;
                            const seg = { key: g.key, color: palette[g.key] || g.color, dash: `${len} ${C - len}`, offset: -acc };
                            acc += len;
                            return seg;
                        });

                    this.verdict = this.buildVerdict();
                },

                buildVerdict() {
                    if (this.remaining < 0) {
                        return 'Your plan spends more than you earn. The fastest fix is the lifestyle bucket, trim there first before touching essentials.';
                    }
                    if (this.futureRate >= 20) {
                        return `Excellent, you're directing ${this.futureRate}% toward future-you (savings, investments, debt and giving). This is how wealth quietly gets built.`;
                    }
                    if (this.incomePct.essentials > 50) {
                        return `Essentials are eating ${this.incomePct.essentials}% of your income (aim for 50% or less). Reducing rent, transport or family support frees the most room.`;
                    }
                    if (this.futureRate < 10) {
                        return `Only ${this.futureRate}% is going to future-you. Try nudging it toward 20%, even a small automated standing order compounds fast.`;
                    }
                    return `A solid, balanced budget. Push future-you from ${this.futureRate}% toward 20% and you'll accelerate every goal.`;
                },

                pdfPayload() {
                    const sections = [{ title: 'Income', rows: [['Monthly take-home', this.fmt(this.income)]] }];
                    for (const g of this.groups) {
                        sections.push({
                            title: g.label + ' (' + (this.incomePct[g.key] ?? 0) + '% of income)',
                            rows: g.items.length
                                ? g.items.map((i) => [i.label || 'Item', this.fmt(Number(i.amount) || 0)])
                                : [[', ', this.fmt(0)]],
                        });
                    }
                    sections.push({
                        title: 'The bottom line',
                        rows: [
                            ['Total planned spending', this.fmt(this.totalExpenses)],
                            ['Toward future-you', this.futureRate + '%'],
                            [this.remaining >= 0 ? 'Left to allocate' : 'Over budget by', this.fmt(Math.abs(this.remaining))],
                        ],
                    });

                    return {
                        currency: window.MW.code(),
                        highlight: {
                            value: this.fmt(this.remaining >= 0 ? this.remaining : Math.abs(this.remaining)),
                            label: this.remaining >= 0 ? 'Left to allocate this month' : 'Over budget this month, trim to balance',
                        },
                        sections: sections.slice(0, 8),
                        note: 'Set up standing orders that match this budget so the right amounts move automatically on payday. Revisit monthly: moneywise.co.ke/tools/budget',
                    };
                },

                savePlan(email = null) {
                    return fetch('{{ route('tools.save', 'budget') }}', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
                        body: JSON.stringify({
                            email,
                            label: 'Monthly budget',
                            inputs: {
                                income: this.income,
                                currency: window.MW.code(),
                                groups: this.groups.map((g) => ({ key: g.key, items: g.items.map((i) => ({ label: i.label, amount: Number(i.amount) || 0 })) })),
                            },
                            outputs: { totalExpenses: this.totalExpenses, remaining: this.remaining, futureRate: this.futureRate, incomePct: this.incomePct },
                        }),
                    }).then(() => window.celebrate?.());
                },
            };
        }
    </script>
    @endpush
</x-layouts.site>
