<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Monzo Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
</head>
<body class="bg-gray-50 font-sans" x-data="dashboard()">
    <div class="min-h-screen">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex justify-between items-center py-4">
                    <h1 class="text-2xl font-bold text-gray-900">Monzo Dashboard</h1>
                    <button 
                        @click="refreshData()"
                        class="bg-pink-600 hover:bg-pink-700 text-white px-4 py-2 rounded-lg transition-colors"
                        :disabled="loading"
                    >
                        <span x-show="!loading">Refresh</span>
                        <span x-show="loading">Loading...</span>
                    </button>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <!-- Error Message -->
            <div x-show="error" class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
                <p x-text="error"></p>
            </div>

            <!-- Loading State -->
            <div x-show="loading && !accounts.length" class="text-center py-12">
                <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-pink-600 mx-auto"></div>
                <p class="mt-4 text-gray-600">Loading your financial data...</p>
            </div>

            <!-- Account Cards - Side by Side Layout -->
            <div x-show="!loading || accounts.length" class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <template x-for="account in accounts" :key="account.id">
                    <div class="space-y-6">
                        <!-- Account Balance Card -->
                        <div class="bg-white rounded-xl shadow-sm border p-6">
                            <div class="flex justify-between items-start mb-4">
                                <div>
                                    <h2 class="text-xl font-semibold text-gray-900" x-text="account.description"></h2>
                                    <p class="text-gray-500 text-sm" x-text="account.id"></p>
                                </div>
                                <div class="text-right">
                                    <p class="text-2xl font-bold text-gray-900" x-text="formatCurrency(account.balance?.balance || 0)"></p>
                                    <p class="text-sm text-gray-500">Available Balance</p>
                                    <p class="text-sm text-gray-600" x-text="'Total: ' + formatCurrency(account.balance?.total_balance || 0)"></p>
                                    <p class="text-sm text-red-600" x-text="'Spent today: ' + formatCurrency(account.balance?.spend_today || 0)"></p>
                                </div>
                            </div>
                        </div>

                        <!-- Account Pots -->
                        <div x-show="getAccountPots(account.id).length > 0" class="bg-white rounded-xl shadow-sm border p-6">
                            <h3 class="text-lg font-semibold text-gray-900 mb-4">Pots</h3>
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <template x-for="pot in getAccountPots(account.id)" :key="pot.id">
                                    <div class="bg-gray-50 rounded-lg p-4">
                                        <div class="flex justify-between items-start mb-2">
                                            <h4 class="font-semibold text-gray-900" x-text="pot.name"></h4>
                                            <span 
                                                class="px-2 py-1 text-xs rounded-full"
                                                :class="pot.deleted ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'"
                                                x-text="pot.deleted ? 'Deleted' : 'Active'"
                                            ></span>
                                        </div>
                                        <p class="text-lg font-bold text-gray-900" x-text="formatCurrency(pot.balance)"></p>
                                        <p class="text-sm text-gray-500" x-text="formatDate(pot.updated, true)"></p>
                                    </div>
                                </template>
                            </div>
                        </div>

                        <!-- Account Transactions -->
                        <div class="bg-white rounded-xl shadow-sm border p-6">
                            <h3 class="text-lg font-semibold text-gray-900 mb-4">Recent Transactions</h3>
                            <div class="space-y-3 max-h-96 overflow-y-auto">
                                <template x-for="transaction in account.transactions" :key="transaction.id">
                                    <div class="flex justify-between items-center py-2 border-b border-gray-100">
                                        <div class="flex-1">
                                            <p class="font-medium text-gray-900" x-text="transaction.description"></p>
                                            <div class="flex items-center space-x-2 text-sm text-gray-500">
                                                <span x-text="formatDate(transaction.created)"></span>
                                                <span x-show="transaction.category" x-text="'• ' + transaction.category"></span>
                                            </div>
                                        </div>
                                        <div class="text-right">
                                            <p 
                                                class="font-semibold"
                                                :class="transaction.amount >= 0 ? 'text-green-600' : 'text-red-600'"
                                                x-text="formatCurrency(transaction.amount)"
                                            ></p>
                                        </div>
                                    </div>
                                </template>
                                <div x-show="!account.transactions?.length" class="text-gray-500 text-center py-4">
                                    No transactions found
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </main>
    </div>

    <script>
        function dashboard() {
            return {
                loading: false,
                error: null,
                accounts: [],
                pots: [],

                async init() {
                    await this.loadData();
                },

                async loadData() {
                    this.loading = true;
                    this.error = null;
                    
                    try {
                        // Load accounts
                        const accountsResponse = await fetch('/api/accounts');
                        if (!accountsResponse.ok) {
                            throw new Error(`HTTP ${accountsResponse.status}: ${await accountsResponse.text()}`);
                        }
                        this.accounts = await accountsResponse.json();

                        // Load balance, transactions, and pots for each account
                        for (let account of this.accounts) {
                            try {
                                const balanceResponse = await fetch(`/api/accounts/${account.id}/balance`);
                                if (balanceResponse.ok) {
                                    account.balance = await balanceResponse.json();
                                }

                                const transactionsResponse = await fetch(`/api/accounts/${account.id}/transactions?limit=10`);
                                if (transactionsResponse.ok) {
                                    account.transactions = await transactionsResponse.json();
                                }

                                const potsResponse = await fetch(`/api/accounts/${account.id}/pots`);
                                if (potsResponse.ok) {
                                    account.pots = await potsResponse.json();
                                }
                            } catch (e) {
                                console.warn(`Failed to load data for account ${account.id}:`, e);
                            }
                        }

                        // Load all pots for backwards compatibility
                        try {
                            const potsResponse = await fetch('/api/pots');
                            if (potsResponse.ok) {
                                this.pots = await potsResponse.json();
                            }
                        } catch (e) {
                            console.warn('Failed to load pots:', e);
                        }

                    } catch (error) {
                        this.error = error.message;
                        console.error('Error loading data:', error);
                    } finally {
                        this.loading = false;
                    }
                },

                async refreshData() {
                    await this.loadData();
                },

                getAccountPots(accountId) {
                    const account = this.accounts.find(acc => acc.id === accountId);
                    return account && account.pots ? account.pots : [];
                },

                formatCurrency(amount) {
                    return new Intl.NumberFormat('en-GB', {
                        style: 'currency',
                        currency: 'GBP'
                    }).format(amount / 100);
                },

                formatDate(dateString, includeTime = false) {
                    const date = new Date(dateString);
                    const options = {
                        year: 'numeric',
                        month: 'short',
                        day: 'numeric'
                    };
                    
                    if (includeTime) {
                        options.hour = '2-digit';
                        options.minute = '2-digit';
                    }
                    
                    return date.toLocaleDateString('en-GB', options);
                }
            };
        }
    </script>
</body>
</html>
