<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Omniscience API</title>
    <link href="https://fonts.googleapis.com/css2?family=Prompt:wght@400;500;600&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <style>
        body { font-family: 'Prompt', sans-serif; background-color: #111111; color: #e5e5e5; }
        [x-cloak] { display: none !important; }
    </style>
</head>
<body class="bg-zinc-950 text-gray-200" x-data="apiTester">
    <!-- Warning Banner -->
    <div class="items-center bg-yellow-600/10 border-b border-yellow-600/20">
        <div class="max-w-4xl mx-auto px-4 py-3">
            <div class="flex gap-2 text-yellow-500">
                <i data-lucide="alert-circle" class="w-5 h-5"></i>
                <p class="text-sm">Access limited to approved users - all activities are monitored.</p>
            </div>
        </div>
    </div>

    <div class="max-w-4xl mx-auto py-16 px-4">
        <div class="space-y-8">
            <!-- Header -->
            <header class="flex items-center gap-6">
                <div class="w-16 h-16 bg-zinc-900 rounded-lg flex items-center justify-center border border-zinc-800">
                    <i data-lucide="eye" class="w-10 h-10 text-blue-500"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-semibold text-white">Omniscience API</h1>
                    <p class="text-sm text-gray-400">O LORD, thou knowest it altogether</p>
                </div>
            </header>

            <!-- Authentication Section -->
            <div class="bg-zinc-900/50 backdrop-blur rounded-xl border border-zinc-800 p-6 space-y-4">
                <h2 class="text-sm font-medium text-gray-400 flex items-center gap-2">
                    <i data-lucide="key" class="w-4 h-4"></i>
                    Authentication
                </h2>
                <div class="flex gap-4">
                    <input type="password" x-model="apiKey" placeholder="Enter API Key" 
                           class="flex-1 bg-zinc-800/50 border border-zinc-700 rounded-lg p-2 text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500/50">
                    <button @click="getToken" 
                            class="bg-blue-600 hover:bg-blue-700 px-6 py-2 rounded-lg flex items-center gap-2 transition-all">
                        <i data-lucide="key" class="w-4 h-4"></i>
                    </button>
                </div>
                <template x-if="token">
                    <div class="space-y-4">
                        <div class="bg-zinc-800/50 p-3 rounded-lg border border-zinc-700">
                            <p class="font-mono text-sm break-all text-gray-300" x-text="token"></p>
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <div class="bg-zinc-800/50 p-3 rounded-lg border border-zinc-700">
                                <p class="text-xs text-gray-400 uppercase mb-1">User</p>
                                <p class="text-sm text-gray-300" x-text="tokenData.sub || 'Unknown'"></p>
                            </div>
                            <div class="bg-zinc-800/50 p-3 rounded-lg border border-zinc-700">
                                <p class="text-xs text-gray-400 uppercase mb-1">Token Expiry</p>
                                <p class="text-sm" 
                                   :class="countdown === 'Token expired' ? 'text-red-500' : 'text-green-500'" 
                                   x-text="countdown"></p>
                            </div>
                        </div>
                    </div>
                </template>
            </div>

            <!-- Request Section -->
            <template x-if="token">
                <div class="bg-zinc-900/50 backdrop-blur rounded-xl border border-zinc-800 p-6 space-y-6">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs text-gray-400 uppercase mb-2">Service</label>
                            <select x-model="selectedService"
                                    class="w-full bg-zinc-800/50 border border-zinc-700 rounded-lg p-2 text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500/50">
                                <template x-for="service in Object.keys(availableEndpoints)" :key="service">
                                    <option :value="service" x-text="service.toUpperCase()"></option>
                                </template>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs text-gray-400 uppercase mb-2">Endpoint</label>
                            <select x-model="selectedEndpoint"
                                    class="w-full bg-zinc-800/50 border border-zinc-700 rounded-lg p-2 text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500/50">
                                <template x-for="[endpoint, label] in Object.entries(currentEndpoints)" :key="endpoint">
                                    <option :value="endpoint" x-text="label"></option>
                                </template>
                            </select>
                        </div>
                    </div>
                    <div>
                        <div class="flex justify-between items-center mb-2">
                            <label class="text-xs text-gray-400 uppercase">Request Body</label>
                            <button @click="advancedMode = !advancedMode" class="text-xs text-blue-400 hover:text-blue-300">
                                <span x-text="advancedMode ? 'Simple' : 'Advanced'"></span>
                            </button>
                        </div>
                        <template x-if="!advancedMode">
                            <input type="text" x-model="pid" placeholder="Enter PID"
                                   class="w-full bg-zinc-800/50 border border-zinc-700 rounded-lg p-2 text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500/50">
                        </template>
                        <template x-if="advancedMode">
                            <textarea x-model="requestBody" rows="5"
                                    class="w-full bg-zinc-800/50 border border-zinc-700 rounded-lg p-2 text-gray-200 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/50"></textarea>
                        </template>
                    </div>
                    <button @click="makeRequest" 
                            class="w-full bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 px-4 py-2 rounded-lg flex items-center justify-center gap-2 transition-colors group">
                        <span class="text-gray-300 group-hover:text-white">Send Request</span>
                    </button>
                    
                    <!-- Enhanced Response Display -->
                    <template x-if="response">
                        <div class="space-y-4">
                            <h3 class="text-sm font-medium text-gray-400 flex items-center gap-2">
                                <i data-lucide="file-text" class="w-4 h-4"></i>
                                Response
                            </h3>
                            <template x-if="isImageResponse">
                                <div class="rounded-lg overflow-hidden">
                                    <img :src="imageData" alt="Response Image" class="max-w-full h-auto">
                                </div>
                            </template>
                            <template x-if="!isImageResponse && response.data">
                                <div class="space-y-4">
                                    <!-- Customer Information -->
                                    <div class="bg-zinc-800/50 p-4 rounded-lg border border-zinc-700">
                                        <div class="grid grid-cols-2 gap-4">
                                            <template x-if="response.data.search.customer && response.data.search.customer[0]">
                                                <div class="space-y-4">
                                                    <div>
                                                        <p class="text-xs text-gray-400 uppercase mb-1">Customer Details</p>
                                                        <p class="text-sm text-gray-200" x-text="response.data.search.customer[0].firstName + ' ' + response.data.search.customer[0].lastName"></p>
                                                        <p class="text-sm text-gray-400" x-text="'ID: ' + response.data.search.customer[0].idNumber"></p>
                                                    </div>
                                                    <div>
                                                        <p class="text-xs text-gray-400 uppercase mb-1">Membership</p>
                                                        <div class="flex items-center gap-2">
                                                            <span class="px-2 py-1 rounded-md bg-blue-500/20 text-blue-400 text-xs" x-text="response.data.search.customer[0].grading"></span>
                                                            <span class="px-2 py-1 rounded-md bg-zinc-700/50 text-gray-300 text-xs" x-text="response.data.search.customer[0].trueCardLevel"></span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </template>
                                        </div>
                                    </div>
                                    
                                    <!-- Assets/Services -->
                                    <template x-if="response.data.search.customer && response.data.search.customer[0].assetList">
                                        <div class="space-y-2">
                                            <p class="text-xs text-gray-400 uppercase">Services</p>
                                            <div class="space-y-2">
                                                <template x-for="asset in response.data.search.customer[0].assetList" :key="asset.serviceId">
                                                    <div class="bg-zinc-800/50 p-4 rounded-lg border border-zinc-700">
                                                        <div class="flex justify-between items-start mb-2">
                                                            <div>
                                                                <p class="text-sm font-medium text-gray-200" x-text="asset.serviceId"></p>
                                                                <p class="text-xs text-gray-400" x-text="asset.productName"></p>
                                                            </div>
                                                            <span class="px-2 py-1 rounded-md text-xs"
                                                                  :class="asset.status === 'Active' ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'"
                                                                  x-text="asset.status"></span>
                                                        </div>
                                                        <div class="grid grid-cols-2 gap-2 text-xs text-gray-400">
                                                            <div>
                                                                <span>Start Date: </span>
                                                                <span class="text-gray-300" x-text="asset.startDate"></span>
                                                            </div>
                                                            <div x-show="asset.endDate">
                                                                <span>End Date: </span>
                                                                <span class="text-gray-300" x-text="asset.endDate"></span>
                                                            </div>
                                                            <div x-show="asset.pricePlan" class="col-span-2">
                                                                <span>Plan: </span>
                                                                <span class="text-gray-300" x-text="asset.pricePlan"></span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </template>
                                            </div>
                                        </div>
                                    </template>
                                </div>
                            </template>
                        </div>
                    </template>
                </div>
            </template>
        </div>
    </div>

    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('apiTester', () => ({
                apiKey: '',
                token: '',
                tokenData: {},
                countdown: '',
                timer: null,
                selectedService: '',
                selectedEndpoint: '',
                pid: '',
                advancedMode: false,
                requestBody: '{\n  "pid": ""\n}',
                response: null,
                isImageResponse: false,
                imageData: '',
                availableEndpoints: {},

                init() {
                    this.startCountdown();
                    this.$watch('tokenData', () => this.startCountdown());
                    this.$watch('selectedService', (value) => {
                        this.selectedEndpoint = Object.keys(this.currentEndpoints)[0];
                    });
                },

                startCountdown() {
                    if (this.timer) clearInterval(this.timer);
                    if (!this.tokenData.exp) return;

                    this.updateCountdown();
                    this.timer = setInterval(() => {
                        this.updateCountdown();
                    }, 1000);
                },

                updateCountdown() {
                    if (!this.tokenData.exp) {
                        this.countdown = '';
                        return;
                    }

                    const timeLeft = this.tokenData.exp - Math.floor(Date.now() / 1000);
                    if (timeLeft <= 0) {
                        this.countdown = 'Token expired';
                        this.token = '';
                        this.tokenData = {};
                        if (this.timer) clearInterval(this.timer);
                        return;
                    }

                    const minutes = Math.floor(timeLeft / 60);
                    const seconds = timeLeft % 60;
                    this.countdown = `${minutes}m ${seconds.toString().padStart(2, '0')}s`;
                },

                get currentEndpoints() {
                    if (!this.selectedService || !this.availableEndpoints[this.selectedService]) return {};
                    return this.availableEndpoints[this.selectedService];
                },

                async getToken() {
                    try {
                        const res = await fetch('https://omniscience.wenhe.bar/token', {
                            method: 'POST',
                            headers: { 'X-Secret': this.apiKey }
                        });
                        if (!res.ok) throw new Error('Failed to get token');
                        const data = await res.json();
                        this.token = data.access_token;

                        const base64Url = this.token.split('.')[1];
                        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                        this.tokenData = JSON.parse(atob(base64));
                        
                        this.availableEndpoints = {};
                        Object.entries(this.tokenData.permissions).forEach(([service, endpoints]) => {
                            this.availableEndpoints[service] = {};
                            endpoints.forEach(endpoint => {
                                this.availableEndpoints[service][endpoint] = endpoint
                                    .split('_')
                                    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
                                    .join(' ');
                            });
                        });
                        
                        this.selectedService = Object.keys(this.availableEndpoints)[0];
                        this.selectedEndpoint = Object.keys(this.availableEndpoints[this.selectedService])[0];

                    } catch (error) {
                        alert('Error: ' + error.message);
                    }
                },

                async makeRequest() {
                    try {
                        let requestData = this.advancedMode ? JSON.parse(this.requestBody) : { pid: this.pid };
                        const res = await fetch(`https://omniscience.wenhe.bar/v1/${this.selectedService}/${this.selectedEndpoint}`, {
                            method: 'POST',
                            headers: {
                                'Authorization': `Bearer ${this.token}`,
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(requestData)
                        });

                        if (!res.ok) throw new Error('Request failed');
                        const data = await res.json();
                        this.response = data;
                        
                        if (this.selectedEndpoint === 'pop_image' && data.data?.image) {
                            this.isImageResponse = true;
                            this.imageData = `${data.data.mineType},${data.data.image}`;
                        } else {
                            this.isImageResponse = false;
                            this.imageData = '';
                        }
                    } catch (error) {
                        alert('Error: ' + error.message);
                    }
                }
            }))
        });

        lucide.createIcons();
    </script>
</body>
</html>