<x-layouts.site>
    <x-slot:title>Values Clarification</x-slot:title>
    <x-slot:description>Discover the core values that should drive every money decision you make, the Money-Wise values clarification exercise. Narrow 80 values down to your top 5 and commit to living by them.</x-slot:description>

    <div class="relative min-h-[calc(100vh-4.75rem)] overflow-hidden bg-mesh" x-data="valuesSort()">
        <div class="blob -left-32 top-20 h-80 w-80 bg-wise-300/30" aria-hidden="true"></div>

        <div class="container-site section relative max-w-4xl">
            <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="compass" class="h-9 w-9" /></span>
                <h1 class="mt-4 font-display text-display-sm font-bold text-navy-900" data-hero-item>Values Clarification</h1>
                <p class="mt-3 text-lg text-navy-600" data-hero-item>
                    Money follows values, whether you've named them or not. We'll start with 80 and narrow to the five that should guide every shilling.
                </p>
            </div>

            {{-- Progress steps --}}
            <div class="mx-auto mt-8 flex max-w-2xl items-center justify-between" x-show="phase !== 'intro'" x-cloak>
                <template x-for="(s, i) in ['Keep 40', 'Keep 20', 'Keep 10', 'Top 5', 'Commit']" :key="i">
                    <div class="flex flex-1 items-center">
                        <div class="flex flex-col items-center gap-1.5" :class="i > 0 && 'flex-1'">
                            <span class="grid h-9 w-9 place-items-center rounded-full font-display text-sm font-extrabold transition-all duration-300"
                                  :class="stepIndex() > i ? 'bg-emerald-500 text-white' : (stepIndex() === i ? 'bg-wise-400 text-navy-950 shadow-wise scale-110' : 'bg-white text-navy-300 ring-2 ring-navy-100')">
                                <span x-show="stepIndex() <= i" x-text="i + 1"></span>
                                <svg x-show="stepIndex() > i" x-cloak class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
                            </span>
                            <span class="text-[10px] font-bold uppercase tracking-wide" :class="stepIndex() >= i ? 'text-navy-700' : 'text-navy-300'" x-text="s"></span>
                        </div>
                        <div x-show="i < 4" class="mx-2 h-0.5 flex-1 rounded-full" :class="stepIndex() > i ? 'bg-emerald-400' : 'bg-navy-100'"></div>
                    </div>
                </template>
            </div>

            {{-- ============ INTRO ============ --}}
            <div x-show="phase === 'intro'" class="mx-auto mt-10 max-w-2xl">
                <div class="card p-7">
                    <h2 class="font-display text-xl font-bold text-navy-900">How this works</h2>
                    <p class="mt-2 leading-relaxed text-navy-600">
                        Values are your heart's deepest desires for how you want to live, relate and decide. This exercise
                        surfaces yours through a few rounds of honest choosing.
                    </p>
                    <ol class="mt-4 space-y-2.5 text-sm leading-relaxed text-navy-700">
                        <li class="flex gap-3"><span class="grid h-6 w-6 shrink-0 place-items-center rounded-full bg-wise-100 font-bold text-wise-700">1</span> From 80 values, keep the ones that resonate, down to about 40.</li>
                        <li class="flex gap-3"><span class="grid h-6 w-6 shrink-0 place-items-center rounded-full bg-wise-100 font-bold text-wise-700">2</span> Narrow again to 20, then 10.</li>
                        <li class="flex gap-3"><span class="grid h-6 w-6 shrink-0 place-items-center rounded-full bg-wise-100 font-bold text-wise-700">3</span> Choose your top 5 core values.</li>
                        <li class="flex gap-3"><span class="grid h-6 w-6 shrink-0 place-items-center rounded-full bg-wise-100 font-bold text-wise-700">4</span> Make 2-3 commitments to live by them.</li>
                    </ol>
                    <p class="mt-4 text-sm text-navy-400">There are no right answers. Go with your gut, it knows.</p>
                    <p class="mt-3 flex items-start gap-2 rounded-2xl bg-emerald-50 px-4 py-3 text-sm leading-relaxed text-emerald-800">
                        <x-icon name="shield-check" class="mt-0.5 h-4 w-4 shrink-0" />
                        <span><strong>Private &amp; confidential:</strong> your selections stay in your browser and aren't stored unless you choose to save them.</span>
                    </p>
                    <button @click="start()" class="btn-accent btn-lg mt-6 w-full">Begin, there are no wrong answers</button>
                    <p class="mt-3 text-center text-[11px] text-navy-400">Adapted from <em>Identity and Destiny</em> by Tom &amp; Pam Wolf.</p>
                </div>
            </div>

            {{-- ============ NARROW ROUNDS ============ --}}
            <div x-show="phase === 'narrow'" x-cloak class="mt-10">
                <div class="text-center">
                    <h2 class="font-display text-xl font-bold text-navy-900" x-text="round < 3 ? 'Which of these resonate with you?' : 'Now, your top 5'"></h2>
                    <p class="mt-1 text-navy-500">
                        <span x-show="round < 3">Tap the ones that matter. Keep up to <strong x-text="target()"></strong>.</span>
                        <span x-show="round === 3" x-cloak>From your 10, choose the <strong>5</strong> you couldn't live without.</span>
                    </p>
                    <p class="mt-3 font-display text-2xl font-extrabold" :class="canContinue() ? 'text-emerald-600' : 'text-wise-600'">
                        <span x-text="selected.length"></span><span class="text-navy-300" x-text="'/' + target()"></span>
                    </p>
                    <p class="text-xs text-navy-400" x-show="selected.length < 5" x-cloak>Keep at least 5 to continue</p>
                </div>

                <div class="mt-6 grid grid-cols-2 gap-2.5 sm:grid-cols-3 md:grid-cols-4">
                    <template x-for="v in pool" :key="v">
                        <button @click="toggle(v)"
                                class="flex items-center justify-center gap-1.5 rounded-xl bg-white px-3 py-3 text-center ring-2 transition-all duration-150 active:scale-95"
                                :class="selected.includes(v) ? 'ring-wise-500 bg-wise-50 shadow-wise -translate-y-0.5' : 'ring-navy-100 hover:ring-wise-300'"
                                :disabled="!selected.includes(v) && selected.length >= target()">
                            <svg x-show="selected.includes(v)" x-cloak class="h-3.5 w-3.5 shrink-0 text-wise-600" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
                            <span class="font-display text-sm font-bold text-navy-900" x-text="v"></span>
                        </button>
                    </template>
                </div>

                <div class="mt-8 flex justify-center gap-3">
                    <button @click="back()" class="btn-ghost">Back</button>
                    <button @click="next()" class="btn-accent btn-lg" :disabled="!canContinue()" :class="!canContinue() && 'opacity-40 pointer-events-none'">
                        <span x-text="round < 3 ? 'Continue' : 'These are my five'"></span>
                    </button>
                </div>
            </div>

            {{-- ============ RESULT ============ --}}
            <div x-show="phase === 'result'" x-cloak class="mt-10">
                <div class="text-center">
                    <h2 class="font-display text-2xl font-bold text-navy-900">Your core values</h2>
                    <p class="mx-auto mt-2 max-w-xl text-navy-600">
                        Every budget line, every investment, every "yes" and "no", measured against these five.
                    </p>
                </div>

                <div class="mx-auto mt-8 grid max-w-xl gap-3 sm:grid-cols-2">
                    <template x-for="(v, i) in top5" :key="v">
                        <div class="card flex items-center gap-4 p-5" :class="i === 0 && 'sm:col-span-2 ring-2 ring-wise-400 shadow-wise'">
                            <span class="grid h-11 w-11 shrink-0 place-items-center rounded-2xl bg-wise-400 font-display text-lg font-extrabold text-navy-950" x-text="i + 1"></span>
                            <span class="font-display text-lg font-bold text-navy-900" x-text="v"></span>
                        </div>
                    </template>
                </div>

                {{-- Commitments --}}
                <div class="card mx-auto mt-6 max-w-xl p-6">
                    <h3 class="flex items-center gap-2 font-display font-bold text-navy-900"><x-icon name="check-circle" class="h-5 w-5 text-wise-600" /> Your commitments</h3>
                    <p class="mt-1 text-sm text-navy-500">Name 2-3 things you'll start doing or change to live by these values.</p>
                    <div class="mt-4 space-y-3">
                        <template x-for="(c, i) in commitments" :key="i">
                            <div class="flex items-center gap-3">
                                <span class="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-navy-50 font-display text-sm font-bold text-navy-500" x-text="i + 1"></span>
                                <input type="text" x-model="commitments[i]" :placeholder="i < 2 ? 'I will…' : 'I will… (optional)'"
                                       class="min-w-0 flex-1 rounded-xl border-navy-200 px-3 py-2 text-sm focus:border-wise-400 focus:ring-wise-400">
                            </div>
                        </template>
                    </div>
                </div>

                {{-- PDF + Save --}}
                <div class="mx-auto mt-6 grid max-w-xl gap-4 sm:grid-cols-2">
                    <div class="card flex items-center justify-between gap-3 p-6" x-data="{ busy: false }">
                        <h3 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</h3>
                        <button @click="busy = true; window.downloadToolPdf('values-clarification', 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>
                    <div class="card p-6" x-data="{ email: '', saved: false, saving: false, error: '' }">
                        <h3 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 it</h3>
                        <template x-if="!saved">
                            <div class="mt-3">
                                @auth
                                    <button @click="saving = true; savePlan().then(() => { saved = true; saving = false })" class="btn-accent w-full" :disabled="saving">
                                        <span x-show="!saving">Save to dashboard</span><span x-cloak x-show="saving">Saving…</span>
                                    </button>
                                @else
                                    <div class="flex gap-2">
                                        <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</span><span x-cloak x-show="saving">…</span>
                                        </button>
                                    </div>
                                @endauth
                                <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 text-sm font-semibold text-emerald-600"><x-icon name="check-circle" class="h-4 w-4" /> Saved! Let your values lead.</p></template>
                    </div>
                </div>

                <div class="mt-8 flex justify-center gap-3">
                    <button @click="reset()" class="btn-ghost"><x-icon name="refresh" class="h-4 w-4" /> Start over</button>
                    <a href="{{ route('tools.show', 'wealth-goals') }}" class="btn-primary">Set value-driven goals <x-icon name="arrow-right" class="h-4 w-4" /></a>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        function valuesSort() {
            const ALL = [
                'Acceptance', 'Accountability', 'Accomplishment', 'Attitude', 'Authenticity', 'Balance', 'Boldness', 'Character',
                'Collaboration', 'Commitment', 'Compassion', 'Competence', 'Confidence', 'Contentment', 'Courage', 'Creativity',
                'Dedication', 'Dependability', 'Devotion', 'Discipline', 'Discovery', 'Diversity', 'Efficiency', 'Empathy',
                'Encouragement', 'Endurance', 'Enthusiasm', 'Excellence', 'Fairness', 'Family', 'Fitness', 'Generosity',
                'Gentleness', 'Goodness', 'Growth', 'Honesty', 'Honor', 'Hope', 'Humility', 'Humor',
                'Independence', 'Integrity', 'Intimacy', 'Joy', 'Justice', 'Kindness', 'Leadership', 'Learning',
                'Love', 'Loyalty', 'Obedience', 'Openness', 'Order', 'Passion', 'Patience', 'Peace',
                'Perseverance', 'Personal Growth', 'Quality', 'Relationship', 'Reliability', 'Respect', 'Sacrifice', 'Security',
                'Self-control', 'Self-discipline', 'Selflessness', 'Simplicity', 'Spirituality', 'Steadfast', 'Submission', 'Teachable',
                'Teamwork', 'Thankfulness', 'Tranquility', 'Transparency', 'Trustworthiness', 'Truth', 'Unity', 'Wisdom',
            ];

            return {
                phase: 'intro',     // intro | narrow | result
                round: 0,           // 0..3 → targets 40, 20, 10, 5
                targets: [40, 20, 10, 5],
                pool: [],
                selected: [],
                history: [],
                top5: [],
                commitments: ['', '', ''],

                target() { return this.targets[this.round]; },
                stepIndex() { return this.phase === 'result' ? 4 : this.round; },
                canContinue() {
                    const n = this.selected.length;
                    return this.round < 3 ? (n >= 5 && n <= this.target()) : (n === 5);
                },

                scrollTop() { window.scrollTo({ top: 0, behavior: 'smooth' }); },

                start() {
                    this.phase = 'narrow';
                    this.round = 0;
                    this.pool = [...ALL];
                    this.selected = [];
                    this.history = [];
                    this.scrollTop();
                },

                toggle(v) {
                    if (this.selected.includes(v)) {
                        this.selected = this.selected.filter((x) => x !== v);
                    } else if (this.selected.length < this.target()) {
                        this.selected.push(v);
                    }
                },

                next() {
                    if (!this.canContinue()) return;
                    if (this.round < 3) {
                        this.history.push({ pool: [...this.pool], selected: [...this.selected] });
                        this.pool = [...this.selected];
                        this.selected = [];
                        this.round++;
                        this.scrollTop();
                    } else {
                        this.top5 = [...this.selected];
                        this.phase = 'result';
                        this.scrollTop();
                        setTimeout(() => window.celebrate?.(), 400);
                    }
                },

                back() {
                    if (this.phase === 'result') {
                        this.phase = 'narrow';
                        this.selected = [...this.top5];
                        this.scrollTop();
                        return;
                    }
                    if (this.round === 0) {
                        this.phase = 'intro';
                        this.scrollTop();
                        return;
                    }
                    const h = this.history.pop();
                    this.pool = h.pool;
                    this.selected = h.selected;
                    this.round--;
                    this.scrollTop();
                },

                reset() {
                    this.phase = 'intro';
                    this.round = 0;
                    this.pool = [];
                    this.selected = [];
                    this.history = [];
                    this.top5 = [];
                    this.commitments = ['', '', ''];
                    this.scrollTop();
                },

                cleanCommitments() { return this.commitments.map((c) => c.trim()).filter(Boolean); },

                pdfPayload() {
                    const commits = this.cleanCommitments();
                    const sections = [
                        { title: 'My top 5 core values', rows: this.top5.map((v, i) => ['Value ' + (i + 1), v]) },
                    ];
                    if (commits.length) {
                        sections.push({ title: 'My commitments', rows: commits.map((c, i) => ['Commitment ' + (i + 1), c]) });
                    }
                    return {
                        highlight: { value: this.top5[0] ?? ', ', label: 'Your number-one core value' },
                        sections,
                        note: 'Measure every money decision against these five. Revisit when life changes: moneywise.co.ke/tools/values-clarification',
                    };
                },

                savePlan(email = null) {
                    return fetch('{{ route('tools.save', 'values-clarification') }}', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
                        body: JSON.stringify({
                            email,
                            label: 'My core values',
                            inputs: { top5: this.top5, commitments: this.cleanCommitments() },
                            outputs: { values: this.top5 },
                        }),
                    });
                },
            };
        }
    </script>
    @endpush
</x-layouts.site>
