<x-layouts.site>
    <x-slot:title>Wealth &amp; Goals Planner</x-slot:title>
    <x-slot:description>Put every life goal on one timeline, home, education, retirement, business, and see exactly what to invest each month to get there.</x-slot:description>

    <div class="relative bg-mesh" x-data="goalsPlanner()" x-init="recalc()" @currency-changed.window="applyCurrency()">
        <div class="container-site section relative">
            <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="target" class="h-9 w-9" /></span>
                <h1 class="mt-4 font-display text-display-sm font-bold text-navy-900" data-hero-item>Wealth &amp; Goals Planner</h1>
                <p class="mt-3 text-lg text-navy-600" data-hero-item>Every dream gets a number, a date, and a monthly plan. Watch them all fit on one timeline.</p>
                <div class="mt-5 flex justify-center" data-hero-item><x-currency-picker /></div>
                <x-tool-intro slug="wealth-goals" title="Wealth &amp; Goals Planner"
                    tagline="Give every dream a number, a date and a monthly amount you can actually start."
                    :steps="[
                        'Add the goals that matter to you.',
                        'Set each target amount and timeline.',
                        'See the monthly amount each goal needs.',
                        'Save your plan and start with goal number one.',
                    ]" />
            </div>

            <div class="mt-10 grid gap-6 lg:grid-cols-[1.1fr,1fr]">
                {{-- ===== Goals ===== --}}
                <div class="space-y-6 lg:sticky lg:top-24 lg:self-start">
                    <div class="card p-6">
                        <div class="flex items-center justify-between">
                            <h2 class="font-display font-bold text-navy-900">My goals</h2>
                            <button @click="addGoal()" class="btn-ghost btn-sm"><x-icon name="plus" class="h-4 w-4" /> Add goal</button>
                        </div>

                        <div class="mt-4 space-y-4">
                            <template x-for="(goal, i) in goals" :key="goal.id">
                                <div class="rounded-2xl bg-navy-50/60 p-4 ring-1 ring-navy-100">
                                    <div class="flex items-center gap-2">
                                        {{-- Icon picker --}}
                                        <div class="flex gap-1">
                                            <template x-for="t in templates" :key="t.key">
                                                <button @click="goal.icon = t.key"
                                                        class="grid h-8 w-8 place-items-center rounded-lg transition"
                                                        :class="goal.icon === t.key ? 'bg-wise-400 text-navy-950' : 'bg-white text-navy-400 hover:text-wise-600'"
                                                        x-html="t.svg" :title="t.label"></button>
                                            </template>
                                        </div>
                                        <input type="text" x-model="goal.name" placeholder="Goal name"
                                               class="min-w-0 flex-1 rounded-xl border-0 bg-white px-3 py-2 text-sm font-semibold text-navy-900 ring-1 ring-navy-200 focus:ring-2 focus:ring-wise-400">
                                        <button @click="goals.splice(i, 1); recalc()" class="grid h-9 w-9 shrink-0 place-items-center rounded-full text-navy-400 transition hover:bg-rose-50 hover:text-rose-500" aria-label="Remove goal">
                                            <x-icon name="trash" class="h-4 w-4" />
                                        </button>
                                    </div>
                                    <div class="mt-3 grid grid-cols-2 gap-4">
                                        <div>
                                            <div class="flex justify-between text-[11px] font-bold uppercase tracking-wide text-navy-400">
                                                <span>Target</span><span class="text-wise-600" x-text="fmt(goal.amount)"></span>
                                            </div>
                                            <input type="range" :min="Math.max(1, Math.round(50000 * cf))" :max="Math.round(20000000 * cf)" :step="Math.max(1, Math.round(50000 * cf))" x-model.number="goal.amount" @input="recalc()" class="slider mt-1.5">
                                        </div>
                                        <div>
                                            <div class="flex justify-between text-[11px] font-bold uppercase tracking-wide text-navy-400">
                                                <span>When</span><span class="text-wise-600"><span x-text="goal.years"></span> yrs (<span x-text="yearOf(goal.years)"></span>)</span>
                                            </div>
                                            <input type="range" min="1" max="30" step="1" x-model.number="goal.years" @input="recalc()" class="slider mt-1.5">
                                        </div>
                                    </div>
                                </div>
                            </template>
                            <p x-show="goals.length === 0" class="rounded-2xl border-2 border-dashed border-navy-200 p-6 text-center text-sm text-navy-400">
                                Add your first goal, a home, school fees, retirement, the business…
                            </p>
                        </div>
                    </div>

                    <div class="card p-6">
                        <h2 class="font-display font-bold text-navy-900">Where the money grows</h2>
                        <div class="mt-3 flex items-center gap-3">
                            <input type="range" min="6" max="16" step="0.5" x-model.number="rate" @input="recalc()" class="slider flex-1">
                            <span class="w-16 text-right font-display font-extrabold text-wise-600" x-text="rate + '%/yr'"></span>
                        </div>
                        <p class="mt-1.5 text-xs text-navy-400">~9% money market · ~13% bonds · ~15% long-term equities. Indicative, before fees and tax.</p>
                    </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">To hit every goal, invest</p>
                            <p class="mt-2 font-display text-4xl font-extrabold text-white"><span x-text="fmt(totalMonthly)"></span><span class="text-lg font-bold text-navy-300">/month</span></p>
                            <p class="mt-1 text-sm text-navy-200"><span x-text="goals.length"></span> goals · growing at <span x-text="rate"></span>% per year</p>
                        </div>
                        <div class="p-6">
                            <h3 class="text-xs font-bold uppercase tracking-widest text-navy-400">Monthly split</h3>
                            <div class="mt-3 space-y-3">
                                <template x-for="g in results" :key="g.id">
                                    <div>
                                        <div class="mb-1 flex items-baseline justify-between text-sm">
                                            <span class="flex items-center gap-2 font-semibold text-navy-800">
                                                <span class="grid h-6 w-6 place-items-center rounded-lg bg-wise-50 text-wise-600" x-html="iconFor(g.icon)"></span>
                                                <span x-text="g.name || 'Unnamed goal'"></span>
                                            </span>
                                            <span class="font-display font-extrabold text-navy-900" x-text="fmt(g.monthly) + '/mo'"></span>
                                        </div>
                                        <div class="h-2.5 overflow-hidden rounded-full bg-navy-100">
                                            <div class="h-full rounded-full bg-gradient-to-r from-wise-400 to-wise-600 transition-all duration-500" :style="'width:' + g.share + '%'"></div>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>

                    {{-- Timeline --}}
                    <div class="card p-6">
                        <h2 class="font-display font-bold text-navy-900">Your life timeline</h2>
                        <div class="mt-4 space-y-0">
                            <template x-for="(g, i) in [...results].sort((a, b) => a.years - b.years)" :key="g.id">
                                <div class="relative flex gap-4 pb-6">
                                    <div class="flex flex-col items-center">
                                        <span class="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-wise-400 text-navy-950 shadow-wise" x-html="iconFor(g.icon)"></span>
                                        <span x-show="i < results.length - 1" class="mt-1 w-0.5 flex-1 rounded-full bg-navy-100"></span>
                                    </div>
                                    <div class="pt-1">
                                        <p class="font-display text-sm font-extrabold text-wise-600" x-text="yearOf(g.years)"></p>
                                        <p class="font-display font-bold text-navy-900" x-text="g.name || 'Unnamed goal'"></p>
                                        <p class="text-sm text-navy-500"><span x-text="fmt(g.amount)"></span> · funded by <span class="font-bold text-navy-700" x-text="fmt(g.monthly) + '/mo'"></span></p>
                                    </div>
                                </div>
                            </template>
                        </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">All goals, one printable plan.</p>
                        </div>
                        <button @click="busy = true; window.downloadToolPdf('wealth-goals', pdfPayload()).then(() => busy = false)"
                                class="btn-primary btn-sm shrink-0" :disabled="busy || goals.length === 0">
                            <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 plan</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 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="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" /> Plan saved, now automate that monthly amount!</p>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        function goalsPlanner() {
            const icon = (paths) => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4">${paths}</svg>`;

            const ICONS = {
                home: icon('<path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>'),
                education: icon('<path d="M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z"/><path d="M22 10v6"/><path d="M6 12.5V16a6 3 0 0 0 12 0v-3.5"/>'),
                retirement: icon('<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"/>'),
                business: icon('<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"/>'),
                travel: icon('<path d="M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z"/>'),
                wedding: icon('<path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/>'),
            };

            const cf = window.MW.factor();

            return {
                cf,
                rate: 11,
                nextId: 4,
                goals: [
                    { id: 1, name: 'Own our home', icon: 'home', amount: Math.round(3000000 * cf), years: 7 },
                    { id: 2, name: 'University fund', icon: 'education', amount: Math.round(1500000 * cf), years: 10 },
                    { id: 3, name: 'Retirement pot', icon: 'retirement', amount: Math.round(10000000 * cf), years: 25 },
                ],

                applyCurrency() {
                    const nf = window.MW.factor();
                    const r = nf / this.cf;
                    this.cf = nf;
                    this.goals.forEach(g => g.amount = Math.round(g.amount * r));
                    this.recalc();
                },
                templates: [
                    { key: 'home', label: 'Home', svg: ICONS.home },
                    { key: 'education', label: 'Education', svg: ICONS.education },
                    { key: 'retirement', label: 'Retirement', svg: ICONS.retirement },
                    { key: 'business', label: 'Business', svg: ICONS.business },
                    { key: 'travel', label: 'Travel', svg: ICONS.travel },
                    { key: 'wedding', label: 'Wedding', svg: ICONS.wedding },
                ],
                results: [],
                totalMonthly: 0,

                fmt(v) { return window.MW.fmt(v); },
                yearOf(years) { return new Date().getFullYear() + years; },
                iconFor(key) { return ICONS[key] ?? ICONS.home; },

                addGoal() {
                    this.goals.push({ id: this.nextId++, name: '', icon: 'business', amount: Math.round(500000 * this.cf), years: 5 });
                    this.recalc();
                },

                monthlyFor(goal) {
                    const r = this.rate / 100 / 12;
                    const n = goal.years * 12;
                    if (n <= 0) return goal.amount;
                    // Future-value annuity: PMT = FV * r / ((1+r)^n - 1)
                    return goal.amount * r / (Math.pow(1 + r, n) - 1);
                },

                recalc() {
                    const monthly = this.goals.map(g => ({ ...g, monthly: this.monthlyFor(g) }));
                    this.totalMonthly = monthly.reduce((s, g) => s + g.monthly, 0);
                    this.results = monthly.map(g => ({ ...g, share: this.totalMonthly > 0 ? Math.round(g.monthly / this.totalMonthly * 100) : 0 }));
                },

                pdfPayload() {
                    return {
                        highlight: { value: this.fmt(this.totalMonthly) + '/month', label: 'Total monthly investment to hit all ' + this.goals.length + ' goals at ' + this.rate + '% growth' },
                        sections: [
                            {
                                title: 'Goal by goal',
                                rows: this.results.map(g => [
                                    (g.name || 'Unnamed goal') + ', ' + this.fmt(g.amount) + ' by ' + this.yearOf(g.years),
                                    this.fmt(g.monthly) + '/month',
                                ]),
                            },
                            {
                                title: 'Timeline',
                                rows: [...this.results].sort((a, b) => a.years - b.years).map(g => [
                                    String(this.yearOf(g.years)),
                                    (g.name || 'Unnamed goal') + ' fully funded',
                                ]),
                            },
                        ],
                        note: 'Automate each goal as its own standing order the day money comes in. Adjust the plan whenever life changes: moneywise.co.ke/tools/wealth-goals',
                    };
                },

                savePlan(email = null) {
                    return fetch('{{ route('tools.save', 'wealth-goals') }}', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
                        body: JSON.stringify({
                            email,
                            label: 'Wealth & goals plan',
                            inputs: { goals: this.goals, rate: this.rate, currency: window.MW.code() },
                            outputs: { totalMonthly: Math.round(this.totalMonthly), perGoal: this.results.map(g => ({ name: g.name, monthly: Math.round(g.monthly), year: this.yearOf(g.years) })) },
                        }),
                    }).then(() => window.celebrate?.());
                },
            };
        }
    </script>
    @endpush
</x-layouts.site>
