import React, { useState, useEffect } from 'react';
import logo from './assets/logo.png';
import { auth, googleProvider } from './firebase';
import { signInWithPopup } from 'firebase/auth';
import './App.css';

interface DeveloperApiKey {
  id: number;
  apiKey: string;
  name: string;
  userId: number;
  userType: string;
  ownerIdentifier: string;
  active: boolean;
  createdAt: string;
  lastUsedAt?: string;
  writeAccess?: boolean;
  permissions?: string;
  appId?: number;
}

interface UserSession {
  token: string;
  id: number;
  name: string;
  emailOrMobile: string;
  roleOrType: string;
}

const BACKEND_URL = 'https://cmsapi.rit-services.in';

function App() {
  // Auth State
  const [session, setSession] = useState<UserSession | null>(null);
  const [loginType, setLoginType] = useState<'CUSTOMER' | 'SYSTEM'>('SYSTEM');
  const [loginEmail, setLoginEmail] = useState('');
  const [loginPassword, setLoginPassword] = useState('');

  // First-time registration flow states (Student Google login)
  const [showCustomerMobilePrompt, setShowCustomerMobilePrompt] = useState(false);
  const [customerPendingEmail, setCustomerPendingEmail] = useState('');
  const [customerPendingName, setCustomerPendingName] = useState('');
  const [customerMobileNumber, setCustomerMobileNumber] = useState('');

  // Key Management State
  const [keys, setKeys] = useState<DeveloperApiKey[]>([]);
  const [newKeyName, setNewKeyName] = useState('');
  const [showSecrets, setShowSecrets] = useState<Record<number, boolean>>({});
  const [writeAccess, setWriteAccess] = useState(false);
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([
    'READ_PRODUCTS', 'READ_STALLS', 'READ_ORDERS', 'READ_WALLETS'
  ]);

  // Apps Management State
  const [apps, setApps] = useState<any[]>([]);
  const [newAppName, setNewAppName] = useState('');
  const [newAppDesc, setNewAppDesc] = useState('');

  // UI Tabs & Feedback
  const [activeTab, setActiveTab] = useState<'keys' | 'playground' | 'docs' | 'logs'>('keys');
  const [logs, setLogs] = useState<any[]>([]);
  const [logPage, setLogPage] = useState(0);
  const [logTotalPages, setLogTotalPages] = useState(0);
  const [logTotalItems, setLogTotalItems] = useState(0);
  const [selectedLog, setSelectedLog] = useState<any | null>(null);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // Playground Sandbox State
  const [selectedKey, setSelectedKey] = useState('');
  const [selectedEndpoint, setSelectedEndpoint] = useState('/api/developer/v1/validate');
  const [customKeyInput, setCustomKeyInput] = useState('');
  const [playgroundLoading, setPlaygroundLoading] = useState(false);
  const [playgroundStatus, setPlaygroundStatus] = useState<number | null>(null);
  const [playgroundResponse, setPlaygroundResponse] = useState<any | null>(null);

  // Simulated Attack State
  const [attackLoading, setAttackLoading] = useState(false);
  const [attackStatus, setAttackStatus] = useState<number | null>(null);
  const [attackResponse, setAttackResponse] = useState<any | null>(null);

  // Restore session from localStorage on mount
  useEffect(() => {
    const saved = localStorage.getItem('developer_session');
    if (saved) {
      try {
        const parsed = JSON.parse(saved);
        setSession(parsed);
      } catch (e) {
        localStorage.removeItem('developer_session');
      }
    }
  }, []);

  // Fetch keys and apps when session changes
  useEffect(() => {
    if (session) {
      fetchKeys();
      if (session.roleOrType === 'CUSTOMER') {
        fetchApps();
      }
    } else {
      setKeys([]);
      setApps([]);
    }
  }, [session]);

  const clearMessages = () => {
    setError(null);
    setSuccess(null);
  };

  const showNotification = (type: 'success' | 'error', msg: string) => {
    if (type === 'success') {
      setSuccess(msg);
      setTimeout(() => setSuccess(null), 4000);
    } else {
      setError(msg);
      setTimeout(() => setError(null), 5000);
    }
  };

  const handleCustomerGoogleSignIn = async () => {
    setLoading(true);
    clearMessages();
    try {
      const result = await signInWithPopup(auth, googleProvider);
      const user = result.user;
      if (user.email) {
        const checkRes = await fetch(`${BACKEND_URL}/api/auth/check-email`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email: user.email }),
        });
        const checkData = await checkRes.json();
        
        if (checkData.exists) {
          await executeCustomerFirebaseLogin(user.email, user.displayName || "Google User");
        } else {
          setCustomerPendingEmail(user.email);
          setCustomerPendingName(user.displayName || "Google User");
          setShowCustomerMobilePrompt(true);
        }
      } else {
        throw new Error('No email found in Google Account.');
      }
    } catch (err: any) {
      showNotification('error', err.message || 'Failed to authenticate with Google');
    } finally {
      setLoading(false);
    }
  };

  const executeCustomerFirebaseLogin = async (email: string, name: string, mobileNumber?: string) => {
    const loginRes = await fetch(`${BACKEND_URL}/api/auth/firebase-login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, name, mobileNumber }),
    });
    const loginData = await loginRes.json();
    if (!loginRes.ok || !loginData.success) {
      throw new Error(loginData.message || 'Google Canteen Login failed');
    }
    
    const sessionData: UserSession = {
      token: loginData.token,
      id: loginData.user.id,
      name: loginData.user.name || 'Customer',
      emailOrMobile: loginData.user.mobileNumber,
      roleOrType: 'CUSTOMER',
    };

    setSession(sessionData);
    localStorage.setItem('developer_session', JSON.stringify(sessionData));
    showNotification('success', `Welcome back, ${sessionData.name}!`);
    setShowCustomerMobilePrompt(false);
  };

  const handleCustomerMobileSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!/^[0-9]{10}$/.test(customerMobileNumber)) {
      showNotification('error', 'Please enter a valid 10-digit mobile number');
      return;
    }
    setLoading(true);
    clearMessages();
    try {
      await executeCustomerFirebaseLogin(customerPendingEmail, customerPendingName, customerMobileNumber);
    } catch (err: any) {
      showNotification('error', err.message || 'Registration failed');
    } finally {
      setLoading(false);
    }
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    clearMessages();

    try {
      const res = await fetch(`${BACKEND_URL}/api/system/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: loginEmail, password: loginPassword }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'System Login failed');

      const sessionData: UserSession = {
        token: data.token,
        id: data.id,
        name: data.name,
        emailOrMobile: data.email,
        roleOrType: data.role,
      };

      setSession(sessionData);
      localStorage.setItem('developer_session', JSON.stringify(sessionData));
      showNotification('success', `Welcome back, ${data.name}!`);
    } catch (err: any) {
      showNotification('error', err.message || 'An error occurred during authentication');
    } finally {
      setLoading(false);
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('developer_session');
    setSession(null);
    clearMessages();
    showNotification('success', 'Logged out successfully');
  };

  const fetchKeys = async () => {
    if (!session) return;
    try {
      const res = await fetch(`${BACKEND_URL}/api/developer-keys`, {
        headers: {
          'Authorization': `Bearer ${session.token}`,
        },
      });
      if (!res.ok) throw new Error('Failed to fetch API keys');
      const data = await res.json();
      setKeys(data);
      if (data.length > 0 && !selectedKey) {
        setSelectedKey(data[0].apiKey);
      }
    } catch (err: any) {
      showNotification('error', err.message);
    }
  };

  const fetchApps = async () => {
    if (!session) return;
    try {
      const res = await fetch(`${BACKEND_URL}/api/developer-apps`, {
        headers: {
          'Authorization': `Bearer ${session.token}`,
        },
      });
      if (!res.ok) throw new Error('Failed to fetch apps');
      const data = await res.json();
      setApps(data);
    } catch (err: any) {
      showNotification('error', err.message);
    }
  };

  const handleCreateApp = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!session) return;
    if (!newAppName.trim()) {
      showNotification('error', 'Please enter a name for the app');
      return;
    }
    setLoading(true);
    clearMessages();
    try {
      const res = await fetch(`${BACKEND_URL}/api/developer-apps`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.token}`,
        },
        body: JSON.stringify({
          name: newAppName,
          description: newAppDesc
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to create app');
      showNotification('success', 'App registered successfully');
      setNewAppName('');
      setNewAppDesc('');
      fetchApps();
    } catch (err: any) {
      showNotification('error', err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteApp = async (appId: number) => {
    if (!session) return;
    if (!window.confirm('Are you sure you want to delete this App? This will also revoke its associated API key.')) return;
    setLoading(true);
    clearMessages();
    try {
      const res = await fetch(`${BACKEND_URL}/api/developer-apps/${appId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${session.token}`,
        },
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to delete app');
      showNotification('success', 'App deleted successfully');
      fetchApps();
      fetchKeys();
    } catch (err: any) {
      showNotification('error', err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateKeyForApp = async (appId: number, name: string) => {
    if (!session) return;
    setLoading(true);
    clearMessages();
    try {
      const permissionsPayload = 'READ_PRODUCTS,READ_STALLS,READ_ORDERS,READ_WALLETS';
      const writeAccessPayload = false;

      const res = await fetch(`${BACKEND_URL}/api/developer-keys`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.token}`,
        },
        body: JSON.stringify({ 
          name: name,
          writeAccess: writeAccessPayload,
          permissions: permissionsPayload,
          appId: appId
        }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to generate key');

      showNotification('success', 'API Key generated successfully');
      fetchKeys();
    } catch (err: any) {
      showNotification('error', err.message);
    } finally {
      setLoading(false);
    }
  };

  const fetchLogs = async (page = 0) => {
    if (!session) return;
    setLoading(true);
    try {
      const res = await fetch(`${BACKEND_URL}/api/developer-keys/logs?page=${page}&size=10`, {
        headers: {
          'Authorization': `Bearer ${session.token}`,
        },
      });
      if (!res.ok) throw new Error('Failed to fetch API logs');
      const data = await res.json();
      setLogs(data.content);
      setLogPage(data.currentPage);
      setLogTotalPages(data.totalPages);
      setLogTotalItems(data.totalItems);
    } catch (err: any) {
      showNotification('error', err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (activeTab === 'logs' && session) {
      fetchLogs(0);
    }
  }, [activeTab, session]);

  const handleCreateKey = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!session) return;
    if (!newKeyName.trim()) {
      showNotification('error', 'Please enter a name for the API key');
      return;
    }
    setLoading(true);
    clearMessages();

    try {
      const isSystemUser = session.roleOrType === 'MASTER' || session.roleOrType === 'MANAGER';
      const permissionsPayload = isSystemUser 
        ? selectedPermissions.join(',') 
        : 'READ_PRODUCTS,READ_STALLS,READ_ORDERS,READ_WALLETS';
      const writeAccessPayload = isSystemUser ? writeAccess : false;

      const res = await fetch(`${BACKEND_URL}/api/developer-keys`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.token}`,
        },
        body: JSON.stringify({ 
          name: newKeyName,
          writeAccess: writeAccessPayload,
          permissions: permissionsPayload
        }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to generate key');

      showNotification('success', 'API Key generated successfully');
      setNewKeyName('');
      fetchKeys();
    } catch (err: any) {
      showNotification('error', err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleRevokeKey = async (id: number) => {
    if (!session) return;
    if (!window.confirm('Are you sure you want to revoke this API key? Applications using this key will immediately lose access.')) return;
    setLoading(true);
    clearMessages();

    try {
      const res = await fetch(`${BACKEND_URL}/api/developer-keys/${id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${session.token}`,
        },
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to revoke key');

      showNotification('success', 'API Key revoked and deleted');
      fetchKeys();
    } catch (err: any) {
      showNotification('error', err.message);
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    showNotification('success', 'Copied to clipboard!');
  };

  const navigateToSection = (sectionId: string) => {
    setActiveTab('docs');
    setTimeout(() => {
      const element = document.getElementById(sectionId);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    }, 100);
  };

  const downloadPostmanCollection = () => {
    const keyToUse = customKeyInput || selectedKey || 'YOUR_API_KEY_HERE';
    const collectionName = 'Tillo Developer API';
    
    const postmanJson = {
      info: {
        name: collectionName,
        schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
        description: 'Postman Collection generated dynamically from Tillo Developer Console to test Developer APIs.'
      },
      variable: [
        {
          key: 'baseUrl',
          value: BACKEND_URL,
          type: 'string'
        },
        {
          key: 'apiKey',
          value: keyToUse,
          type: 'string'
        }
      ],
      item: [
        {
          name: 'Health Check / Validate Key',
          request: {
            method: 'GET',
            header: [
              {
                key: 'X-Developer-Key',
                value: '{{apiKey}}',
                type: 'text'
              }
            ],
            url: {
              raw: '{{baseUrl}}/api/developer/v1/validate',
              host: ['{{baseUrl}}'],
              path: ['api', 'developer', 'v1', 'validate']
            }
          }
        },
        {
          name: 'Get Active Stalls',
          request: {
            method: 'GET',
            header: [
              {
                key: 'X-Developer-Key',
                value: '{{apiKey}}',
                type: 'text'
              }
            ],
            url: {
              raw: '{{baseUrl}}/api/developer/v1/stalls',
              host: ['{{baseUrl}}'],
              path: ['api', 'developer', 'v1', 'stalls']
            }
          }
        },
        {
          name: 'Get Active Products',
          request: {
            method: 'GET',
            header: [
              {
                key: 'X-Developer-Key',
                value: '{{apiKey}}',
                type: 'text'
              }
            ],
            url: {
              raw: '{{baseUrl}}/api/developer/v1/products',
              host: ['{{baseUrl}}'],
              path: ['api', 'developer', 'v1', 'products']
            }
          }
        },
        {
          name: 'Get Wallet Balance (Own)',
          request: {
            method: 'GET',
            header: [
              {
                key: 'X-Developer-Key',
                value: '{{apiKey}}',
                type: 'text'
              }
            ],
            url: {
              raw: '{{baseUrl}}/api/developer/v1/wallet',
              host: ['{{baseUrl}}'],
              path: ['api', 'developer', 'v1', 'wallet']
            }
          }
        },
        {
          name: "Query User's Wallet Balance (By Mobile)",
          request: {
            method: 'GET',
            header: [
              {
                key: 'X-Developer-Key',
                value: '{{apiKey}}',
                type: 'text'
              }
            ],
            url: {
              raw: '{{baseUrl}}/api/developer/v1/wallet?mobileNumber=9876543210',
              host: ['{{baseUrl}}'],
              path: ['api', 'developer', 'v1', 'wallet'],
              query: [
                {
                  key: 'mobileNumber',
                  value: '9876543210'
                }
              ]
            }
          }
        },
        {
          name: 'Get Active Orders',
          request: {
            method: 'GET',
            header: [
              {
                key: 'X-Developer-Key',
                value: '{{apiKey}}',
                type: 'text'
              }
            ],
            url: {
              raw: '{{baseUrl}}/api/developer/v1/orders',
              host: ['{{baseUrl}}'],
              path: ['api', 'developer', 'v1', 'orders']
            }
          }
        }
      ]
    };

    const dataStr = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(postmanJson, null, 2));
    const downloadAnchor = document.createElement('a');
    downloadAnchor.setAttribute('href', dataStr);
    downloadAnchor.setAttribute('download', 'Tillo_Developer_API.postman_collection.json');
    document.body.appendChild(downloadAnchor);
    downloadAnchor.click();
    downloadAnchor.remove();
    showNotification('success', 'Postman Collection downloaded! Import it directly into Postman to start testing.');
  };

  const toggleRevealKey = (id: number) => {
    setShowSecrets(prev => ({ ...prev, [id]: !prev[id] }));
  };

  const executePlayground = async () => {
    const apiKeyToUse = customKeyInput || selectedKey;
    if (!apiKeyToUse) {
      showNotification('error', 'Please select or enter a developer API Key');
      return;
    }

    setPlaygroundLoading(true);
    setPlaygroundStatus(null);
    setPlaygroundResponse(null);

    try {
      const res = await fetch(`${BACKEND_URL}${selectedEndpoint}`, {
        headers: {
          'X-Developer-Key': apiKeyToUse,
        },
      });
      setPlaygroundStatus(res.status);
      const data = await res.json();
      setPlaygroundResponse(data);
    } catch (err: any) {
      setPlaygroundResponse({ error: err.message || 'Network request failed' });
    } finally {
      setPlaygroundLoading(false);
    }
  };

  const runSimulatedAttack = async (attackUrl: string, method: string = 'GET') => {
    const apiKeyToUse = customKeyInput || selectedKey;
    if (!apiKeyToUse) {
      showNotification('error', 'Please select or enter an API Key to simulate the attack');
      return;
    }

    setAttackLoading(true);
    setAttackStatus(null);
    setAttackResponse(null);

    try {
      const options: RequestInit = {
        method,
        headers: {
          'X-Developer-Key': apiKeyToUse,
          'Content-Type': 'application/json',
        },
      };

      if (method === 'POST') {
        options.body = JSON.stringify({ amount: '1000', userId: 1 });
      }

      const res = await fetch(`${BACKEND_URL}${attackUrl}`, options);
      setAttackStatus(res.status);
      const data = await res.json();
      setAttackResponse(data);
    } catch (err: any) {
      setAttackResponse({ error: err.message || 'Request blocked or failed' });
    } finally {
      setAttackLoading(false);
    }
  };

  const isSystemUser = session ? (session.roleOrType === 'MASTER' || session.roleOrType === 'MANAGER') : false;
  const isLimitReached = !isSystemUser && keys.length >= 3;

  return (
    <div className={session ? "api-dashboard-layout" : "api-dashboard-container login-mode"}>
      {/* Notifications */}
      {success && <div className="toast toast-success">{success}</div>}
      {error && <div className="toast toast-error">{error}</div>}

      {!session ? (
        /* Login Panel */
        <div className="login-screen-wrapper">
          <div className="premium-card login-card animate-slideUp">
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: '0.5rem' }}>
              <img src={logo} alt="Branding" style={{ height: '48px', width: 'auto' }} />
            </div>
            <h2>Access Developer Console</h2>
            <p className="login-desc">Use your existing Tillo user credentials or system administrator login to manage API keys.</p>

            <div className="login-type-switch">
              <button
                type="button"
                className={loginType === 'SYSTEM' ? 'active' : ''}
                onClick={() => { setLoginType('SYSTEM'); clearMessages(); }}
              >
                System Admin / Staff
              </button>
              <button
                type="button"
                className={loginType === 'CUSTOMER' ? 'active' : ''}
                onClick={() => { setLoginType('CUSTOMER'); clearMessages(); }}
              >
                Student Portal
              </button>
            </div>

            {loginType === 'SYSTEM' ? (
              <form onSubmit={handleLogin} className="login-form">
                <div className="input-group">
                  <label htmlFor="username">Username</label>
                  <input
                    type="text"
                    id="username"
                    required
                    placeholder="e.g. admin"
                    value={loginEmail}
                    onChange={(e) => setLoginEmail(e.target.value)}
                  />
                </div>
                <div className="input-group">
                  <label htmlFor="password">Password</label>
                  <input
                    type="password"
                    id="password"
                    required
                    placeholder="••••••••"
                    value={loginPassword}
                    onChange={(e) => setLoginPassword(e.target.value)}
                  />
                </div>
                <button type="submit" className="btn-primary w-full" disabled={loading}>
                  {loading ? 'Authenticating...' : 'Sign In to Dashboard'}
                </button>
              </form>
            ) : (
              <div className="customer-login-container">
                {showCustomerMobilePrompt ? (
                  <form onSubmit={handleCustomerMobileSubmit} className="login-form">
                    <div className="input-group">
                      <label htmlFor="customerMobile">10-Digit Mobile Number</label>
                      <input
                        type="tel"
                        id="customerMobile"
                        required
                        pattern="[0-9]{10}"
                        placeholder="9876543210"
                        value={customerMobileNumber}
                        onChange={(e) => setCustomerMobileNumber(e.target.value.replace(/[^0-9]/g, '').slice(0, 10))}
                        disabled={loading}
                      />
                    </div>
                    <button type="submit" className="btn-primary w-full" disabled={loading || customerMobileNumber.length !== 10}>
                      {loading ? 'Registering...' : 'Register & Enter Dashboard'}
                    </button>
                    <button 
                      type="button" 
                      className="btn-revoke w-full" 
                      onClick={() => { setShowCustomerMobilePrompt(false); clearMessages(); }}
                      disabled={loading}
                      style={{ marginTop: '0.5rem', border: '1px solid var(--color-border)', color: 'var(--color-text-secondary)' }}
                    >
                      Cancel
                    </button>
                  </form>
                ) : (
                  <div className="google-signin-wrapper" style={{ marginTop: '0.5rem', display: 'flex', justifyContent: 'center' }}>
                    <button 
                      type="button"
                      className="google-login-btn" 
                      onClick={handleCustomerGoogleSignIn} 
                      disabled={loading}
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        gap: '12px',
                        width: '100%',
                        padding: '12px',
                        backgroundColor: '#ffffff',
                        border: '1px solid #cbd5e1',
                        borderRadius: '12px',
                        color: '#1e293b',
                        fontWeight: '700',
                        cursor: 'pointer',
                        boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
                      }}
                    >
                      {loading ? (
                        <span>Connecting...</span>
                      ) : (
                        <>
                          <svg className="google-icon" viewBox="0 0 24 24" width="20" height="20">
                            <path
                              fill="#4285F4"
                              d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
                            />
                            <path
                              fill="#34A853"
                              d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
                            />
                            <path
                              fill="#FBBC05"
                              d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
                            />
                            <path
                              fill="#EA4335"
                              d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
                            />
                          </svg>
                          <span>Sign in with Google</span>
                        </>
                      )}
                    </button>
                  </div>
                )}
              </div>
            )}

            <div className="demo-credentials-box">
              <h4>💡 Dev Sandbox Access:</h4>
              {loginType === 'SYSTEM' ? (
                <p>Default Admin: <strong>admin</strong> / Password: <strong>admin</strong></p>
              ) : (
                <p>Sign in with your Google account. First-time users will be asked for a mobile number to complete registration.</p>
              )}
            </div>
          </div>
        </div>
      ) : (
        <>
          {/* Mobile Top Navigation Header */}
          <div className="mobile-header">
            <button className="mobile-menu-toggle" onClick={() => setSidebarOpen(!sidebarOpen)} title="Toggle menu">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <line x1="3" y1="12" x2="21" y2="12"></line>
                <line x1="3" y1="6" x2="21" y2="6"></line>
                <line x1="3" y1="18" x2="21" y2="18"></line>
              </svg>
            </button>
            <div className="mobile-brand-title">Tillo Dev Portal</div>
          </div>

          {/* Sidebar Backdrop Overlay on Mobile */}
          {sidebarOpen && (
            <div className="sidebar-backdrop" onClick={() => setSidebarOpen(false)} />
          )}

          {/* Full Height left sidebar */}
          <aside className={`dashboard-sidebar glass-effect ${sidebarOpen ? 'open' : ''}`}>
            <div className="sidebar-brand">
              <img src={logo} alt="Branding" className="tillo-logo-img" />
            </div>

            <nav className="sidebar-nav">
              <button
                className={`nav-item ${activeTab === 'keys' ? 'active' : ''}`}
                onClick={() => { setActiveTab('keys'); setSidebarOpen(false); }}
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="nav-icon">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                  <path d="M7 11V7a5 5 0 0110 0v4"/>
                </svg>
                API Key Credentials
              </button>

              <button
                className={`nav-item ${activeTab === 'playground' ? 'active' : ''}`}
                onClick={() => { setActiveTab('playground'); setSidebarOpen(false); }}
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="nav-icon">
                  <polyline points="16 18 22 12 16 6"/>
                  <polyline points="8 6 2 12 8 18"/>
                </svg>
                Developer Sandbox
              </button>

              <button
                className={`nav-item ${activeTab === 'logs' ? 'active' : ''}`}
                onClick={() => { setActiveTab('logs'); setSidebarOpen(false); }}
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="nav-icon">
                  <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
                  <polyline points="14 2 14 8 20 8"/>
                  <line x1="16" y1="13" x2="8" y2="13"/>
                  <line x1="16" y1="17" x2="8" y2="17"/>
                  <polyline points="10 9 9 9 8 9"/>
                </svg>
                API Request Logs
              </button>

              <div className="nav-item-group">
                <button
                  className={`nav-item ${activeTab === 'docs' ? 'active' : ''}`}
                  onClick={() => { setActiveTab('docs'); setSidebarOpen(false); }}
                >
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="nav-icon">
                    <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
                    <polyline points="14 2 14 8 20 8"/>
                    <line x1="16" y1="13" x2="8" y2="13"/>
                    <line x1="16" y1="17" x2="8" y2="17"/>
                    <polyline points="10 9 9 9 8 9"/>
                  </svg>
                  API Reference Docs
                </button>
                {activeTab === 'docs' && (
                  <div className="submenu animate-slideUp">
                    <button onClick={() => navigateToSection('doc-section-1')} className="submenu-item">
                      1. Architecture
                    </button>
                    <button onClick={() => navigateToSection('doc-section-2')} className="submenu-item">
                      2. Auth & Headers
                    </button>
                    <button onClick={() => navigateToSection('doc-section-3')} className="submenu-item">
                      3. Endpoints Directory
                    </button>
                    <button onClick={() => navigateToSection('doc-section-4')} className="submenu-item">
                      4. Rules & Shields
                    </button>
                    <button onClick={() => navigateToSection('doc-section-5')} className="submenu-item">
                      5. Error Schemas
                    </button>
                    <button onClick={() => navigateToSection('doc-section-6')} className="submenu-item">
                      6. JS Code Template
                    </button>
                  </div>
                )}
              </div>
            </nav>

            <div className="security-guarantee-box">
              <div className="shield-icon">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#08a850" strokeWidth="2.5">
                  <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                </svg>
              </div>
              <h4>Security Scope</h4>
              <p>Keys obtained here only have <strong>Read-Only</strong> permissions. Access to financial transactions and mutations is blocked.</p>
            </div>

            <div className="sidebar-footer">
              <div className="user-profile-badge">
                <div className="avatar">
                  {session.name.charAt(0).toUpperCase()}
                </div>
                <div className="user-info">
                  <span className="username">{session.name}</span>
                  <span className="user-role">{session.roleOrType} Profile</span>
                </div>
                <button onClick={handleLogout} className="btn-logout" title="Sign Out">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </button>
              </div>
            </div>
          </aside>

          {/* Main Content Area */}
          <main className="dashboard-main-content">
            {activeTab === 'keys' && (
              <div className="tab-pane animate-slideUp">
                <div className="panel-header">
                  <h2>Manage Developer API Keys</h2>
                  <p>Obtain authentication tokens for integrating program modules and external query widgets.</p>
                </div>

                {/* API Key list */}
                {isSystemUser ? (
                  <div className="keys-grid">
                    <div className="premium-card key-creator-card">
                      <h3>Generate New API Key</h3>
                      <p className="card-desc">Assign a friendly name to describe your application module usage.</p>
                      
                      <form onSubmit={handleCreateKey} className="create-key-form">
                        <div className="input-group">
                          <label htmlFor="keyName">Application / Module Name</label>
                          <input
                            type="text"
                            id="keyName"
                            placeholder="e.g. Canteen Status Widget"
                            value={newKeyName}
                            disabled={isLimitReached}
                            onChange={(e) => setNewKeyName(e.target.value)}
                          />
                        </div>

                        <div className="permissions-config animate-slideUp">
                          <label className="toggle-label-header">Elevated Key Privileges</label>
                          <div className="toggle-switch-wrapper">
                            <label className="switch">
                              <input 
                                type="checkbox" 
                                checked={writeAccess}
                                onChange={(e) => {
                                  const checked = e.target.checked;
                                  setWriteAccess(checked);
                                  if (checked) {
                                    setSelectedPermissions([
                                      'READ_PRODUCTS', 'WRITE_PRODUCTS',
                                      'READ_STALLS', 'WRITE_STALLS',
                                      'READ_ORDERS', 'WRITE_ORDERS',
                                      'READ_WALLETS', 'WRITE_WALLETS'
                                    ]);
                                  } else {
                                    setSelectedPermissions([
                                      'READ_PRODUCTS', 'READ_STALLS', 'READ_ORDERS', 'READ_WALLETS'
                                    ]);
                                  }
                                }}
                              />
                              <span className="slider round"></span>
                            </label>
                            <span className="toggle-desc">Enable Writing & Mutation Access</span>
                          </div>

                          <label className="toggle-label-header">Modular API Scopes</label>
                          <div className="permissions-checklist">
                            {[
                              { id: 'stalls', label: 'Stalls Catalog', read: 'READ_STALLS', write: 'WRITE_STALLS' },
                              { id: 'products', label: 'Products Catalog', read: 'READ_PRODUCTS', write: 'WRITE_PRODUCTS' },
                              { id: 'orders', label: 'Orders List', read: 'READ_ORDERS', write: 'WRITE_ORDERS' },
                              { id: 'wallets', label: 'Wallet circulation / Lookup', read: 'READ_WALLETS', write: 'WRITE_WALLETS' }
                            ].map((group) => {
                              const hasRead = selectedPermissions.includes(group.read);
                              const hasWrite = selectedPermissions.includes(group.write);
                              
                              return (
                                <div key={group.id} className="permission-group-card">
                                  <h4>{group.label}</h4>
                                  <div className="permission-checkboxes">
                                    <label className="checkbox-container">
                                      <input
                                        type="checkbox"
                                        checked={hasRead}
                                        onChange={(e) => {
                                          if (e.target.checked) {
                                            setSelectedPermissions(prev => [...prev, group.read]);
                                          } else {
                                            setSelectedPermissions(prev => prev.filter(p => p !== group.read));
                                          }
                                        }}
                                      />
                                      <span className="checkmark"></span>
                                      Read
                                    </label>
                                    <label className={`checkbox-container ${!writeAccess ? 'disabled' : ''}`}>
                                      <input
                                        type="checkbox"
                                        disabled={!writeAccess}
                                        checked={writeAccess && hasWrite}
                                        onChange={(e) => {
                                          if (e.target.checked) {
                                            setSelectedPermissions(prev => [...prev, group.write]);
                                          } else {
                                            setSelectedPermissions(prev => prev.filter(p => p !== group.write));
                                          }
                                        }}
                                      />
                                      <span className="checkmark"></span>
                                      Write
                                    </label>
                                  </div>
                                </div>
                              );
                            })}
                          </div>
                        </div>
                        
                        <button
                          type="submit"
                          className="btn-primary w-full"
                          disabled={loading || isLimitReached}
                          style={{ marginTop: '1rem' }}
                        >
                          {isLimitReached ? 'Key Limit Reached (Max 3)' : 'Generate Key'}
                        </button>
                      </form>

                      <div className="limit-indicator">
                        <span className="dot" style={{ backgroundColor: '#08a850' }}></span>
                        <span>Unlimited Staff API Keys Allowed</span>
                      </div>
                    </div>

                    <div className="keys-list-container">
                      {keys.length === 0 ? (
                        <div className="empty-state">
                          <div className="empty-icon">🔐</div>
                          <h3>No Active API Keys</h3>
                          <p>You haven't generated any API keys yet. Create one on the left to start accessing endpoints.</p>
                        </div>
                      ) : (
                        keys.map((key) => (
                          <div key={key.id} className="premium-card api-key-card animate-slideUp">
                            <div className="key-card-header">
                              <div>
                                <h4>{key.name}</h4>
                                <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.25rem' }}>
                                  <span className="badge-user-type">{key.userType} Key</span>
                                  <span className={`badge-access-type ${key.writeAccess ? 'elevated' : 'readonly'}`}>
                                    {key.writeAccess ? 'Elevated (Write)' : 'Read-Only'}
                                  </span>
                                </div>
                              </div>
                              <button
                                onClick={() => handleRevokeKey(key.id)}
                                className="btn-revoke"
                                title="Revoke and Delete Key"
                              >
                                Revoke
                              </button>
                            </div>

                            <div className="key-display-box">
                              <code className="key-code">
                                {showSecrets[key.id] ? key.apiKey : `${key.apiKey.substring(0, 8)}••••••••••••••••••••••••••••`}
                              </code>
                              <div className="key-actions">
                                <button
                                  onClick={() => toggleRevealKey(key.id)}
                                  className="btn-icon-only"
                                  title={showSecrets[key.id] ? 'Hide Key' : 'Reveal Key'}
                                >
                                  {showSecrets[key.id] ? (
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                      <path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/>
                                      <line x1="1" y1="1" x2="23" y2="23"/>
                                    </svg>
                                  ) : (
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                                      <circle cx="12" cy="12" r="3"/>
                                    </svg>
                                  )}
                                </button>

                                <button
                                  onClick={() => copyToClipboard(key.apiKey)}
                                  className="btn-icon-only"
                                  title="Copy Key"
                                >
                                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                                    <path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>
                                  </svg>
                                </button>
                              </div>
                            </div>

                            {key.permissions && (
                              <div className="key-permissions-list">
                                <span className="scopes-label">Scopes:</span>
                                <div className="scopes-badges">
                                  {key.permissions.split(',').map(scope => (
                                    <span key={scope} className="scope-tag">{scope}</span>
                                  ))}
                                </div>
                              </div>
                            )}

                            <div className="key-metadata">
                              <span>Created: <strong>{new Date(key.createdAt).toLocaleDateString()}</strong></span>
                              <span>Last Used: <strong>{key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleTimeString() : 'Never'}</strong></span>
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  </div>
                ) : (
                  <div className="keys-grid">
                    {/* CUSTOMER Mode: Register App and show App based Keys */}
                    <div className="premium-card key-creator-card">
                      <h3>Register New App</h3>
                      <p className="card-desc">First create an app to configure features and obtain its API credentials.</p>
                      
                      <form onSubmit={handleCreateApp} className="create-key-form">
                        <div className="input-group">
                          <label htmlFor="appName">Application Name</label>
                          <input
                            type="text"
                            id="appName"
                            placeholder="e.g. My Canteen Companion"
                            value={newAppName}
                            onChange={(e) => setNewAppName(e.target.value)}
                            required
                          />
                        </div>

                        <div className="input-group" style={{ marginTop: '1rem' }}>
                          <label htmlFor="appDesc">Description</label>
                          <textarea
                            id="appDesc"
                            placeholder="Describe what your app will build or access..."
                            value={newAppDesc}
                            onChange={(e) => setNewAppDesc(e.target.value)}
                            style={{
                              width: '100%',
                              padding: '0.85rem 1rem',
                              borderRadius: '0.85rem',
                              border: '1px solid var(--color-border)',
                              backgroundColor: 'var(--color-input-bg)',
                              color: 'var(--color-text-dark)',
                              fontFamily: 'inherit',
                              minHeight: '80px',
                              resize: 'vertical'
                            }}
                          />
                        </div>
                        
                        <button
                          type="submit"
                          className="btn-primary w-full"
                          disabled={loading}
                          style={{ marginTop: '1.5rem' }}
                        >
                          Register App
                        </button>
                      </form>

                      <div className="limit-indicator">
                        <span className="dot" style={{ backgroundColor: keys.length >= 3 ? '#ef4444' : '#08a850' }}></span>
                        <span>Total Keys generated: <strong>{keys.length} of 3 limit</strong></span>
                      </div>
                    </div>

                    <div className="keys-list-container">
                      {apps.length === 0 ? (
                        <div className="empty-state">
                          <div className="empty-icon">📱</div>
                          <h3>No Registered Applications</h3>
                          <p>You need to register an App first before you can generate API keys.</p>
                        </div>
                      ) : (
                        apps.map((app) => {
                          const appKey = keys.find(k => k.appId === app.id);
                          return (
                            <div key={app.id} className="premium-card api-key-card animate-slideUp" style={{ position: 'relative' }}>
                              <div className="key-card-header">
                                <div>
                                  <h4 style={{ fontSize: '1.25rem', fontWeight: '800' }}>{app.name}</h4>
                                  <p style={{ color: 'var(--color-text-secondary)', fontSize: '0.9rem', marginTop: '0.25rem' }}>
                                    {app.description || 'No description provided.'}
                                  </p>
                                  <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.5rem' }}>
                                    <span className="badge-user-type">App ID: {app.id}</span>
                                    {appKey ? (
                                      <span className="badge-access-type readonly">Active API Key</span>
                                    ) : (
                                      <span className="badge-access-type" style={{ background: '#f59e0b', color: '#fff' }}>Missing API Key</span>
                                    )}
                                  </div>
                                </div>
                                <button
                                  onClick={() => handleDeleteApp(app.id)}
                                  className="btn-revoke"
                                  style={{ background: 'rgba(239, 68, 68, 0.08)', color: 'var(--color-danger)' }}
                                  title="Delete App and revoke key"
                                >
                                  Delete App
                                </button>
                              </div>

                              {appKey ? (
                                <div style={{ marginTop: '1.5rem' }}>
                                  <div className="key-display-box">
                                    <code className="key-code">
                                      {showSecrets[appKey.id] ? appKey.apiKey : `${appKey.apiKey.substring(0, 8)}••••••••••••••••••••••••••••`}
                                    </code>
                                    <div className="key-actions">
                                      <button
                                        onClick={() => toggleRevealKey(appKey.id)}
                                        className="btn-icon-only"
                                        title={showSecrets[appKey.id] ? 'Hide Key' : 'Reveal Key'}
                                      >
                                        {showSecrets[appKey.id] ? (
                                          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                            <path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/>
                                            <line x1="1" y1="1" x2="23" y2="23"/>
                                          </svg>
                                        ) : (
                                          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                                            <circle cx="12" cy="12" r="3"/>
                                          </svg>
                                        )}
                                      </button>

                                      <button
                                        onClick={() => copyToClipboard(appKey.apiKey)}
                                        className="btn-icon-only"
                                        title="Copy Key"
                                      >
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                          <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                                          <path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>
                                        </svg>
                                      </button>
                                    </div>
                                  </div>

                                  <div className="key-metadata" style={{ marginTop: '1rem', borderTop: '1px dashed var(--color-border)', paddingTop: '0.75rem' }}>
                                    <span>Created: <strong>{new Date(appKey.createdAt).toLocaleDateString()}</strong></span>
                                    <span>Last Used: <strong>{appKey.lastUsedAt ? new Date(appKey.lastUsedAt).toLocaleTimeString() : 'Never'}</strong></span>
                                  </div>
                                </div>
                              ) : (
                                <div style={{ marginTop: '1.5rem', textAlign: 'center', padding: '1.25rem', background: 'rgba(0,0,0,0.02)', borderRadius: '1rem', border: '1px dashed var(--color-border)' }}>
                                  <p style={{ fontSize: '0.9rem', color: 'var(--color-text-secondary)', marginBottom: '1rem' }}>
                                    No API key generated for this app yet.
                                  </p>
                                  <button
                                    onClick={() => handleCreateKeyForApp(app.id, app.name)}
                                    className="btn-primary"
                                    disabled={loading || keys.length >= 3}
                                    style={{ padding: '0.5rem 1.5rem', fontSize: '0.875rem' }}
                                  >
                                    {keys.length >= 3 ? 'Key Limit Reached (Max 3)' : 'Generate API Key'}
                                  </button>
                                </div>
                              )}
                            </div>
                          );
                        })
                      )}
                    </div>
                  </div>
                )}
              </div>
            )}

            {activeTab === 'logs' && (
              <div className="tab-pane animate-slideUp">
                <div className="panel-header">
                  <h2>API Request Logs</h2>
                  <p>Track history, latency, and status codes of all requests querying your developer endpoints.</p>
                </div>

                <div className="premium-card">
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
                    <h3 style={{ margin: 0 }}>Request History</h3>
                    <button onClick={() => fetchLogs(0)} className="btn-primary" style={{ padding: '0.4rem 1rem', fontSize: '0.85rem' }} disabled={loading}>
                      Refresh Logs
                    </button>
                  </div>

                  {logs.length === 0 ? (
                    <div className="empty-state" style={{ padding: '3rem 0' }}>
                      <div className="empty-icon">📊</div>
                      <h3>No API Request History</h3>
                      <p>Use your API keys to call the API or test requests in the Developer Sandbox to populate logs.</p>
                    </div>
                  ) : (
                    <>
                      <div style={{ display: 'flex', gap: '1.5rem', alignItems: 'flex-start' }}>
                        {/* Left: Logs Table */}
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ overflowX: 'auto' }}>
                            <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', minWidth: '550px' }}>
                              <thead>
                                <tr style={{ borderBottom: '2px solid var(--color-border)', paddingBottom: '0.75rem' }}>
                                  <th style={{ padding: '0.75rem 1rem', fontSize: '0.8rem', fontWeight: '800', color: 'var(--color-text-secondary)', textTransform: 'uppercase' }}>Timestamp</th>
                                  <th style={{ padding: '0.75rem 1rem', fontSize: '0.8rem', fontWeight: '800', color: 'var(--color-text-secondary)', textTransform: 'uppercase' }}>Method</th>
                                  <th style={{ padding: '0.75rem 1rem', fontSize: '0.8rem', fontWeight: '800', color: 'var(--color-text-secondary)', textTransform: 'uppercase' }}>Endpoint</th>
                                  <th style={{ padding: '0.75rem 1rem', fontSize: '0.8rem', fontWeight: '800', color: 'var(--color-text-secondary)', textTransform: 'uppercase' }}>Status</th>
                                  <th style={{ padding: '0.75rem 1rem', fontSize: '0.8rem', fontWeight: '800', color: 'var(--color-text-secondary)', textTransform: 'uppercase' }}>IP Address</th>
                                </tr>
                              </thead>
                              <tbody>
                                {logs.map((log) => {
                                  const isSuccess = log.status >= 200 && log.status < 300;
                                  const isSelected = selectedLog && selectedLog.id === log.id;
                                  return (
                                    <tr 
                                      key={log.id} 
                                      onClick={() => setSelectedLog(log)}
                                      style={{ 
                                        borderBottom: '1px solid var(--color-border)', 
                                        transition: 'background 0.2s',
                                        cursor: 'pointer',
                                        backgroundColor: isSelected ? 'rgba(0, 24, 40, 0.06)' : 'transparent'
                                      }} 
                                      className="log-row-hover"
                                    >
                                      <td style={{ padding: '1rem', fontSize: '0.875rem', color: 'var(--color-text-dark)', whiteSpace: 'nowrap' }}>
                                        {new Date(log.timestamp).toLocaleString()}
                                      </td>
                                      <td style={{ padding: '1rem' }}>
                                        <span style={{
                                          padding: '0.25rem 0.6rem',
                                          borderRadius: '0.5rem',
                                          fontSize: '0.75rem',
                                          fontWeight: '800',
                                          color: '#fff',
                                          backgroundColor: log.method === 'GET' ? '#3b82f6' : log.method === 'POST' ? '#10b981' : log.method === 'DELETE' ? '#ef4444' : '#6b7280'
                                        }}>
                                          {log.method}
                                        </span>
                                      </td>
                                      <td style={{ padding: '1rem', fontSize: '0.875rem', fontFamily: 'monospace', color: 'var(--color-text-dark)', wordBreak: 'break-all' }}>
                                        {log.endpoint}
                                      </td>
                                      <td style={{ padding: '1rem' }}>
                                        <span style={{
                                          padding: '0.25rem 0.6rem',
                                          borderRadius: '0.5rem',
                                          fontSize: '0.75rem',
                                          fontWeight: '800',
                                          color: isSuccess ? '#065f46' : '#991b1b',
                                          backgroundColor: isSuccess ? '#d1fae5' : '#fee2e2'
                                        }}>
                                          {log.status}
                                        </span>
                                      </td>
                                      <td style={{ padding: '1rem', fontSize: '0.875rem', color: 'var(--color-text-secondary)' }}>
                                        {log.clientIp || 'Unknown'}
                                      </td>
                                    </tr>
                                  );
                                })}
                              </tbody>
                            </table>
                          </div>
                        </div>

                        {/* Right: Response JSON Detail View */}
                        {selectedLog && (
                          <div className="premium-card animate-slideUp" style={{ width: '400px', display: 'flex', flexDirection: 'column', flexShrink: 0, padding: '1.5rem', background: 'rgba(0,0,0,0.01)', border: '1px solid var(--color-border)', borderRadius: '1rem', maxHeight: '550px', overflowY: 'auto' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem', borderBottom: '1px solid var(--color-border)', paddingBottom: '0.75rem' }}>
                              <h4 style={{ margin: 0, fontSize: '1.05rem', fontWeight: '800', color: 'var(--color-text-dark)' }}>Response Payload</h4>
                              <button 
                                onClick={() => setSelectedLog(null)} 
                                style={{ background: 'transparent', border: 'none', fontSize: '1.25rem', cursor: 'pointer', color: 'var(--color-text-secondary)' }}
                              >
                                &times;
                              </button>
                            </div>
                            
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.65rem', fontSize: '0.825rem', marginBottom: '1rem' }}>
                              <div>
                                <strong style={{ color: 'var(--color-text-secondary)' }}>Endpoint: </strong>
                                <span style={{ fontFamily: 'monospace' }}>{selectedLog.endpoint}</span>
                              </div>
                              <div style={{ display: 'flex', gap: '1rem' }}>
                                <div>
                                  <strong style={{ color: 'var(--color-text-secondary)' }}>Method: </strong>
                                  <span style={{
                                    padding: '0.15rem 0.4rem',
                                    borderRadius: '0.25rem',
                                    fontSize: '0.7rem',
                                    fontWeight: '800',
                                    color: '#fff',
                                    backgroundColor: selectedLog.method === 'GET' ? '#3b82f6' : selectedLog.method === 'POST' ? '#10b981' : selectedLog.method === 'DELETE' ? '#ef4444' : '#6b7280'
                                  }}>
                                    {selectedLog.method}
                                  </span>
                                </div>
                                <div>
                                  <strong style={{ color: 'var(--color-text-secondary)' }}>Status: </strong>
                                  <span style={{
                                    padding: '0.15rem 0.4rem',
                                    borderRadius: '0.25rem',
                                    fontSize: '0.7rem',
                                    fontWeight: '800',
                                    color: (selectedLog.status >= 200 && selectedLog.status < 300) ? '#065f46' : '#991b1b',
                                    backgroundColor: (selectedLog.status >= 200 && selectedLog.status < 300) ? '#d1fae5' : '#fee2e2'
                                  }}>
                                    {selectedLog.status}
                                  </span>
                                </div>
                              </div>
                              <div>
                                <strong style={{ color: 'var(--color-text-secondary)' }}>IP Address: </strong>
                                <span>{selectedLog.clientIp || 'Unknown'}</span>
                              </div>
                              <div>
                                <strong style={{ color: 'var(--color-text-secondary)' }}>Timestamp: </strong>
                                <span>{new Date(selectedLog.timestamp).toLocaleString()}</span>
                              </div>
                            </div>

                            <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
                              <strong style={{ color: 'var(--color-text-secondary)', fontSize: '0.825rem', display: 'block', marginBottom: '0.5rem' }}>Response JSON:</strong>
                              <pre style={{ 
                                margin: 0, 
                                padding: '0.75rem', 
                                backgroundColor: 'rgba(0,0,0,0.03)', 
                                border: '1px solid var(--color-border)', 
                                borderRadius: '0.5rem', 
                                fontFamily: 'monospace', 
                                fontSize: '0.75rem', 
                                color: 'var(--color-text-dark)',
                                overflowX: 'auto',
                                overflowY: 'auto',
                                whiteSpace: 'pre-wrap',
                                wordBreak: 'break-all',
                                maxHeight: '300px'
                              }}>
                                {selectedLog.responseBody ? (
                                  (() => {
                                    try {
                                      return JSON.stringify(JSON.parse(selectedLog.responseBody), null, 2);
                                    } catch (e) {
                                      return selectedLog.responseBody;
                                    }
                                  })()
                                ) : (
                                  "No response body returned or logged."
                                )}
                              </pre>
                            </div>
                          </div>
                        )}
                      </div>

                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
                        <span style={{ fontSize: '0.875rem', color: 'var(--color-text-secondary)' }}>
                          Showing Page <strong>{logPage + 1}</strong> of <strong>{logTotalPages || 1}</strong> (<strong>{logTotalItems}</strong> items)
                        </span>
                        <div style={{ display: 'flex', gap: '0.5rem' }}>
                          <button
                            onClick={() => fetchLogs(logPage - 1)}
                            disabled={logPage === 0 || loading}
                            className="btn-primary"
                            style={{
                              padding: '0.4rem 1rem',
                              fontSize: '0.85rem',
                              opacity: logPage === 0 ? 0.5 : 1,
                              cursor: logPage === 0 ? 'not-allowed' : 'pointer'
                            }}
                          >
                            Previous
                          </button>
                          <button
                            onClick={() => fetchLogs(logPage + 1)}
                            disabled={logPage + 1 >= logTotalPages || loading}
                            className="btn-primary"
                            style={{
                              padding: '0.4rem 1rem',
                              fontSize: '0.85rem',
                              opacity: logPage + 1 >= logTotalPages ? 0.5 : 1,
                              cursor: logPage + 1 >= logTotalPages ? 'not-allowed' : 'pointer'
                            }}
                          >
                            Next
                          </button>
                        </div>
                      </div>
                    </>
                  )}
                </div>
              </div>
            )}

            {activeTab === 'playground' && (
              <div className="tab-pane animate-slideUp">
                <div className="panel-header">
                  <h2>Developer Sandbox Playground</h2>
                  <p>Query endpoints live and observe the robust read-only and anti-financial access controls.</p>
                </div>

                <div className="sandbox-workspace">
                  <div className="sandbox-controls">
                    <div className="premium-card">
                      <h3>Configure Sandbox Query</h3>
                      
                      <div className="input-group">
                        <label>Select API Key</label>
                        <select
                          value={selectedKey}
                          onChange={(e) => {
                            setSelectedKey(e.target.value);
                            setCustomKeyInput('');
                          }}
                        >
                          {keys.map((k) => (
                            <option key={k.id} value={k.apiKey}>{k.name} ({k.apiKey.substring(0, 8)}...)</option>
                          ))}
                          <option value="">-- Use Custom Key (Enter Below) --</option>
                        </select>
                      </div>

                      {!selectedKey && (
                        <div className="input-group animate-slideUp">
                          <label>Custom API Key</label>
                          <input
                            type="text"
                            placeholder="DEV-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                            value={customKeyInput}
                            onChange={(e) => setCustomKeyInput(e.target.value)}
                          />
                        </div>
                      )}

                      <div className="input-group">
                        <label>Target Endpoint</label>
                        <select
                          value={selectedEndpoint}
                          onChange={(e) => setSelectedEndpoint(e.target.value)}
                        >
                          <option value="/api/developer/v1/validate">GET /api/developer/v1/validate (Validation check)</option>
                          <option value="/api/developer/v1/stalls">GET /api/developer/v1/stalls (Stalls Catalogue)</option>
                          <option value="/api/developer/v1/products">GET /api/developer/v1/products (Products Catalog)</option>
                          <option value="/api/developer/v1/wallet">GET /api/developer/v1/wallet (Own Wallet Balance)</option>
                          <option value="/api/developer/v1/wallet?mobileNumber=9876543210">GET /api/developer/v1/wallet?mobileNumber=9876543210 (Check Any Wallet by Mobile)</option>
                          <option value="/api/developer/v1/orders">GET /api/developer/v1/orders (Active Orders list)</option>
                        </select>
                      </div>

                      <button
                        onClick={executePlayground}
                        className="btn-primary w-full"
                        disabled={playgroundLoading}
                        style={{ marginBottom: '0.75rem' }}
                      >
                        {playgroundLoading ? 'Sending Request...' : 'Send API Request'}
                      </button>

                      <button
                        onClick={downloadPostmanCollection}
                        className="btn-postman w-full"
                      >
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{ marginRight: '6px' }}>
                          <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14L21 3" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                        Test with Postman (Export Collection)
                      </button>
                    </div>

                    {/* Simulated security audit / attack tests */}
                    <div className="premium-card security-audit-card">
                      <div className="audit-card-title">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ea580c" strokeWidth="2.5">
                          <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                        </svg>
                        <h3>Simulate Security Audit Attacks</h3>
                      </div>
                      <p className="card-desc">Try to breach financial or write layers using the developer key. Watch Tillo's robust guard mechanism reject it.</p>

                      <div className="attack-buttons-grid">
                        <button
                          onClick={() => runSimulatedAttack('/api/wallet/transactions/all')}
                          className="btn-attack"
                          disabled={attackLoading}
                        >
                          Attack Ledger: Get All User Transactions
                        </button>
                        
                        <button
                          onClick={() => runSimulatedAttack('/api/wallet/topup', 'POST')}
                          className="btn-attack"
                          disabled={attackLoading}
                        >
                          Attack Write: Inject Wallet Topup
                        </button>

                        <button
                          onClick={() => runSimulatedAttack('/api/wallet/stats')}
                          className="btn-attack"
                          disabled={attackLoading}
                        >
                          Attack Core: Fetch Global Financial Stats
                        </button>
                      </div>
                    </div>
                  </div>

                  <div className="sandbox-outputs">
                    <div className="premium-card output-card">
                      <div className="output-card-header">
                        <h3>Sandbox Terminal Response</h3>
                        {playgroundStatus !== null && (
                          <span className={`status-badge ${playgroundStatus >= 200 && playgroundStatus < 300 ? 'success' : 'error'}`}>
                            HTTP {playgroundStatus}
                          </span>
                        )}
                      </div>
                      
                      <div className="terminal-body">
                        {playgroundLoading ? (
                          <div className="terminal-loading">
                            <div className="spinner"></div>
                            <span>Request dispatched... waiting for backend frame</span>
                          </div>
                        ) : playgroundResponse ? (
                          <pre className="json-output">
                            {JSON.stringify(playgroundResponse, null, 2)}
                          </pre>
                        ) : (
                          <div className="terminal-empty">
                            <span>Ready. Select an endpoint above and click "Send API Request".</span>
                          </div>
                        )}
                      </div>
                    </div>

                    {/* Attack response audit terminal */}
                    {(attackResponse || attackLoading) && (
                      <div className="premium-card output-card attack-output-card animate-slideUp">
                        <div className="output-card-header">
                          <h3 className="text-orange">Audit Firewall Log</h3>
                          {attackStatus !== null && (
                            <span className={`status-badge ${attackStatus >= 400 ? 'block' : 'breach'}`}>
                              {attackStatus === 401 || attackStatus === 403 ? 'BLOCKED - SECURE' : `STATUS ${attackStatus}`}
                            </span>
                          )}
                        </div>
                        
                        <div className="terminal-body attack-terminal">
                          {attackLoading ? (
                            <div className="terminal-loading">
                              <div className="spinner orange-spinner"></div>
                              <span>Penetration query executing...</span>
                            </div>
                          ) : (
                            <div>
                              <div className="firewall-audit-header">
                                <span className="green-text">[SHIELD-ACTIVE]</span> Detected access violation on restricted resource. Access Denied.
                              </div>
                              <pre className="json-output attack-output">
                                {JSON.stringify(attackResponse, null, 2)}
                              </pre>
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}

            {activeTab === 'docs' && (
              <div className="tab-pane animate-slideUp">
                <div className="panel-header">
                  <h2>API Reference Integration Guide</h2>
                  <p>How to use your Developer API keys to authenticate and query Tillo system details.</p>
                </div>

                <div className="premium-card docs-card">
                  <h3 id="doc-section-1">1. System Architecture & Scope Segregation</h3>
                  <p>
                    The Tillo Developer API acts as a read-only integration layer designed to support external widgets, active status screens, and profile integrations. 
                    Authorization is separated based on the owner of the API Key:
                  </p>
                  
                  <div className="security-notice-banner" style={{ margin: '1rem 0', background: 'rgba(0,24,40,0.02)', borderColor: 'var(--color-border)' }}>
                    <ul style={{ paddingLeft: '1.25rem', fontSize: '0.875rem', display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                      <li><strong>Customer Key Scopes:</strong> Allows programmatic reading of the key owner's own orders and wallet balance. Perfect for building custom widgets or personal status trackers.</li>
                      <li><strong>System Key Scopes:</strong> Allows canteen-wide catalog querying (stalls, product list, inventory levels) and overall statistics, but redacts specific customer transaction profiles.</li>
                    </ul>
                  </div>

                  <h3 id="doc-section-2">2. Authentication & Header Specs</h3>
                  <p>
                    All endpoints require you to supply your custom key inside the <code>X-Developer-Key</code> HTTP header. 
                    Traditional JWT authorization headers (e.g., <code>Authorization: Bearer ...</code>) are not required and will be ignored when querying developer paths.
                  </p>
                  
                  <div className="code-block-wrapper">
                    <div className="code-header">
                      <span>HTTP Request Example</span>
                      <div>
                        <button onClick={downloadPostmanCollection} className="btn-copy-code" style={{ marginRight: '8px' }}>Test with Postman</button>
                        <button onClick={() => copyToClipboard('curl -H "X-Developer-Key: DEV-YOUR_API_KEY_HERE" ' + BACKEND_URL + '/api/developer/v1/stalls')} className="btn-copy-code">Copy curl</button>
                      </div>
                    </div>
                    <pre className="code-pre">
{`curl -X GET \\
  -H "X-Developer-Key: DEV-YOUR_API_KEY_HERE" \\
  ${BACKEND_URL}/api/developer/v1/stalls`}
                    </pre>
                  </div>

                  <h3 id="doc-section-3" className="section-title">3. Endpoint Directory (Read-Only)</h3>
                  
                  <table className="docs-table">
                    <thead>
                      <tr>
                        <th>HTTP Method</th>
                        <th>Path</th>
                        <th>Description / Usage</th>
                        <th>Permissions / Scope</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td><span className="method-get">GET</span></td>
                        <td><code>/api/developer/v1/validate</code></td>
                        <td>Verifies key health, active status, and returns key metadata.</td>
                        <td>Key validated</td>
                      </tr>
                      <tr>
                        <td><span className="method-get">GET</span></td>
                        <td><code>/api/developer/v1/stalls</code></td>
                        <td>Lists active canteen stalls, descriptions, and operational status.</td>
                        <td>Key validated</td>
                      </tr>
                      <tr>
                        <td><span className="method-get">GET</span></td>
                        <td><code>/api/developer/v1/products</code></td>
                        <td>Returns the active menu item catalog, categories, pricing, and current stock.</td>
                        <td>Key validated</td>
                      </tr>
                      <tr>
                        <td><span className="method-get">GET</span></td>
                        <td><code>/api/developer/v1/wallet</code></td>
                        <td>
                          Returns wallet balance. <br />
                          • <strong>Default</strong>: Returns own balance (for Customer Key) or circulation stats (for System Key). <br />
                          • <strong>Query Parameter</strong>: Pass <code>?mobileNumber=...</code> or <code>?userId=...</code> to check the wallet balance of any user in the system.
                        </td>
                        <td>Any user balance, read-only</td>
                      </tr>
                      <tr>
                        <td><span className="method-get">GET</span></td>
                        <td><code>/api/developer/v1/orders</code></td>
                        <td>
                          Retrieves active and completed order lists. <br />
                          • <strong>Customer Key</strong>: Returns key owner's own orders. <br />
                          • <strong>System Key</strong>: Lists system orders with financial elements (payout details) masked.
                        </td>
                        <td>Owner scope, key validated</td>
                      </tr>
                    </tbody>
                  </table>

                  <h3 id="doc-section-4" className="section-title">4. Core Rules & Security Shields</h3>
                  <div className="security-notice-banner" style={{ borderLeft: '4px solid var(--color-danger)' }}>
                    <h4 style={{ color: 'var(--color-danger)' }}>🔒 Strict Mutation and Financial Block</h4>
                    <p style={{ marginTop: '0.25rem', fontSize: '0.85rem' }}>
                      To prevent unauthorized changes or leaks of financial parameters, developer API keys are bounded by strict policies:
                    </p>
                    <ul style={{ paddingLeft: '1.25rem', marginTop: '0.5rem', fontSize: '0.825rem', display: 'flex', flexDirection: 'column', gap: '0.25rem' }}>
                      <li><strong>Read-Only Constraints:</strong> Standard operations like checking out, creating coupon codes, placing orders, or topping up balances are blocked. Mutation endpoints will return <code>401 Unauthorized</code> or <code>403 Forbidden</code>.</li>
                      <li><strong>Financial Isolation:</strong> General database tables containing financial audits, payment processor reference IDs, vendor billing settlements, and total daily canteen earnings are inaccessible to API keys.</li>
                      <li><strong>Quota Limit:</strong> To prevent token spam, a hard limit of <strong>3 API keys</strong> is enforced per account. Revoke an old key to create a new one.</li>
                    </ul>
                  </div>

                  <h3 id="doc-section-5">5. Error Responses Schema</h3>
                  <p>When query violations occur, the firewall returns standard JSON error bodies to simplify client parsing:</p>
                  <div className="code-block-wrapper">
                    <div className="code-header">
                      <span>HTTP 401 Unauthorized / Invalid Key</span>
                    </div>
                    <pre className="code-pre">
{`{
  "error": "Invalid or missing X-Developer-Key header"
}`}
                    </pre>
                  </div>
                  <div className="code-block-wrapper">
                    <div className="code-header">
                      <span>HTTP 403 Forbidden / Access Denied</span>
                    </div>
                    <pre className="code-pre">
{`{
  "status": 403,
  "error": "Forbidden",
  "message": "Access Denied on restricted financial/mutation endpoint",
  "path": "/api/wallet/topup"
}`}
                    </pre>
                  </div>

                  <h3 id="doc-section-6">6. Quick Integration JavaScript Snippet</h3>
                  <div className="code-block-wrapper">
                    <div className="code-header">
                      <span>JavaScript Fetch Template</span>
                    </div>
                    <pre className="code-pre">
{`async function getCanteenMenu(apiKey) {
  try {
    const response = await fetch('${BACKEND_URL}/api/developer/v1/products', {
      headers: {
        'X-Developer-Key': apiKey
      }
    });
    
    if (!response.ok) {
      const errorBody = await response.json();
      throw new Error(errorBody.error || 'Failed to fetch');
    }
    
    const products = await response.json();
    console.log('Active Products:', products);
    return products;
  } catch (error) {
    console.error('API Error:', error.message);
  }
}`}
                    </pre>
                  </div>
                </div>
              </div>
            )}
          </main>
        </>
      )}
    </div>
  );
}

export default App;
