"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <title>Prestige Realty - Enterprise Department Login Portal</title>\n  <script src=\"https://cdn.tailwindcss.com\"></script>\n  <script>\n    tailwind.config = {\n      theme: {\n        extend: {\n          colors: {\n            brand: {\n              black: '#000000',\n              charcoal: '#111111',\n              card: '#1a1a1a',\n              border: '#333333',\n              muted: '#666666',\n              gray: '#979797',\n              light: '#EEEEEE',\n              blue: '#0088CC',\n              blueHover: '#0077b5',\n              blueDark: '#006699',\n            },\n            slate: {\n              950: '#000000',\n              900: '#111111',\n              800: '#1a1a1a',\n              700: '#333333',\n              600: '#666666',\n              500: '#808080',\n              400: '#979797',\n              300: '#cccccc',\n              200: '#EEEEEE',\n              100: '#f5f5f5',\n              50: '#ffffff'\n            },\n            sky: {\n              50: '#eef8fc',\n              100: '#d7eff9',\n              200: '#aee0f3',\n              300: '#75cbee',\n              400: '#38b0e5',\n              500: '#0088CC',\n              600: '#0077b5',\n              700: '#006699',\n              800: '#005580',\n              900: '#004466',\n              950: '#002233',\n            }\n          }\n        }\n      }\n    };\n  </script>\n  <style>\n    @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap');\n    body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: #000000; color: #EEEEEE; }\n    .custom-scrollbar::-webkit-scrollbar { width: 5px; height: 5px; }\n    .custom-scrollbar::-webkit-scrollbar-track { background: #000000; }\n    .custom-scrollbar::-webkit-scrollbar-thumb { background: #666666; border-radius: 9999px; }\n    .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #979797; }\n  </style>\n</head>\n<body class=\"bg-black text-[#EEEEEE] min-h-screen flex flex-col justify-between antialiased relative overflow-x-hidden\">\n\n  <!-- Ambient Glow Effects (Brand Blue #0088CC) -->\n  <div class=\"absolute -top-40 -left-40 w-96 h-96 bg-[#0088CC]/15 rounded-full blur-3xl pointer-events-none\"></div>\n  <div class=\"absolute top-1/2 -right-40 w-96 h-96 bg-[#0088CC]/10 rounded-full blur-3xl pointer-events-none\"></div>\n  <div class=\"absolute -bottom-40 left-1/3 w-96 h-96 bg-[#0088CC]/10 rounded-full blur-3xl pointer-events-none\"></div>\n\n  <!-- Top Navigation Header -->\n  <header class=\"w-full px-6 py-4 flex items-center justify-between z-10 border-b border-[#333333] bg-black/80 backdrop-blur-md\">\n    <div class=\"flex items-center space-x-3\">\n      <div class=\"w-10 h-10 rounded-xl bg-[#0088CC] flex items-center justify-center text-white font-black text-xl shadow-lg shadow-[#0088CC]/30\">\n        🏢\n      </div>\n      <div>\n        <h1 class=\"text-base font-extrabold text-[#EEEEEE] tracking-tight\">PRESTIGE REALTY</h1>\n        <p class=\"text-[10px] text-[#0088CC] font-semibold uppercase tracking-wider\">Enterprise Real Estate CRM System</p>\n      </div>\n    </div>\n    <div class=\"flex items-center space-x-3 text-xs\">\n      <a href=\"/track\" class=\"inline-flex items-center space-x-1.5 px-3.5 py-1.5 rounded-xl bg-gradient-to-r from-sky-600 to-cyan-600 hover:from-sky-500 hover:to-cyan-500 text-white font-bold text-xs shadow-md shadow-sky-600/20 transition-all duration-200 border border-sky-400/30\">\n        <span>🔎</span>\n        <span>Track Case Status</span>\n      </a>\n      <span class=\"inline-flex items-center space-x-1.5 px-3 py-1 rounded-full bg-[#0088CC]/10 text-[#0088CC] border border-[#0088CC]/25 font-medium text-[11px]\">\n        <span class=\"w-2 h-2 rounded-full bg-[#0088CC] animate-pulse\"></span>\n        <span>System Status: Online</span>\n      </span>\n    </div>\n  </header>\n\n  <!-- Main Content Area -->\n  <main class=\"flex-1 flex items-center justify-center p-6 z-10\">\n    <div class=\"w-full max-w-5xl\">\n\n      <!-- AUTHENTICATED STATE BANNER (Shown if already logged in) -->\n      <div id=\"authenticatedCard\" class=\"hidden bg-slate-900/90 border border-slate-800 rounded-3xl p-8 shadow-2xl backdrop-blur-xl max-w-2xl mx-auto space-y-6\">\n        <div class=\"flex items-center justify-between pb-4 border-b border-slate-800\">\n          <div class=\"flex items-center space-x-4\">\n            <div class=\"w-14 h-14 rounded-2xl bg-gradient-to-tr from-sky-500 to-indigo-600 flex items-center justify-center text-white font-extrabold text-2xl shadow-lg\" id=\"authUserAvatar\">\n              SJ\n            </div>\n            <div>\n              <div class=\"flex items-center space-x-2\">\n                <h3 class=\"text-lg font-bold text-white\" id=\"authUserName\">Sarah Jenkins</h3>\n                <span class=\"px-2 py-0.5 rounded text-[10px] font-bold uppercase bg-purple-500/20 text-purple-300 border border-purple-500/30\" id=\"authUserRole\">MASTER ADMIN</span>\n              </div>\n              <p class=\"text-xs text-slate-400 mt-0.5\"><span id=\"authUserUsername\">@admin</span> • <span id=\"authUserEmail\">admin@prestige.com</span></p>\n            </div>\n          </div>\n          <button onclick=\"handleLogout()\" class=\"px-3.5 py-1.5 bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 border border-rose-500/20 rounded-xl text-xs font-semibold transition\">\n            Log Out / Switch\n          </button>\n        </div>\n\n        <div class=\"space-y-3\">\n          <label class=\"block text-xs font-bold text-slate-300 uppercase tracking-wider\">Access Your Authorized Portals:</label>\n          <div class=\"grid grid-cols-1 md:grid-cols-2 gap-3\" id=\"authDeptLinks\">\n            <!-- Injected via JavaScript -->\n          </div>\n        </div>\n\n        <div class=\"pt-4 border-t border-slate-800 flex items-center justify-between text-xs text-slate-500\">\n          <span>Connected  Database: <code class=\"text-slate-400\">real_estate_crm</code></span>\n          <button onclick=\"showLoginForm()\" class=\"text-sky-400 hover:underline\">Log in as another user &rarr;</button>\n        </div>\n      </div>\n\n      <!-- UNAUTHENTICATED LOGIN CARD -->\n      <div id=\"loginCard\" class=\"grid grid-cols-1 lg:grid-cols-12 gap-8 items-center\">\n\n        <!-- Left Brand & Department Info Column -->\n        <div class=\"lg:col-span-5 space-y-5\">\n          <div class=\"space-y-2\">\n            <span class=\"px-2.5 py-1 rounded-lg text-[10px] font-bold uppercase tracking-wider bg-sky-500/15 text-sky-300 border border-sky-500/20\">\n              Multi-Department Authentication\n            </span>\n            <h2 class=\"text-3xl font-extrabold text-white tracking-tight leading-tight\">\n              Sign in to your Department\n            </h2>\n            <p class=\"text-xs text-slate-400 leading-relaxed\">\n              Welcome to Prestige Realty Enterprise CRM. Select your department section or log in with your assigned employee username and password.\n            </p>\n          </div>\n\n          <!-- Department Overview Badges -->\n          <div class=\"space-y-2.5 text-xs\">\n            <div onclick=\"setSection('cr')\" class=\"cursor-pointer flex items-center justify-between p-3 rounded-2xl bg-[#111111] hover:bg-[#181818] border border-[#333333] hover:border-[#0088CC]/50 transition group\">\n              <div class=\"flex items-center space-x-3\">\n                <span class=\"w-8 h-8 rounded-xl bg-[#0088CC]/15 text-[#0088CC] flex items-center justify-center font-bold text-base\">🤝</span>\n                <div>\n                  <p class=\"font-bold text-[#EEEEEE] group-hover:text-[#0088CC] transition\">Agent CR Department</p>\n                  <p class=\"text-[11px] text-[#979797]\">Leads, site meetings & deal quotation letterheads</p>\n                </div>\n              </div>\n              <span class=\"text-[10px] font-mono text-[#0088CC] bg-[#0088CC]/10 px-2 py-0.5 rounded border border-[#0088CC]/25\">/cr</span>\n            </div>\n\n            <div onclick=\"setSection('listing')\" class=\"cursor-pointer flex items-center justify-between p-3 rounded-2xl bg-[#111111] hover:bg-[#181818] border border-[#333333] hover:border-[#0088CC]/50 transition group\">\n              <div class=\"flex items-center space-x-3\">\n                <span class=\"w-8 h-8 rounded-xl bg-[#0088CC]/15 text-[#0088CC] flex items-center justify-center font-bold text-base\">📋</span>\n                <div>\n                  <p class=\"font-bold text-[#EEEEEE] group-hover:text-[#0088CC] transition\">Listing Department</p>\n                  <p class=\"text-[11px] text-[#979797]\">Property inventory, dynamic specs & client registry</p>\n                </div>\n              </div>\n              <span class=\"text-[10px] font-mono text-[#0088CC] bg-[#0088CC]/10 px-2 py-0.5 rounded border border-[#0088CC]/25\">/listing</span>\n            </div>\n\n            <div onclick=\"setSection('docs')\" class=\"cursor-pointer flex items-center justify-between p-3 rounded-2xl bg-[#111111] hover:bg-[#181818] border border-[#333333] hover:border-[#0088CC]/50 transition group\">\n              <div class=\"flex items-center space-x-3\">\n                <span class=\"w-8 h-8 rounded-xl bg-[#0088CC]/15 text-[#0088CC] flex items-center justify-center font-bold text-base\">📁</span>\n                <div>\n                  <p class=\"font-bold text-[#EEEEEE] group-hover:text-[#0088CC] transition\">Documentation Team</p>\n                  <p class=\"text-[11px] text-[#979797]\">System file uploads, KYC verification & title deeds</p>\n                </div>\n              </div>\n              <span class=\"text-[10px] font-mono text-[#0088CC] bg-[#0088CC]/10 px-2 py-0.5 rounded border border-[#0088CC]/25\">/docs</span>\n            </div>\n\n            <div onclick=\"setSection('accounts')\" class=\"cursor-pointer flex items-center justify-between p-3 rounded-2xl bg-[#111111] hover:bg-[#181818] border border-[#333333] hover:border-[#0088CC]/50 transition group\">\n              <div class=\"flex items-center space-x-3\">\n                <span class=\"w-8 h-8 rounded-xl bg-[#0088CC]/15 text-[#0088CC] flex items-center justify-center font-bold text-base\">💰</span>\n                <div>\n                  <p class=\"font-bold text-[#EEEEEE] group-hover:text-[#0088CC] transition\">Accounts & Finance</p>\n                  <p class=\"text-[11px] text-[#979797]\">Tax invoices, payment closing & contract renewals</p>\n                </div>\n              </div>\n              <span class=\"text-[10px] font-mono text-[#0088CC] bg-[#0088CC]/10 px-2 py-0.5 rounded border border-[#0088CC]/25\">/accounts</span>\n            </div>\n\n            <div onclick=\"setSection('admin')\" class=\"cursor-pointer flex items-center justify-between p-3 rounded-2xl bg-[#111111] hover:bg-[#181818] border border-[#333333] hover:border-[#0088CC]/50 transition group\">\n              <div class=\"flex items-center space-x-3\">\n                <span class=\"w-8 h-8 rounded-xl bg-[#0088CC]/15 text-[#0088CC] flex items-center justify-center font-bold text-base\">👑</span>\n                <div>\n                  <p class=\"font-bold text-[#EEEEEE] group-hover:text-[#0088CC] transition\">Admin Control Panel</p>\n                  <p class=\"text-[11px] text-[#979797]\">User accounts, passwords & department permissions</p>\n                </div>\n              </div>\n              <span class=\"text-[10px] font-mono text-[#0088CC] bg-[#0088CC]/10 px-2 py-0.5 rounded border border-[#0088CC]/25\">/admin</span>\n            </div>\n\n            <!-- Client Portal Link -->\n            <a href=\"/track\" class=\"flex items-center justify-between p-3 rounded-2xl bg-sky-950/20 hover:bg-sky-950/40 border border-sky-500/30 hover:border-sky-400 transition group\">\n              <div class=\"flex items-center space-x-3\">\n                <span class=\"w-8 h-8 rounded-xl bg-sky-500/20 text-sky-300 flex items-center justify-center font-bold text-base shadow-sm\">🔎</span>\n                <div>\n                  <div class=\"flex items-center space-x-2\">\n                    <p class=\"font-bold text-white group-hover:text-sky-300 transition\">Client Case Status Portal</p>\n                    <span class=\"text-[9px] bg-emerald-500/20 text-emerald-400 px-1.5 py-0.2 rounded font-bold uppercase\">Public</span>\n                  </div>\n                  <p class=\"text-[11px] text-slate-400\">Track deal progress by Name, Mobile Number, or Unique Case ID</p>\n                </div>\n              </div>\n              <span class=\"text-[10px] font-mono text-sky-300 bg-sky-500/15 px-2 py-0.5 rounded border border-sky-500/30 font-bold\">/track &rarr;</span>\n            </a>\n          </div>\n        </div>\n\n        <!-- Right Form Column -->\n        <div class=\"lg:col-span-7 bg-[#111111]/95 border border-[#333333] rounded-3xl p-7 shadow-2xl backdrop-blur-xl space-y-6\">\n\n          <!-- Department Switcher Tabs -->\n          <div>\n            <label class=\"block text-[11px] font-bold text-[#979797] uppercase tracking-wider mb-2\">Select Your Department Section:</label>\n            <div class=\"grid grid-cols-2 sm:grid-cols-5 gap-1.5 bg-black p-1 rounded-xl border border-[#333333] text-xs font-semibold\" id=\"sectionTabs\">\n              <button type=\"button\" onclick=\"setSection('admin')\" id=\"tab-admin\" class=\"py-2 px-1 text-center rounded-lg transition bg-[#0088CC] text-[#EEEEEE] shadow-md shadow-[#0088CC]/20 font-bold\">\n                👑 Admin\n              </button>\n              <button type=\"button\" onclick=\"setSection('cr')\" id=\"tab-cr\" class=\"py-2 px-1 text-center rounded-lg transition text-[#979797] hover:text-[#EEEEEE]\">\n                🤝 CR\n              </button>\n              <button type=\"button\" onclick=\"setSection('listing')\" id=\"tab-listing\" class=\"py-2 px-1 text-center rounded-lg transition text-[#979797] hover:text-[#EEEEEE]\">\n                📋 Listing\n              </button>\n              <button type=\"button\" onclick=\"setSection('docs')\" id=\"tab-docs\" class=\"py-2 px-1 text-center rounded-lg transition text-[#979797] hover:text-[#EEEEEE]\">\n                📁 Docs\n              </button>\n              <button type=\"button\" onclick=\"setSection('accounts')\" id=\"tab-accounts\" class=\"py-2 px-1 text-center rounded-lg transition text-[#979797] hover:text-[#EEEEEE]\">\n                💰 Accounts\n              </button>\n            </div>\n          </div>\n\n          <!-- Login Form -->\n          <form onsubmit=\"handleFormSubmit(event)\" class=\"space-y-4\">\n            <div>\n              <label class=\"block text-xs font-semibold text-[#EEEEEE] mb-1\">Username or Company Email *</label>\n              <div class=\"relative\">\n                <span class=\"absolute inset-y-0 left-0 pl-3 flex items-center text-[#666666] text-xs\">@</span>\n                <input type=\"text\" id=\"loginUsername\" required placeholder=\"e.g. admin\" class=\"w-full bg-black border border-[#333333] focus:border-[#0088CC] rounded-xl pl-8 pr-3.5 py-2.5 text-xs text-[#EEEEEE] focus:outline-none transition\">\n              </div>\n            </div>\n\n            <div>\n              <div class=\"flex items-center justify-between mb-1\">\n                <label class=\"block text-xs font-semibold text-[#EEEEEE]\">Password *</label>\n                <button type=\"button\" onclick=\"togglePasswordVisibility()\" class=\"text-[10px] text-[#0088CC] hover:underline\" id=\"togglePwdBtn\">Show Password</button>\n              </div>\n              <input type=\"password\" id=\"loginPassword\" required placeholder=\"e.g. admin123\" class=\"w-full bg-black border border-[#333333] focus:border-[#0088CC] rounded-xl px-3.5 py-2.5 text-xs text-[#EEEEEE] focus:outline-none transition\">\n            </div>\n\n            <!-- Error Banner -->\n            <div id=\"loginErrorMessage\" class=\"hidden text-xs text-rose-300 bg-rose-950/60 border border-rose-800 p-3 rounded-xl flex items-center space-x-2\">\n              <span>⚠️</span>\n              <span id=\"loginErrorText\">Invalid credentials. Please verify username and password.</span>\n            </div>\n\n            <button type=\"submit\" id=\"submitBtn\" class=\"w-full bg-[#0088CC] hover:bg-[#0077b5] active:scale-95 text-[#EEEEEE] font-bold py-3 px-4 rounded-xl text-xs shadow-lg shadow-[#0088CC]/30 transition flex items-center justify-center space-x-2 cursor-pointer\">\n              <span id=\"submitBtnText\">Sign In to Admin Portal</span>\n              <span>&rarr;</span>\n            </button>\n          </form>\n\n          <!-- 1-Click Fast Fill & Login for Master Admin -->\n          <div class=\"pt-4 border-t border-slate-800 space-y-3\">\n            <div class=\"flex items-center justify-between\">\n              <span class=\"text-[10px] font-bold text-slate-400 uppercase tracking-wider\">⚡ 1-Click Quick Login:</span>\n              <span class=\"text-[10px] text-emerald-400 font-bold\">Only Admin Login</span>\n            </div>\n            \n            <div>\n              <button type=\"button\" onclick=\"quickLogin('admin', 'admin123')\" class=\"w-full p-3 rounded-2xl bg-gradient-to-r from-purple-950/60 via-slate-900 to-indigo-950/60 hover:from-purple-900/60 hover:to-indigo-900/60 border border-purple-500/30 hover:border-purple-400/60 text-left transition-all duration-200 active:scale-98 group flex items-center justify-between shadow-lg cursor-pointer\">\n                <div class=\"flex items-center space-x-3\">\n                  <span class=\"w-9 h-9 rounded-xl bg-purple-500/20 text-purple-300 border border-purple-500/30 flex items-center justify-center text-base font-bold shadow-sm\">👑</span>\n                  <div>\n                    <p class=\"font-bold text-sm text-purple-200 group-hover:text-white flex items-center space-x-1.5\">\n                      <span>admin</span>\n                      <span class=\"text-[9px] bg-purple-500/20 text-purple-300 border border-purple-500/30 px-1.5 py-0.2 rounded font-mono font-normal\">MASTER ADMIN</span>\n                    </p>\n                    <p class=\"text-[11px] text-slate-400 mt-0.5\">Full Master Access: CR, Documentation, Accounts & Admin Portals</p>\n                  </div>\n                </div>\n                <span class=\"px-3 py-1.5 rounded-xl bg-purple-600/30 border border-purple-400/40 text-purple-200 text-xs font-bold group-hover:bg-purple-600 group-hover:text-white transition\">\n                  Click to Fill &rarr;\n                </span>\n              </button>\n            </div>\n          </div>\n        </div>\n      </div>\n\n    </div>\n  </main>\n\n  <!-- Bottom System Footer -->\n  <footer class=\"w-full px-6 py-3 border-t border-slate-900 text-center text-xs text-slate-500 z-10 flex flex-col md:flex-row items-center justify-between\">\n    <span>Prestige Realty Enterprise CRM</span>\n    <span class=\"mt-1 md:mt-0\">All Database Operations Sync in Real-Time</span>\n  </footer>\n\n  <script>\n    let currentSection = 'admin';\n    let sessionUser = null;\n\n    const DEPT_CONFIGS = {\n      admin: {\n        title: \"Sign In to Admin Portal\",\n        tabClass: \"bg-[#0088CC] text-[#EEEEEE] shadow font-bold\",\n        btnClass: \"bg-[#0088CC] hover:bg-[#0077b5]\",\n        demoUser: \"admin\",\n        demoPwd: \"admin123\",\n        redirect: \"/admin\"\n      },\n      cr: {\n        title: \"Sign In to CR Department Portal\",\n        tabClass: \"bg-[#0088CC] text-[#EEEEEE] shadow font-bold\",\n        btnClass: \"bg-[#0088CC] hover:bg-[#0077b5]\",\n        demoUser: \"admin\",\n        demoPwd: \"admin123\",\n        redirect: \"/cr\"\n      },\n      listing: {\n        title: \"Sign In to Listing Department Portal\",\n        tabClass: \"bg-[#0088CC] text-[#EEEEEE] shadow font-bold\",\n        btnClass: \"bg-[#0088CC] hover:bg-[#0077b5]\",\n        demoUser: \"tariq_listing\",\n        demoPwd: \"agent123\",\n        redirect: \"/listing\"\n      },\n      docs: {\n        title: \"Sign In to Documentation Portal\",\n        tabClass: \"bg-[#0088CC] text-[#EEEEEE] shadow font-bold\",\n        btnClass: \"bg-[#0088CC] hover:bg-[#0077b5]\",\n        demoUser: \"admin\",\n        demoPwd: \"admin123\",\n        redirect: \"/docs\"\n      },\n      accounts: {\n        title: \"Sign In to Accounts & Finance Portal\",\n        tabClass: \"bg-[#0088CC] text-[#EEEEEE] shadow font-bold\",\n        btnClass: \"bg-[#0088CC] hover:bg-[#0077b5]\",\n        demoUser: \"admin\",\n        demoPwd: \"admin123\",\n        redirect: \"/accounts\"\n      }\n    };\n\n    async function initPage() {\n      // 1. Check if user is already authenticated\n      try {\n        const res = await fetch('/api/auth/me');\n        if (res.ok) {\n          const data = await res.json();\n          if (data && data.authenticated && data.user) {\n            sessionUser = data.user;\n            renderAuthenticatedView(data.user);\n            return;\n          }\n        }\n      } catch (err) {}\n\n      // 2. Read URL params for pre-selecting section or showing error\n      const params = new URLSearchParams(window.location.search);\n      const sec = params.get('section');\n      if (sec && DEPT_CONFIGS[sec]) {\n        setSection(sec);\n      } else {\n        setSection('admin');\n      }\n\n      if (params.get('error') === 'Unauthorized') {\n        showError(\"Your account does not have permission to access that department page. Please sign in with an authorized account.\");\n      }\n    }\n\n    function renderAuthenticatedView(user) {\n      document.getElementById('loginCard').classList.add('hidden');\n      const card = document.getElementById('authenticatedCard');\n      card.classList.remove('hidden');\n\n      const initials = (user.full_name || user.username || \"U\").split(' ').map(n=>n[0]).join('').substring(0, 2).toUpperCase();\n      document.getElementById('authUserAvatar').innerText = initials;\n      document.getElementById('authUserName').innerText = user.full_name;\n      document.getElementById('authUserRole').innerText = user.role.replace('_', ' ');\n      document.getElementById('authUserUsername').innerText = `@${user.username}`;\n      document.getElementById('authUserEmail').innerText = user.email;\n\n      const linksContainer = document.getElementById('authDeptLinks');\n      const links = [];\n\n      if (user.role === 'MASTER_ADMIN' || user.role === 'DEPT_ADMIN') {\n        links.push(`\n          <a href=\"/admin\" class=\"p-4 rounded-2xl bg-purple-950/40 hover:bg-purple-900/60 border border-purple-800/40 flex items-center justify-between text-white font-bold transition group shadow-sm\">\n            <div class=\"flex items-center space-x-3\">\n              <span class=\"w-8 h-8 rounded-lg bg-purple-500/20 text-purple-300 flex items-center justify-center\">👑</span>\n              <div>\n                <p class=\"text-xs group-hover:text-purple-300 transition\">Admin Control Panel</p>\n                <p class=\"text-[10px] text-slate-400 font-normal\">Full System Oversight</p>\n              </div>\n            </div>\n            <span class=\"text-xs text-purple-400 group-hover:translate-x-1 transition\">&rarr;</span>\n          </a>\n        `);\n      }\n\n      if (user.departments.includes('cr') || user.role === 'MASTER_ADMIN') {\n        links.push(`\n          <a href=\"/cr\" class=\"p-4 rounded-2xl bg-sky-950/40 hover:bg-sky-900/60 border border-sky-800/40 flex items-center justify-between text-white font-bold transition group shadow-sm\">\n            <div class=\"flex items-center space-x-3\">\n              <span class=\"w-8 h-8 rounded-lg bg-sky-500/20 text-sky-300 flex items-center justify-center\">🤝</span>\n              <div>\n                <p class=\"text-xs group-hover:text-sky-300 transition\">CR Department Portal</p>\n                <p class=\"text-[10px] text-slate-400 font-normal\">Leads, Properties & Quotes</p>\n              </div>\n            </div>\n            <span class=\"text-xs text-sky-400 group-hover:translate-x-1 transition\">&rarr;</span>\n          </a>\n        `);\n      }\n\n      if (user.departments.includes('listing') || user.role === 'MASTER_ADMIN') {\n        links.push(`\n          <a href=\"/listing\" class=\"p-4 rounded-2xl bg-emerald-950/40 hover:bg-emerald-900/60 border border-emerald-800/40 flex items-center justify-between text-white font-bold transition group shadow-sm\">\n            <div class=\"flex items-center space-x-3\">\n              <span class=\"w-8 h-8 rounded-lg bg-emerald-500/20 text-emerald-300 flex items-center justify-center\">📋</span>\n              <div>\n                <p class=\"text-xs group-hover:text-emerald-300 transition\">Listing Department Portal</p>\n                <p class=\"text-[10px] text-slate-400 font-normal\">Property & Client Listings Portfolio</p>\n              </div>\n            </div>\n            <span class=\"text-xs text-emerald-400 group-hover:translate-x-1 transition\">&rarr;</span>\n          </a>\n        `);\n      }\n\n      if (user.departments.includes('docs') || user.role === 'MASTER_ADMIN') {\n        links.push(`\n          <a href=\"/docs\" class=\"p-4 rounded-2xl bg-teal-950/40 hover:bg-teal-900/60 border border-teal-800/40 flex items-center justify-between text-white font-bold transition group shadow-sm\">\n            <div class=\"flex items-center space-x-3\">\n              <span class=\"w-8 h-8 rounded-lg bg-teal-500/20 text-teal-300 flex items-center justify-center\">📁</span>\n              <div>\n                <p class=\"text-xs group-hover:text-teal-300 transition\">Documentation Team Vault</p>\n                <p class=\"text-[10px] text-slate-400 font-normal\">Files & KYC Verification</p>\n              </div>\n            </div>\n            <span class=\"text-xs text-teal-400 group-hover:translate-x-1 transition\">&rarr;</span>\n          </a>\n        `);\n      }\n\n      if (user.departments.includes('accounts') || user.role === 'MASTER_ADMIN') {\n        links.push(`\n          <a href=\"/accounts\" class=\"p-4 rounded-2xl bg-amber-950/40 hover:bg-amber-900/60 border border-amber-800/40 flex items-center justify-between text-white font-bold transition group shadow-sm\">\n            <div class=\"flex items-center space-x-3\">\n              <span class=\"w-8 h-8 rounded-lg bg-amber-500/20 text-amber-300 flex items-center justify-center\">💰</span>\n              <div>\n                <p class=\"text-xs group-hover:text-amber-300 transition\">Accounts & Finance Portal</p>\n                <p class=\"text-[10px] text-slate-400 font-normal\">Invoices & Renewals</p>\n              </div>\n            </div>\n            <span class=\"text-xs text-amber-400 group-hover:translate-x-1 transition\">&rarr;</span>\n          </a>\n        `);\n      }\n\n      links.push(`\n        <a href=\"/track\" target=\"_blank\" class=\"p-4 rounded-2xl bg-slate-900 hover:bg-slate-800 border border-sky-500/40 flex items-center justify-between text-white font-bold transition group shadow-sm\">\n          <div class=\"flex items-center space-x-3\">\n            <span class=\"w-8 h-8 rounded-lg bg-sky-500/20 text-sky-300 flex items-center justify-center\">🔎</span>\n            <div>\n              <p class=\"text-xs text-sky-300 group-hover:text-sky-200 transition\">Client Case Status Tracker</p>\n              <p class=\"text-[10px] text-slate-400 font-normal\">Public tracking portal (/track)</p>\n            </div>\n          </div>\n          <span class=\"text-xs text-sky-400 group-hover:translate-x-1 transition\">&rarr;</span>\n        </a>\n      `);\n\n      linksContainer.innerHTML = links.join('');\n    }\n\n    function showLoginForm() {\n      document.getElementById('authenticatedCard').classList.add('hidden');\n      document.getElementById('loginCard').classList.remove('hidden');\n    }\n\n    function setSection(sec) {\n      if (!DEPT_CONFIGS[sec]) return;\n      currentSection = sec;\n      const conf = DEPT_CONFIGS[sec];\n\n      // Reset tabs styling\n      ['admin', 'cr', 'docs', 'accounts'].forEach(k => {\n        const btn = document.getElementById(`tab-${k}`);\n        if (k === sec) {\n          btn.className = `py-2 px-1 text-center rounded-lg transition ${conf.tabClass}`;\n        } else {\n          btn.className = \"py-2 px-1 text-center rounded-lg transition text-slate-400 hover:text-white\";\n        }\n      });\n\n      // Update submit button\n      const submitBtn = document.getElementById('submitBtn');\n      document.getElementById('submitBtnText').innerText = conf.title;\n      submitBtn.className = `w-full bg-gradient-to-r ${conf.btnClass} text-white font-bold py-3 px-4 rounded-xl text-xs shadow-lg transition flex items-center justify-center space-x-2`;\n\n      // Update placeholders\n      document.getElementById('loginUsername').placeholder = `e.g. ${conf.demoUser}`;\n      document.getElementById('loginPassword').placeholder = `e.g. ${conf.demoPwd}`;\n\n      hideError();\n    }\n\n    function togglePasswordVisibility() {\n      const pwd = document.getElementById('loginPassword');\n      const btn = document.getElementById('togglePwdBtn');\n      if (pwd.type === 'password') {\n        pwd.type = 'text';\n        btn.innerText = \"Hide Password\";\n      } else {\n        pwd.type = 'password';\n        btn.innerText = \"Show Password\";\n      }\n    }\n\n    function showError(msg) {\n      const el = document.getElementById('loginErrorMessage');\n      document.getElementById('loginErrorText').innerText = msg;\n      el.classList.remove('hidden');\n    }\n\n    function hideError() {\n      document.getElementById('loginErrorMessage').classList.add('hidden');\n    }\n\n    async function handleFormSubmit(e) {\n      e.preventDefault();\n      hideError();\n\n      const username = document.getElementById('loginUsername').value.trim();\n      const password = document.getElementById('loginPassword').value.trim();\n\n      if (!username || !password) {\n        showError(\"Please enter both username and password.\");\n        return;\n      }\n\n      const submitBtn = document.getElementById('submitBtn');\n      const origText = document.getElementById('submitBtnText').innerText;\n      document.getElementById('submitBtnText').innerText = \"Authenticating...\";\n      submitBtn.disabled = true;\n\n      try {\n        const res = await fetch('/api/auth/login', {\n          method: 'POST',\n          headers: { 'Content-Type': 'application/json' },\n          body: JSON.stringify({ username, password, section: currentSection })\n        });\n\n        if (res.ok) {\n          const data = await res.json();\n          const targetUrl = data.redirect || DEPT_CONFIGS[currentSection].redirect;\n          window.location.href = targetUrl;\n          return;\n        } else {\n          const errData = await res.json().catch(() => ({}));\n          showError(errData.detail || \"Invalid username or password entered. Please verify and try again.\");\n        }\n      } catch (err) {\n        showError(\"Network error connecting to CRM backend server. Please verify server is running.\");\n      } finally {\n        document.getElementById('submitBtnText').innerText = origText;\n        submitBtn.disabled = false;\n      }\n    }\n\n    async function quickLogin(username, password) {\n      document.getElementById('loginUsername').value = username;\n      document.getElementById('loginPassword').value = password;\n      hideError();\n\n      try {\n        const res = await fetch('/api/auth/login', {\n          method: 'POST',\n          headers: { 'Content-Type': 'application/json' },\n          body: JSON.stringify({ username, password, section: currentSection })\n        });\n\n        if (res.ok) {\n          const data = await res.json();\n          window.location.href = data.redirect || '/admin';\n          return;\n        } else {\n          const errData = await res.json().catch(() => ({}));\n          showError(errData.detail || \"Quick login failed.\");\n        }\n      } catch (err) {\n        showError(\"Failed to reach server. Please check connection and try again.\");\n      }\n    }\n\n    async function handleLogout() {\n      try {\n        await fetch('/api/auth/logout', { method: 'POST' });\n      } catch (e) {}\n      window.location.href = '/?logged_out=1';\n    }\n\n    window.addEventListener('DOMContentLoaded', initPage);\n  </script>\n</body>\n</html>\n"