d<!DOCTYPE html>
<html>
<head>
  <base target="_top">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <style>

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: Arial, sans-serif;
  color: #142b50;
  background:
    linear-gradient(135deg, rgba(0,36,105,.92), rgba(0,115,190,.72)),
    linear-gradient(180deg, #168bd0, #f5a35b 65%, #073c79);
  min-height: 100vh;
}

.page-shell {
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  padding-bottom: 20px;

  background-image:
    linear-gradient(
      rgba(0, 35, 90, 0.35),
      rgba(0, 35, 90, 0.45)
    ),
    url("https://drive.google.com/thumbnail?id=1Xqc3boycc_MeJvHaidqJs54Fmyj9IFAv&sz=w2000");

  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

.top-header {
  background: linear-gradient(110deg, #00256f, #0645a5, #00266f);
  color: white;
  min-height: 125px;
  padding: 18px 25px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 25px;
  border-bottom: 4px solid #f4c52e;
  text-align: center;
}

.crest-mark {
  width: 130px;
  min-width: 130px;
  height: 110px;
  border-right: 2px solid #e8c34b;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-right: 15px;
}

.crest-mark img {
  width: 105px;
  height: 105px;
  object-fit: contain;
  display: block;
  mix-blend-mode: screen;
}

.official-heading h1 {
  margin: 0 0 8px;
  font-size: 25px;
  font-weight: 900;
  line-height: 1.15;
}

.official-heading p {
  margin: 5px 0;
  font-size: 16px;
  font-weight: 900;
}

.official-heading .gold {
  color: #ffda32;
}

.official-heading .portal-label {
  display: inline-block;
  border: 1px solid #f5cf43;
  border-radius: 25px;
  padding: 5px 22px;
  margin-top: 3px;
}

.brand-area {
  text-align: center;
  padding: 15px 10px 5px;
}

.brand-ribbon {
  display: inline-block;
  max-width: 95%;
  background: linear-gradient(100deg, #001d63, #073e9e, #001d63);
  border: 5px solid #f5c632;
  border-radius: 60px;
  padding: 8px 35px;
  color: white;
  font-size: clamp(25px, 4vw, 48px);
  font-weight: 900;
  letter-spacing: 1px;
  box-shadow: 0 5px 0 #b77a00, 0 8px 20px #001b4d66;
}

.brand-ribbon span {
  color: #ffd52e;
}

.brand-portal {
  display: inline-block;
  background: linear-gradient(#ff3434, #c60000);
  color: white;
  padding: 5px 35px;
  border-radius: 30px;
  font-size: 25px;
  font-weight: 900;
  margin-top: -2px;
  position: relative;
}

.tagline {
  color: #F4CD55;
  font-size: 15px;
  font-weight: 900;
  letter-spacing: 2px;
  text-align: center;
  margin: 15px 5px 20px;
  text-shadow: 1px 2px 3px rgba(0,0,0,0.35);
}
.portal-layout {
  max-width: 1250px;
  margin: 0 auto;
  padding: 10px 22px 25px;
  display: grid;
  grid-template-columns: 270px minmax(0, 1fr);
  gap: 28px;
  align-items: center;
}

.feature-panel {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 13px;
  background: rgba(255,255,255,.93);
  padding: 13px;
  border-radius: 18px;
  box-shadow: 0 4px 12px #001b4d55;
  border: 1px solid #d7e6ff;
  font-size: 14px;
  font-weight: 900;
  min-height: 75px;
}

.feature-icon {
  width: 53px;
  height: 53px;
  min-width: 53px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 15px;
  color: white;
  font-size: 25px;
  background: linear-gradient(135deg, #0875ef, #002e9d);
}

.feature-item:nth-child(2) .feature-icon {
  background: linear-gradient(135deg, #bd28ec, #6300ad);
}

.feature-item:nth-child(3) .feature-icon {
  background: linear-gradient(135deg, #13cf69, #008039);
}

.feature-item:nth-child(4) .feature-icon {
  background: linear-gradient(135deg, #ffbf20, #ed7200);
}

.portal-card {
  background: rgba(255,255,255,.97);
  border-radius: 22px;
  padding: 25px;
  box-shadow: 0 8px 28px #001b4d55;
  border: 2px solid #dceaff;
  width: 100%;
  max-width: 700px;
  margin: auto;
}

.portal-card-heading {
  text-align: center;
  color: #062a70;
  font-size: 25px;
  font-weight: 900;
  margin: 0 0 20px;
}

.notice {
  background: #fff0a8;
  padding: 13px;
  border-radius: 9px;
  border-left: 5px solid #e9b400;
  font-size: 13px;
  font-weight: bold;
  margin-bottom: 20px;
}

.section-heading {
  background: #062c80;
  color: white;
  text-align: center;
  padding: 9px;
  border-radius: 25px;
  font-size: 17px;
  font-weight: 900;
  margin: 18px 0;
}

label {
  display: block;
  font-weight: bold;
  margin-bottom: 8px;
}

input {
  width: 100%;
  padding: 13px;
  border: 1px solid #a9c3eb;
  border-radius: 13px;
  font-size: 15px;
  margin-bottom: 15px;
  background: white;
}

button {
  background: linear-gradient(100deg, #07358f, #0646b5);
  color: white;
  border: none;
  padding: 13px 25px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 15px;
  font-weight: bold;
}

button:hover {
  background: #00266c;
}

button:disabled {
  opacity: .6;
  cursor: not-allowed;
}

#loginButton {
  width: 100%;
  font-size: 18px;
}

#statusMessage,
#loginMessage,
#dashboardStatus {
  margin-top: 15px;
  font-size: 14px;
}

#resultArea {
  display: none;
  margin-top: 30px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.staff-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
}

.staff-table td {
  padding: 12px;
  border: 1px solid #dce3eb;
  text-align: left;
  font-size: 14px;
}

.staff-table td:first-child {
  font-weight: bold;
  background: #edf3fc;
  width: 42%;
}

.dashboard-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 15px;
}

.dashboard-stat {
  background: #edf4ff;
  padding: 18px;
  border-radius: 12px;
  border-left: 4px solid #e3b323;
}

.dashboard-stat h4 {
  color: #12345a;
}

.dashboard-stat p {
  font-size: 25px;
  font-weight: 900;
}

.bottom-banner {
  max-width: 1250px;
  margin: 15px auto;
  padding: 20px;
  background: linear-gradient(100deg, #00266f, #0748a8, #00266f);
  color: white;
  border-top: 4px solid #f5cb32;
  border-bottom: 4px solid #f5cb32;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  gap: 18px;
  text-align: center;
  font-weight: 900;
}

.bottom-banner div {
  min-width: 180px;
  padding: 5px;
}

.footer {
  text-align: center;
  color: white;
  font-size: 12px;
  margin: 20px 0;
  font-weight: bold;
}

/* =========================================
   RESPONSIVE LAYOUT - TABLET AND MOBILE
   CMD/HR57 CONNECT PORTAL
========================================= */

/* Desktop remains a two-column layout. */

@media (max-width: 800px) {
  .top-header {
    flex-direction: column;
    gap: 10px;
    padding: 15px 12px;
  }

  .crest-mark {
    width: 100%;
    min-width: 0;
    height: 90px;
    border-right: none;
    border-bottom: 2px solid #e8c34b;
    padding: 5px;
  }

  .crest-mark img {
    width: 80px;
    height: 80px;
  }

  .official-heading h1 {
    font-size: 20px;
  }

  .official-heading p {
    font-size: 13px;
  }

  /* Mobile order: login card first, feature panels second. */
  .portal-layout {
    display: flex !important;
    flex-direction: column !important;
    align-items: stretch !important;
    width: 100% !important;
    max-width: 100% !important;
    margin: 0 auto !important;
    padding: 12px !important;
    gap: 15px !important;
  }

  .portal-layout > .portal-card {
    order: 1 !important;
    display: block !important;
    width: 100% !important;
    max-width: 100% !important;
    margin: 0 !important;
    padding: 18px !important;
  }

  .portal-layout > .feature-panel {
    order: 2 !important;
    display: grid !important;
    grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
    width: 100% !important;
    min-width: 0 !important;
    gap: 10px !important;
  }

  .feature-item {
    width: 100% !important;
    min-width: 0 !important;
    font-size: 13px;
  }

  .bottom-banner {
    width: calc(100% - 24px) !important;
    max-width: none !important;
    margin: 12px !important;
  }
}

@media (max-width: 520px) {
  body {
    font-size: 14px;
  }

  .page-shell {
    background-attachment: scroll;
  }

  .top-header {
    padding: 12px 8px;
  }

  .official-heading h1 {
    font-size: 17px;
  }

  .official-heading p {
    font-size: 11px;
    line-height: 1.4;
  }

  .official-heading .portal-label {
    padding: 5px 10px;
    font-size: 10px;
  }

  .brand-area {
    padding: 14px 5px 3px;
  }

  .brand-ribbon {
    max-width: 96%;
    font-size: 22px;
    padding: 9px 12px;
    letter-spacing: 0;
  }

  .brand-portal {
    font-size: 19px;
    padding: 5px 25px;
  }

  .tagline {
    font-size: 11px;
    line-height: 1.5;
    letter-spacing: 1px;
    padding: 0 10px;
  }

  .portal-layout {
    padding: 10px !important;
    gap: 12px !important;
  }

  .portal-layout > .portal-card {
    padding: 16px !important;
    border-radius: 15px;
  }

  .portal-layout > .feature-panel {
    grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
  }

  .portal-card-heading {
    font-size: 20px;
  }

  .notice {
    font-size: 12px;
    line-height: 1.5;
  }

  .section-heading {
    font-size: 14px;
  }

  input {
    padding: 14px;
    font-size: 16px;
  }

  button {
    min-height: 44px;
  }

  #portalNavigation {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  #portalNavigation button {
    width: 100%;
    margin: 0 !important;
  }

  .feature-item {
    min-height: 68px;
    padding: 9px;
    gap: 8px;
    font-size: 11px;
  }

  .feature-icon {
    width: 42px;
    height: 42px;
    min-width: 42px;
    font-size: 21px;
  }

  .bottom-banner {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 5px;
    margin: 12px 8px !important;
    padding: 10px 5px;
    font-size: 11px;
  }

  .bottom-banner div {
    min-width: 0;
    width: auto;
    padding: 6px 3px;
  }

  .dashboard-grid {
    grid-template-columns: 1fr;
  }

  .staff-table td {
    padding: 9px;
    font-size: 12px;
  }

  .footer {
    padding: 0 10px;
    line-height: 1.6;
  }
}

@media (max-width: 360px) {
  .brand-ribbon {
    font-size: 18px;
  }

  .official-heading h1 {
    font-size: 15px;
  }

  .portal-layout > .portal-card {
    padding: 12px !important;
  }

  .portal-card-heading {
    font-size: 18px;
  }
}


/* CMD/HR57 CONNECT ALIGNMENT WITH UPPER BANNER */

.brand-area,
.tagline {
  position: relative;
  left: 5.9vw;
  width: 100%;
  box-sizing: border-box;
  text-align: center;
}

.brand-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.brand-ribbon,
.brand-portal {
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}

.tagline {
  display: block;
}

/* Mobile: retain normal centre alignment */
@media (max-width: 800px) {
  .brand-area,
  .tagline {
    left: 0;
  }
}


</style>
</head>

<body>


<div class="page-shell">

  <header class="top-header">
    <div class="crest-mark">
  <img
    src="https://drive.google.com/thumbnail?id=1VVH9ImDuaWSM_SB35yCm0r-YCecTInbt&sz=w500"
    alt="Lagos State Coat of Arms">
</div>

    <div class="official-heading">
      <h1>LAGOS STATE LOCAL GOVERNMENT<br>SERVICE COMMISSION</h1>
      <p class="gold">STAFF DISPOSITION DATA COLLECTION SYSTEM</p>
      <p class="portal-label">HUMAN RESOURCE MANAGEMENT AND CAREER ADMINISTRATION PORTAL</p>
    </div>
  </header>

  <div class="brand-area">
    <div class="brand-ribbon">
      CMD/<span>HR57</span>CONNECT
    </div>
    <br>
    <div class="brand-portal">PORTAL</div>
  </div>

  <div class="tagline">
    CONNECTING THE 57 LOCAL GOVERNMENTS AND LCDAs
  </div>

  <main class="portal-layout">

    <aside class="feature-panel">

      <div class="feature-item">
        <div class="feature-icon">👥</div>
        <div>Staff Records<br>Management</div>
      </div>

      <div class="feature-item">
        <div class="feature-icon">📊</div>
        <div>Promotion &amp;<br>Retirement Tracking</div>
      </div>

      <div class="feature-item">
        <div class="feature-icon">🏢</div>
        <div>Centralised<br>Personnel Database</div>
      </div>

      <div class="feature-item">
        <div class="feature-icon">🛡</div>
        <div>Secure &amp; Authorised<br>Access</div>
      </div>

    </aside>

    <section class="portal-card">

      <h2 class="portal-card-heading">
        👥 HR Officers' Portal
      </h2>

      <div class="notice">
        🔒 CONFIDENTIALITY NOTICE: This portal is intended for
        authorised personnel only. Access to staff records is
        subject to official authorisation and assigned permissions.
      </div>

      <div id="loginSection" style="margin-bottom:25px;">

        <div class="section-heading">AUTHORISED USER LOGIN</div>

        <p>Please sign in with your registered portal email and password.</p>

        <label for="loginEmail">Email Address</label>
        <input
          type="email"
          id="loginEmail"
          placeholder="Enter your registered email"
          autocomplete="username"
        >

        <label for="loginPassword">Password</label>
        <input
          type="password"
          id="loginPassword"
          placeholder="Enter your password"
          autocomplete="current-password"
        >

        <button type="button" id="loginButton">Sign In</button>
        <p style="text-align:center;margin-top:12px;">
          <button type="button" id="forgotPasswordButton"
                  style="background:transparent;color:#0646b5;text-decoration:underline;padding:5px;">
            Forgot Password?
          </button>
        </p>

        
<div id="loginMessage"
     role="status"
     aria-live="polite"
     style="margin-top:15px;">
</div>
<button
  type="button"
  id="resendVerificationButton"
  style="display:none; margin-top:15px;">
  Resend Verification Email
</button>
      </div>


      <div id="invitationRegistrationSection" style="display:none;margin-bottom:25px;">
        <div class="section-heading">ACTIVATE YOUR PORTAL ACCOUNT</div>
        <p id="invitationInfo">Checking your invitation...</p>
        <label for="invitePassword">Create Password</label>
        <input type="password" id="invitePassword" autocomplete="new-password"
               placeholder="Create a password (minimum 8 characters)">
        <label for="invitePasswordConfirm">Confirm Password</label>
        <input type="password" id="invitePasswordConfirm" autocomplete="new-password"
               placeholder="Re-enter your password">
        <button type="button" id="registerInvitationButton">Create Account</button>
        <p id="invitationMessage" role="status" aria-live="polite"></p>
        <p>Already created your account and verified your email?
          <button type="button" id="showInvitationLoginButton" style="padding:7px 14px;">Sign In</button>
        </p>
      </div>

      <div id="authenticatedSection" style="display:none;">

        <p id="loggedInUser"></p>

        <div style="background:#f0f5ff;padding:14px;border-radius:12px;margin:12px 0;">
          <strong>CHANGE PASSWORD</strong>
          <label for="newPortalPassword" style="margin-top:10px;">New Password</label>
          <input type="password" id="newPortalPassword" autocomplete="new-password"
                 placeholder="Enter new password">
          <label for="confirmPortalPassword">Confirm New Password</label>
          <input type="password" id="confirmPortalPassword" autocomplete="new-password"
                 placeholder="Confirm new password">
          <button type="button" id="changePortalPasswordButton">Update Password</button>
          <p id="passwordChangeMessage" role="status" aria-live="polite"></p>
        </div>

        <button type="button" id="logoutButton"
                style="background:#a52828;">
          Sign Out
        </button>

      </div>

      <div id="portalNavigation" style="display:none; margin-bottom:25px;">

        <button type="button" id="dashboardButton">
          Management Dashboard
        </button>

        <button type="button" id="staffSearchButton" style="margin-left:8px;">
          Staff Record Search
        </button>
        <button type="button" id="reportsButton" style="margin-left:8px;">
          Report Generation
        </button>
        <button type="button" id="nominalRollButton" style="margin-left:8px;display:none;">
          Nominal Roll Download
        </button>

      </div>


      <div id="userManagementSection" style="display:none;margin-bottom:25px;">
        <div class="section-heading">AUTHORised USER INVITATIONS</div>
        <p>Invite approved personnel. The invited user will create their own password and verify their email address.</p>
        <label for="inviteFullName">Full Name</label>
        <input type="text" id="inviteFullName" placeholder="Enter user's full name">
        <label for="inviteEmail">Official Email Address</label>
        <input type="email" id="inviteEmail" placeholder="Enter user's email address">
        <label for="inviteRole">Access Role</label>
        <select id="inviteRole" style="width:100%;padding:13px;border:1px solid #a9c3eb;border-radius:13px;font-size:15px;margin-bottom:15px;background:white;">
          <option value="HR OFFICER">HR Officer</option>
          <option value="MANAGEMENT">Management</option>
          <option value="ICT ADMINISTRATOR">ICT Administrator</option>
          <option value="CMD STAFF">CMD Staff</option>
        </select>
        <label for="inviteDepartment">Assigned LGA / LCDA (HR Officers only)</label>
        <input type="text" id="inviteDepartment" placeholder="Enter assigned LGA / LCDA">
        <button type="button" id="sendInvitationButton">Send Secure Invitation</button>
        <p id="userManagementMessage" role="status" aria-live="polite"></p>
      </div>
      <div id="cmdStaffApprovalSection"
     style="display:none;margin-bottom:25px;">

  <div class="section-heading">
    CMD STAFF ACCOUNT APPROVAL
  </div>

  <p>
    Management and ICT Administrator must approve a CMD STAFF account
    before staff records can be added or edited.
  </p>

  <label for="cmdStaffApprovalEmail">
    CMD Staff Official Email Address
  </label>

  <input type="email"
         id="cmdStaffApprovalEmail"
         placeholder="Enter CMD Staff email address">

  <button type="button" id="checkCmdStaffApprovalButton">
    Check Approval Status
  </button>
<div id="cmdStaffApprovalActions" style="margin-top:12px;">

  <button type="button" id="managementApproveCmdStaffButton">
    Approve CMD STAFF — Management
  </button>

  <button type="button" id="managementRevokeCmdStaffButton">
    Revoke Management Approval
  </button>

  <button type="button" id="ictApproveCmdStaffButton">
    Approve CMD STAFF — ICT
  </button>

  <button type="button" id="ictRevokeCmdStaffButton">
    Revoke ICT Approval
  </button>
<button type="button" id="grantCmdStaffEditAccessButton"
        style="background:#176b3a;margin-top:10px;">
  Grant Temporary Editing Access (30 Minutes)
</button>
</div>
  <p id="cmdStaffApprovalStatus"
     role="status"
     aria-live="polite"></p>

</div>

      <div id="dashboardSection" style="display:none;">

        <div class="section-heading">MANAGEMENT DASHBOARD</div>

        <p id="dashboardStatus" role="status" aria-live="polite">
          Dashboard statistics will appear here.
        </p>

        <div id="dashboardCards"></div>

        <button type="button" id="refreshDashboardButton"
                style="margin-top:20px;">
          Refresh Dashboard
        </button>

      </div>

      <div id="reportSection" style="display:none;">

        <div class="section-heading">REPORT GENERATION</div>

        <p>Select a report and generate the latest authorised staff information.</p>

        <label for="reportType">Select Report Type</label>
        <select id="reportType" style="width:100%;padding:13px;border:1px solid #a9c3eb;border-radius:13px;font-size:15px;margin-bottom:15px;background:white;">
          <option value="STAFF_MASTER">Staff Master Report</option>
          <option value="LGA_DISTRIBUTION">LGA / LCDA Distribution Report</option>
          <option value="GRADE_LEVEL">Grade Level Distribution Report</option>
          <option value="PROMOTION">Expected Promotion Report</option>
          <option value="RETIREMENT">Expected Retirement Report</option>
          <option value="EMPLOYMENT_STATUS">Employment Status Report</option>
        </select>

        <div style="display:flex;gap:10px;flex-wrap:wrap;">
          <button type="button" id="generateReportButton">Generate Report</button>
          <button type="button" id="exportReportButton" style="display:none;background:#08743d;">Export to Excel (CSV)</button>
          <button type="button" id="printReportButton" style="display:none;background:#555;">Print / Save as PDF</button>
        </div>

        <p id="reportStatus" role="status" aria-live="polite"></p>
        <div id="reportSummary" style="font-weight:bold;margin:12px 0;"></div>
        <div id="reportOutput" class="table-container"></div>

      </div>

      <div id="nominalRollSection" style="display:none;">

        <div class="section-heading">NOMINAL ROLL DOWNLOAD</div>
        <p>Generate the authorised staff Nominal Roll for Excel and PDF download.</p>
        <p id="nominalRollStatus" role="status" aria-live="polite"></p>
        <button type="button" id="generateNominalRollButton">Generate Nominal Roll</button>
        <div id="nominalRollLinks" style="margin-top:18px;line-height:2;"></div>

      </div>

      <div id="staffSearchSection" style="display:none;">

        <div class="section-heading">STAFF RECORD SEARCH</div>
  

</div>

        <label for="oracleID">Enter Staff Oracle ID</label>

        <input
          type="text"
          id="oracleID"
          placeholder="Enter Oracle ID"
        >

        <button type="button" id="searchButton">
          Search Staff Record
        </button>
        <div id="staffEditingLinkSection"
     style="display:none; margin-top:20px;">

 <div id="staffEditingLinkSection">
  <button type="button" id="getStaffEditingLinkButton">
    Get / Generate Staff Editing Link
  </button>

  <div id="staffEditingLinkResult"
       style="margin-top:15px;">
  </div>
</div>
</div>

        <div id="statusMessage" role="status" aria-live="polite"></div>

        <div id="resultArea">

          <h3>STAFF PERSONNEL INFORMATION</h3>

          <div class="table-container">
            <div id="staffDetails"></div>
          </div>

          <button type="button" id="clearButton" style="margin-top:20px;">
            Search Another Staff
          </button>

        </div>

      </div>

    </section>

  </main>

  <div class="bottom-banner">
    <div>👥<br>57 LGs/LCDAs<br>Integration</div>
    <div>💻<br>Real-time<br>Personnel Data</div>
    <div>📊<br>Reporting &amp;<br>Decision Support</div>
  </div>

  <div class="footer">
    Lagos State Local Government Service Commission<br>
    Staff Disposition Data Collection System
  </div>

</div>

<script src="https://www.gstatic.com/firebasejs/10.12.5/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.12.5/firebase-auth-compat.js"></script>
<script>


  // INVITATION TOKEN PROVIDED BY THE APPS SCRIPT WEB APP
  
const invitationToken = <?!= JSON.stringify(invitationToken) ?>;

  console.log("FRONTEND TOKEN LENGTH: " +
  String(invitationToken || "").length);

console.log("FRONTEND TOKEN START: " +
  String(invitationToken || "").substring(0, 4));

console.log("FRONTEND TOKEN END: " +
  String(invitationToken || "").slice(-4));

  // FIREBASE CONFIGURATION

  const firebaseConfig = {
    apiKey: "AIzaSyBvKok2BCAxvpK6EgEjNGrL_vEe8-EndCw",
    authDomain: "lagos-staff-disposition-portal.firebaseapp.com",
    projectId: "lagos-staff-disposition-portal",
    storageBucket: "lagos-staff-disposition-portal.firebasestorage.app",
    messagingSenderId: "325409211102",
    appId: "1:325409211102:web:16632541e332adee99f84f"
  };

  // INITIALISE FIREBASE

  if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
  }

  const auth = firebase.auth();
  let invitationRegistrationInProgress = false;


  // LOAD AUTHORISED USER INFORMATION

  let currentUserRole = "";


function loadPortalUser(idToken) {

  google.script.run

    .withSuccessHandler(function(user) {

      currentUserRole = user.accessLevel;
      document.getElementById("getStaffEditingLinkButton").style.display =
  currentUserRole === "ICT ADMINISTRATOR" ? "inline-block" : "none";
     document.getElementById("staffEditingLinkSection").style.display =
  (
    currentUserRole === "ICT ADMINISTRATOR" ||
    currentUserRole === "CMD STAFF"
  ) ? "block" : "none";
      document.getElementById("userManagementSection").style.display =
        currentUserRole === "ICT ADMINISTRATOR" ? "block" : "none";
        document.getElementById("cmdStaffApprovalSection").style.display =
  ["MANAGEMENT", "ICT ADMINISTRATOR", "CMD STAFF"].includes(currentUserRole)
    ? "block"
    : "none";
    document.getElementById("cmdStaffApprovalActions").style.display =
  ["MANAGEMENT", "ICT ADMINISTRATOR"].includes(currentUserRole)
    ? "block"
    : "none";

      document.getElementById("loginSection").style.display = "none";
      document.getElementById("authenticatedSection").style.display = "block";

      document.getElementById("loggedInUser").textContent =
        "Signed in as: " + user.name + " (" + user.accessLevel + ")";

      const navigation =
        document.getElementById("portalNavigation");

      const dashboardButton =
        document.getElementById("dashboardButton");

      const staffButton =
        document.getElementById("staffSearchButton");

      if (currentUserRole === "MANAGEMENT") {

        navigation.style.display = "block";
        dashboardButton.style.display = "inline-block";
        staffButton.style.display = "inline-block";
        document.getElementById("reportsButton").style.display = "inline-block";
        // Management is authorised to download the consolidated Nominal Roll.
document.getElementById("nominalRollButton").style.display = "inline-block";

        showDashboard();

      } else if (currentUserRole === "HR OFFICER") {
        

        navigation.style.display = "block";
        dashboardButton.style.display = "none";
        staffButton.style.display = "inline-block";
        document.getElementById("reportsButton").style.display = "inline-block";
        document.getElementById("nominalRollButton").style.display = "inline-block";

        showStaffSearch();

     } else if (currentUserRole === "ICT ADMINISTRATOR") {

  navigation.style.display = "block";
  dashboardButton.style.display = "inline-block";
  staffButton.style.display = "inline-block";
  document.getElementById("reportsButton").style.display = "inline-block";
  document.getElementById("nominalRollButton").style.display = "inline-block";

  showDashboard();

} else if (currentUserRole === "CMD STAFF") {

  navigation.style.display = "block";
  dashboardButton.style.display = "none";
  staffButton.style.display = "inline-block";
  document.getElementById("reportsButton").style.display = "none";
  document.getElementById("nominalRollButton").style.display = "none";

  showStaffSearch();

}
    })

    .withFailureHandler(function(error) {

      document.getElementById("loginMessage").textContent =
        "Portal access error: " + error.message;

    })

    .getPortalUserInfo(idToken);

}


  // FIREBASE SIGN IN

  
document.getElementById("loginButton")
  .addEventListener("click", async function() {

    const email = document.getElementById("loginEmail").value.trim();
    const password = document.getElementById("loginPassword").value;
    const message = document.getElementById("loginMessage");
    const button = document.getElementById("loginButton");
    const resendButton = document.getElementById("resendVerificationButton");

    if (!email || !password) {
      message.textContent = "Please enter your email address and password.";
      return;
    }

    button.disabled = true;
    button.textContent = "Signing in...";
    message.textContent = "";
    resendButton.style.display = "none";

    try {

      const credential = await auth.signInWithEmailAndPassword(
        email,
        password
      );

      await credential.user.reload();

      if (!credential.user.emailVerified) {

        message.textContent =
          "Your email address is not verified. Please verify your email before accessing the portal.";

        resendButton.style.display = "inline-block";

        // Keep the user signed in so the verification email can be resent.
        return;
      }

      resendButton.style.display = "none";

    } catch (error) {

      message.textContent = "Login failed: " + error.message;

    } finally {

      button.disabled = false;
      button.textContent = "Sign In";

    }

  });


  // FIREBASE SIGN OUT

  document.getElementById("logoutButton")
    .addEventListener("click", async function() {

      try {
        // Revoke CMD STAFF temporary editing access before signing out.
        if (
          currentUserRole === "CMD STAFF" &&
          auth.currentUser
        ) {
          try {
            const idToken = await auth.currentUser.getIdToken();

            await new Promise((resolve, reject) => {
              google.script.run
                .withSuccessHandler(resolve)
                .withFailureHandler(reject)
                .revokeCmdStaffEditAccessOnLogout(idToken);
            });

          } catch (revokeError) {
            console.warn(
              "Temporary access revocation failed:",
              revokeError
            );
          }
        }
        await auth.signOut();

        document.getElementById("loginSection").style.display = "block";
        document.getElementById("authenticatedSection").style.display = "none";
        document.getElementById("portalNavigation").style.display = "none";
        document.getElementById("dashboardSection").style.display = "none";
        document.getElementById("staffSearchSection").style.display = "none";
        document.getElementById("reportSection").style.display = "none";
        document.getElementById("loginPassword").value = "";
        document.getElementById("loginMessage").textContent = "You have signed out successfully.";

      } catch (error) {

        document.getElementById("loginMessage").textContent =
          "Sign-out error: " + error.message;

      }

    });

  // MONITOR FIREBASE AUTHENTICATION STATE

  auth.onAuthStateChanged(async function(firebaseUser) {

    if (invitationRegistrationInProgress) return;

    const loginSection = document.getElementById("loginSection");
    const authenticatedSection = document.getElementById("authenticatedSection");
    const loginButton = document.getElementById("loginButton");

    if (!firebaseUser) {

      loginSection.style.display = "block";
      authenticatedSection.style.display = "none";
      document.getElementById("portalNavigation").style.display = "none";
      document.getElementById("dashboardSection").style.display = "none";
      document.getElementById("staffSearchSection").style.display = "none";
      document.getElementById("reportSection").style.display = "none";
      document.getElementById("userManagementSection").style.display = "none";

      loginButton.disabled = false;
      loginButton.textContent = "Sign In";

      return;
    }

    try {

      if (invitationToken) {
        const handled = await completeInvitationIfNeeded(firebaseUser);
        if (handled) return;
      } else if (!firebaseUser.emailVerified) {
        await auth.signOut();
        document.getElementById("loginMessage").textContent =
          "Your email address is not verified. Please check your inbox and verify your email before signing in.";
        return;
      }

      const idToken = await firebaseUser.getIdToken();

      loadPortalUser(idToken);

    } catch (error) {

      document.getElementById("loginMessage").textContent =
        "Portal authentication error: " + error.message;

      await auth.signOut();

    }

  });


  // DISPLAY MANAGEMENT DASHBOARD

  function showDashboard() {

    document.getElementById("dashboardSection").style.display = "block";
    document.getElementById("staffSearchSection").style.display = "none";
    document.getElementById("reportSection").style.display = "none";
    document.getElementById("nominalRollSection").style.display = "none";

    loadManagementDashboard();

  }


  // DISPLAY STAFF SEARCH

  function showStaffSearch() {

    document.getElementById("dashboardSection").style.display = "none";
    document.getElementById("staffSearchSection").style.display = "block";
    document.getElementById("reportSection").style.display = "none";
    document.getElementById("nominalRollSection").style.display = "none";

  }

  // DISPLAY REPORT GENERATION MODULE
  function showReports() {
    document.getElementById("dashboardSection").style.display = "none";
    document.getElementById("staffSearchSection").style.display = "none";
    document.getElementById("reportSection").style.display = "block";
    document.getElementById("nominalRollSection").style.display = "none";
    document.getElementById("reportStatus").textContent =
      "Choose a report type, then select Generate Report.";
  }


  // DISPLAY NOMINAL ROLL MODULE
  function showNominalRoll() {
    document.getElementById("dashboardSection").style.display = "none";
    document.getElementById("staffSearchSection").style.display = "none";
    document.getElementById("reportSection").style.display = "none";
    document.getElementById("nominalRollSection").style.display = "block";
    document.getElementById("nominalRollStatus").textContent =
      "Generate the Nominal Roll for your authorised area.";
    document.getElementById("nominalRollLinks").innerHTML = "";
  }

  async function generateNominalRollDownloads() {
    const status = document.getElementById("nominalRollStatus");
    const links = document.getElementById("nominalRollLinks");
    links.innerHTML = "";
    status.textContent = "Generating Nominal Roll files. Please wait...";

    if (!auth.currentUser) {
      status.textContent = "Please sign in again to continue.";
      return;
    }

    try {
      const idToken = await auth.currentUser.getIdToken();
      google.script.run
        .withSuccessHandler(function(result) {
          status.textContent = "Nominal Roll generated successfully. Records: " + result.total;
          links.innerHTML =
            '<a href="' + result.excelUrl + '" target="_blank" rel="noopener">Download Excel Nominal Roll</a><br>' +
            '<a href="' + result.pdfUrl + '" target="_blank" rel="noopener">Download PDF Nominal Roll</a>';
        })
        .withFailureHandler(function(error) {
          status.textContent = "Unable to generate Nominal Roll: " + error.message;
        })
        .generateNominalRollFiles(idToken);
    } catch (error) {
      status.textContent = "Authentication error: " + error.message;
    }
  }

  // RETRIEVE DASHBOARD STATISTICS



async function loadManagementDashboard() {

  const status = document.getElementById("dashboardStatus");

  status.textContent = "Loading dashboard statistics...";

  if (!auth.currentUser) {
    status.textContent = "Please sign in to continue.";
    return;
  }

  try {

    const idToken = await auth.currentUser.getIdToken();

    google.script.run

      .withSuccessHandler(function(data) {

  console.log("DASHBOARD BACKEND DATA:", data);

  if (!data || typeof data !== "object") {
    status.textContent =
      "Dashboard error: The server returned no data. Please contact the ICT Administrator.";

    console.error(
      "Dashboard returned an empty or invalid response:",
      data
    );

    return;
  }

  
// FIVE GENERAL DASHBOARD STATISTICS
const generalStatistics = [
  ["TOTAL STAFF", data.totalStaff],
  ["TOTAL LGAs / LCDAs", data.totalLGAs],
  ["GRADE LEVELS REPRESENTED", data.gradeLevels],
  ["EXPECTED PROMOTIONS", data.expectedPromotions],
  ["EXPECTED RETIREMENTS", data.expectedRetirements]
];

        // FIVE GENDER DASHBOARD STATISTICS
        const genderStatistics = [
          ["MALE STAFF", data.maleStaff ?? 0],
          ["FEMALE STAFF", data.femaleStaff ?? 0],
          ["GENDER NOT RECORDED", data.unrecordedGender ?? 0],
          ["MALE STAFF (%)", (data.malePercentage ?? 0) + "%"],
          ["FEMALE STAFF (%)", (data.femalePercentage ?? 0) + "%"]
        ];

        // FUNCTION TO CREATE STATISTIC CARDS
        function createDashboardGrid(items) {

          const grid = document.createElement("div");
          grid.className = "dashboard-grid";

          items.forEach(function(item) {

            const card = document.createElement("div");
            card.className = "dashboard-stat";

            const heading = document.createElement("h4");
            heading.textContent = item[0];

            const value = document.createElement("p");
            value.textContent = item[1] ?? 0;

            card.appendChild(heading);
            card.appendChild(value);

            grid.appendChild(card);

          });

          return grid;
        }

        // GENERAL STATISTICS
        const generalGrid =
          createDashboardGrid(generalStatistics);

        // GRADE LEVEL DISTRIBUTION HEADING
        const gradeHeading = document.createElement("h3");
        gradeHeading.textContent =
          "STAFF DISTRIBUTION BY GRADE LEVEL";

        gradeHeading.style.color = "#12345a";
        gradeHeading.style.marginTop = "25px";
        gradeHeading.style.marginBottom = "12px";

        // GRADE LEVEL DISTRIBUTION TABLE
        const gradeTable = document.createElement("table");

        gradeTable.style.width = "100%";
        gradeTable.style.borderCollapse = "collapse";
        gradeTable.style.background = "#ffffff";
        gradeTable.style.borderRadius = "10px";
        gradeTable.style.overflow = "hidden";
        gradeTable.style.marginBottom = "20px";

        const gradeHead = document.createElement("thead");
        const headerRow = document.createElement("tr");

        ["GRADE LEVEL", "NUMBER OF STAFF"].forEach(function(text) {

          const th = document.createElement("th");
          th.textContent = text;
          th.style.background = "#0b327b";
          th.style.color = "#ffffff";
          th.style.padding = "12px";
          th.style.textAlign = "left";
          th.style.border = "1px solid #d5dfef";

          headerRow.appendChild(th);

        });

        gradeHead.appendChild(headerRow);
        gradeTable.appendChild(gradeHead);

        const gradeBody = document.createElement("tbody");

        const gradeBreakdown =
          Array.isArray(data.gradeLevelBreakdown)
            ? data.gradeLevelBreakdown
            : [];

        let gradeTotal = 0;

        if (gradeBreakdown.length > 0) {

          gradeBreakdown.forEach(function(item) {

            const row = document.createElement("tr");

            const gradeCell = document.createElement("td");
            gradeCell.textContent = item.gradeLevel;

            const countCell = document.createElement("td");
            countCell.textContent = item.staffCount;

            gradeTotal += Number(item.staffCount) || 0;

            [gradeCell, countCell].forEach(function(cell) {

              cell.style.padding = "11px";
              cell.style.border = "1px solid #d5dfef";
              cell.style.color = "#142b50";

            });

            row.appendChild(gradeCell);
            row.appendChild(countCell);

            gradeBody.appendChild(row);

          });

        } else {

          const row = document.createElement("tr");
          const cell = document.createElement("td");

          cell.colSpan = 2;
          cell.textContent =
            "No grade-level distribution data is available.";

          cell.style.padding = "12px";
          cell.style.textAlign = "center";

          row.appendChild(cell);
          gradeBody.appendChild(row);

        }

        // TOTAL STAFF ROW
        const totalRow = document.createElement("tr");

        const totalLabel = document.createElement("td");
        totalLabel.textContent = "TOTAL STAFF WITH GRADE RECORDED";

        const totalValue = document.createElement("td");
        totalValue.textContent = gradeTotal;

        [totalLabel, totalValue].forEach(function(cell) {

          cell.style.padding = "12px";
          cell.style.fontWeight = "bold";
          cell.style.background = "#e8f0ff";
          cell.style.border = "1px solid #d5dfef";

        });

        totalRow.appendChild(totalLabel);
        totalRow.appendChild(totalValue);

        gradeBody.appendChild(totalRow);

        // GRADE LEVELS NOT RECORDED
        const missingRow = document.createElement("tr");

        const missingLabel = document.createElement("td");
        missingLabel.textContent = "GRADE LEVEL NOT RECORDED";

        const missingValue = document.createElement("td");
        missingValue.textContent =
          data.gradeLevelNotRecorded ?? 0;

        [missingLabel, missingValue].forEach(function(cell) {

          cell.style.padding = "11px";
          cell.style.border = "1px solid #d5dfef";

        });

        missingRow.appendChild(missingLabel);
        missingRow.appendChild(missingValue);

        gradeBody.appendChild(missingRow);

        gradeTable.appendChild(gradeBody);

        // GENDER DISTRIBUTION
        const genderHeading = document.createElement("h3");

        genderHeading.textContent =
          "STAFF DISTRIBUTION BY GENDER";

        genderHeading.style.color = "#12345a";
        genderHeading.style.marginTop = "25px";

        const genderGrid =
          createDashboardGrid(genderStatistics);
// ---------------------------------------
// INTERACTIVE PROMOTION FORECAST
// ---------------------------------------

const promotionHeading = document.createElement("h3");
promotionHeading.textContent = "2027 PROMOTION FORECAST";
promotionHeading.style.marginTop = "25px";

const promotionTable = document.createElement("table");
promotionTable.className = "table table-bordered table-striped";

const promotionCategories = [
  {
    title: "January 2027 Promotion List",
    officers: data.january2027Promotions || []
  },
  {
    title: "July 2027 Promotion List",
    officers: data.july2027Promotions || []
  },
  {
    title: "Combined January Examination",
    officers: (data.january2027Promotions || [])
      .concat(data.july2027Promotions || [])
  },
  {
    title: "Previous Years' Outstanding Promotions",
    officers: data.outstandingPromotions || []
  }
];
const promotionBody = document.createElement("tbody");

promotionCategories.forEach((item, index) => {
  const tr = document.createElement("tr");

  const nameCell = document.createElement("td");
  nameCell.textContent = item.title;

  const countCell = document.createElement("td");
  countCell.textContent = item.officers.length;

  const actionCell = document.createElement("td");
  const viewButton = document.createElement("button");
  viewButton.textContent = "VIEW OFFICERS";
  viewButton.className = "btn btn-primary btn-sm";
  viewButton.onclick = () => {
    displayPromotionOfficers(item.officers, item.title);
  };

  actionCell.appendChild(viewButton);
  tr.append(nameCell, countCell, actionCell);
  promotionBody.appendChild(tr);
});

promotionTable.innerHTML = `
  <thead>
    <tr>
      <th>Promotion Category</th>
      <th>Number of Officers</th>
      <th>Action</th>
    </tr>
  </thead>
`;

promotionTable.appendChild(promotionBody);

const promotionDetailsHeading = document.createElement("h4");
promotionDetailsHeading.textContent = "PROMOTION OFFICERS DETAILS";
promotionDetailsHeading.style.marginTop = "20px";

const promotionDetailsTable = document.createElement("table");
promotionDetailsTable.className = "table table-bordered table-striped";
promotionDetailsTable.id = "promotionDetailsTable";

function displayPromotionOfficers(officers, title) {
  promotionDetailsHeading.textContent = title;

  promotionDetailsTable.innerHTML = `
    <thead>
      <tr>
        <th>Full Name</th>
        <th>Oracle ID</th>
        <th>Grade Level</th>
        <th>Designation / Present Appointment</th>
        <th>LGA/LCDA</th>
        <th>Expected Promotion Date</th>
      </tr>
    </thead>
    <tbody>
      ${officers.map(officer => `
        <tr>
          <td>${officer.fullName || ""}</td>
          <td>${officer.oracleID || ""}</td>
          <td>${officer.gradeLevel || ""}</td>
          <td>${officer.designation || ""}</td>
          <td>${officer.lga || ""}</td>
          <td>${officer.promotionDate || ""}</td>
        </tr>
      `).join("")}
    </tbody>
  `;
}
        // ---------------------------------------
        // INTERACTIVE RETIREMENT FORECAST
        // ---------------------------------------

        const retirementHeading = document.createElement("h3");

        retirementHeading.textContent =
          "MONTHLY RETIREMENT FORECAST";

        retirementHeading.style.color = "#12345a";
        retirementHeading.style.marginTop = "30px";

        const retirementMonths = Array.isArray(data.retirementMonths)
          ? data.retirementMonths
          : [];

        // MONTHLY RETIREMENT TABLE
        const retirementTable = document.createElement("table");

        retirementTable.style.width = "100%";
        retirementTable.style.borderCollapse = "collapse";
        retirementTable.style.marginBottom = "20px";

        const retirementHead = document.createElement("thead");
        const retirementHeaderRow = document.createElement("tr");

        ["RETIREMENT MONTH", "NUMBER OF OFFICERS", "ACTION"]
          .forEach(function(label) {

            const th = document.createElement("th");
            th.textContent = label;
            th.style.background = "#0b327b";
            th.style.color = "#ffffff";
            th.style.padding = "10px";
            th.style.textAlign = "left";
            th.style.border = "1px solid #d5dfef";

            retirementHeaderRow.appendChild(th);
          });

        retirementHead.appendChild(retirementHeaderRow);
        retirementTable.appendChild(retirementHead);

        const retirementBody = document.createElement("tbody");

        // OFFICER DETAILS SECTION
        const retirementDetailsHeading =
          document.createElement("h3");

        retirementDetailsHeading.textContent =
          "RETIRED OFFICERS - SELECT A MONTH";

        retirementDetailsHeading.style.color = "#12345a";
        retirementDetailsHeading.style.marginTop = "25px";

        const retirementDetailsTable =
          document.createElement("table");

        retirementDetailsTable.style.width = "100%";
        retirementDetailsTable.style.borderCollapse = "collapse";
        retirementDetailsTable.style.marginBottom = "20px";

        function displayRetirementOfficers(monthItem) {

          retirementDetailsHeading.textContent =
            "OFFICERS DUE FOR RETIREMENT - " +
            monthItem.monthName;

          retirementDetailsTable.replaceChildren();

          const detailHead = document.createElement("thead");
          const detailHeaderRow = document.createElement("tr");

          [
            "FULL NAME",
            "ORACLE ID",
            "GRADE LEVEL",
            "LGA / LCDA",
            "RETIREMENT DATE"
          ].forEach(function(label) {

            const th = document.createElement("th");
            th.textContent = label;
            th.style.background = "#0b327b";
            th.style.color = "#ffffff";
            th.style.padding = "10px";
            th.style.border = "1px solid #d5dfef";
            th.style.textAlign = "left";

            detailHeaderRow.appendChild(th);
          });

          detailHead.appendChild(detailHeaderRow);
          retirementDetailsTable.appendChild(detailHead);

          const detailBody = document.createElement("tbody");

          const officers = Array.isArray(monthItem.officers)
            ? monthItem.officers
            : [];

          if (officers.length === 0) {

            const row = document.createElement("tr");
            const cell = document.createElement("td");

            cell.colSpan = 5;
            cell.textContent =
              "No officers are scheduled for retirement in this month.";

            cell.style.padding = "12px";
            cell.style.textAlign = "center";

            row.appendChild(cell);
            detailBody.appendChild(row);

          } else {

            officers.forEach(function(officer) {

              const row = document.createElement("tr");

              const values = [
                officer.fullName || "",
                officer.oracleID || "",
                officer.gradeLevel || "",
                officer.lga || "",
                officer.retirementDate || ""
              ];

              values.forEach(function(value) {

                const cell = document.createElement("td");

                cell.textContent = value;
                cell.style.padding = "9px";
                cell.style.border = "1px solid #d5dfef";
                cell.style.color = "#142b50";

                row.appendChild(cell);
              });

              detailBody.appendChild(row);
            });
          }

          retirementDetailsTable.appendChild(detailBody);
        }

        retirementMonths.forEach(function(monthItem) {

          const row = document.createElement("tr");

          const monthCell = document.createElement("td");
          monthCell.textContent = monthItem.monthName;

          const countCell = document.createElement("td");
          countCell.textContent = monthItem.count;

          const actionCell = document.createElement("td");

          const viewButton = document.createElement("button");

          viewButton.type = "button";
          viewButton.textContent = "VIEW OFFICERS";
          viewButton.style.background = "#0b327b";
          viewButton.style.color = "#ffffff";
          viewButton.style.border = "none";
          viewButton.style.borderRadius = "6px";
          viewButton.style.padding = "8px 12px";
          viewButton.style.cursor = "pointer";

          viewButton.addEventListener("click", function() {
            displayRetirementOfficers(monthItem);
          });

          actionCell.appendChild(viewButton);

          [monthCell, countCell, actionCell].forEach(function(cell) {

            cell.style.padding = "10px";
            cell.style.border = "1px solid #d5dfef";
            cell.style.color = "#142b50";

          });

          row.appendChild(monthCell);
          row.appendChild(countCell);
          row.appendChild(actionCell);

          retirementBody.appendChild(row);
        });

        if (retirementMonths.length === 0) {

          const row = document.createElement("tr");
          const cell = document.createElement("td");

          cell.colSpan = 3;
          cell.textContent =
            "No retirement forecast data is available.";

          cell.style.padding = "12px";

          row.appendChild(cell);
          retirementBody.appendChild(row);
        }

        retirementTable.appendChild(retirementBody);


        // DISPLAY ALL DASHBOARD SECTIONS
        const dashboardContainer =
          document.getElementById("dashboardCards");

  dashboardContainer.replaceChildren(
  generalGrid,
  gradeHeading,
  gradeTable,
  genderHeading,
  genderGrid,
  promotionHeading,
  promotionTable,
  promotionDetailsHeading,
  promotionDetailsTable,
  retirementHeading,
  retirementTable,
  retirementDetailsHeading,
  retirementDetailsTable
);
        status.textContent =
          "Dashboard updated successfully.";

      })

      .withFailureHandler(function(error) {

        status.textContent =
          "Dashboard error: " + error.message;

      })

      .getManagementDashboard(idToken);

  } catch (error) {

    status.textContent =
      "Authentication error: " + error.message;

  }

}

function convertHRDateToISO(dateText) {
  if (!dateText) return "";

  const months = {
    January: "01", February: "02", March: "03",
    April: "04", May: "05", June: "06",
    July: "07", August: "08", September: "09",
    October: "10", November: "11", December: "12"
  };

  const match = String(dateText).trim().match(
    /^(\d{1,2})\s+([A-Za-z]+)\s+(\d{4})$/
  );

  if (!match || !months[match[2]]) return "";

  return match[3] + "-" + months[match[2]] + "-" +
    String(match[1]).padStart(2, "0");
}


function displayStaffRecord(staff) {
  const gradeNumber = parseInt(
  String(staff.gradeLevel || "").replace(/\D/g, ""), 10
);

const nextPromotionDisplay =
  gradeNumber === 17
    ? "Maximum Grade Level Attained"
    : staff.nextPromotion;

  const sections = [
    {
      title: "A. PERSONAL INFORMATION",
      fields: [
        ["Oracle ID", staff.oracleID],
        ["Full Name", staff.fullName],
        ["Date of Birth", staff.dateOfBirth],
        ["Gender", staff.gender],
        ["State of Origin", staff.stateOrigin],
        ["Phone Number", staff.phoneNumber],
        ["Email Address", staff.emailAddress]
      ]
    },
    {
  title: "B. EMPLOYMENT AND APPOINTMENT INFORMATION",
  fields: [
    ["Commission File Number", staff.staffNumber],
    ["Employment Status", staff.employmentStatus],
    ["Post of First Appointment", staff.firstPost],
    ["Date of First Appointment", staff.firstAppointment],
    ["Date of Confirmation", staff.confirmationDate],
    ["Present Post / Designation", staff.designation],
    ["Cadre", staff.cadre],
    ["Grade Level", staff.gradeLevel],
    ["Date of Appointment at Present Grade Level", staff.presentGradeDate],
    ["HR-Verified Present Grade Date", staff.hrVerifiedPresentGradeDate],
["HR Verification Remarks", staff.hrVerificationRemarks],
    ["Appointment Verification Status", staff.appointmentVerificationStatus],
["Appointment Validation Message", staff.appointmentVerificationMessage],
    ["Educational Qualification", staff.qualification],
    ["Professional Qualification", staff.professionalQualification]
  ]
},
    {
      title: "C. DEPLOYMENT INFORMATION",
      fields: [
        ["Present LGA / LCDA", staff.presentLGA],
        ["Date Deployed to Present LGA / LCDA", staff.deploymentDate]
      ]
    },
    {
  title: "D. PROMOTION AND RETIREMENT INFORMATION",
  fields: [
    ["Expected Next Promotion Date", nextPromotionDisplay],
    ["Expected Retirement Date", staff.expectedRetirement]
  ]
}
  ];
  const details = document.getElementById("staffDetails");
  details.replaceChildren();

  sections.forEach(function(section) {

    const heading = document.createElement("h4");
    heading.textContent = section.title;
    heading.style.color = "#12345a";
    heading.style.marginTop = "25px";

    details.appendChild(heading);

    const table = document.createElement("table");
    table.className = "staff-table";

    section.fields.forEach(function(field) {

      const row = table.insertRow();
      const labelCell = row.insertCell();

      labelCell.textContent = field[0];

      const valueCell = row.insertCell();

      valueCell.textContent =
        field[1] !== undefined &&
        field[1] !== null &&
        field[1] !== ""
          ? field[1]
          : "Not available";

    });

    details.appendChild(table);

  });

// HR VERIFICATION INTERFACE – HR OFFICERS ONLY
if (
  currentUserRole === "HR OFFICER" ||
  currentUserRole === "MANAGEMENT"
) {

  const panel = document.createElement("div");
  panel.style.marginTop = "25px";
  panel.style.padding = "15px";
  panel.style.border = "1px solid #ccc";
  panel.style.borderRadius = "8px";

  const heading = document.createElement("h4");
  heading.textContent = "HR VERIFICATION OF PRESENT GRADE DATE";
  heading.style.color = "#12345a";
  panel.appendChild(heading);

  const originalLabel = document.createElement("label");
  originalLabel.textContent =
    "Original Present Grade Appointment Date";
  panel.appendChild(originalLabel);

  const originalDate = document.createElement("input");
  originalDate.type = "text";
  originalDate.readOnly = true;
  originalDate.value = staff.presentGradeDate || "Not available";
  originalDate.style.width = "100%";
  originalDate.style.marginBottom = "12px";
  panel.appendChild(originalDate);

  const verifiedLabel = document.createElement("label");
  verifiedLabel.textContent = "HR-Verified Appointment Date";
  panel.appendChild(verifiedLabel);

  const verifiedDate = document.createElement("input");
  verifiedDate.type = "date";
  verifiedDate.value = convertHRDateToISO(
    staff.hrVerifiedPresentGradeDate
  );
  verifiedDate.style.width = "100%";
  verifiedDate.style.marginBottom = "12px";
  panel.appendChild(verifiedDate);

  const remarksLabel = document.createElement("label");
  remarksLabel.textContent = "HR Verification Remarks";
  panel.appendChild(remarksLabel);

  const remarks = document.createElement("textarea");
  remarks.value = staff.hrVerificationRemarks || "";
  remarks.rows = 3;
  remarks.style.width = "100%";
  remarks.style.marginBottom = "12px";
  panel.appendChild(remarks);

  const saveButton = document.createElement("button");
  saveButton.type = "button";
  saveButton.textContent = "Save HR Verification";
  panel.appendChild(saveButton);

  const message = document.createElement("div");
  message.style.marginTop = "10px";
  message.setAttribute("role", "status");
  message.setAttribute("aria-live", "polite");
  panel.appendChild(message);

  saveButton.addEventListener("click", async function() {

    if (!verifiedDate.value) {
      message.textContent =
        "Please enter the HR-verified appointment date.";
      return;
    }

    if (!auth.currentUser) {
      message.textContent = "Please sign in again.";
      return;
    }

    saveButton.disabled = true;
    saveButton.textContent = "Saving...";

    try {
      const idToken = await auth.currentUser.getIdToken();

      google.script.run
       
.withSuccessHandler(function(response) {

  const dateParts = verifiedDate.value.split("-");
  const monthNames = [
    "January", "February", "March", "April",
    "May", "June", "July", "August",
    "September", "October", "November", "December"
  ];

  staff.hrVerifiedPresentGradeDate =
    Number(dateParts[2]) + " " +
    monthNames[Number(dateParts[1]) - 1] + " " +
    dateParts[0];

  staff.hrVerificationRemarks = remarks.value.trim();

  displayStaffRecord(staff);

  statusMessage.textContent =
    response.message || "HR verification saved successfully.";

})

        .withFailureHandler(function(error) {
          message.textContent =
            "Verification failed: " + error.message;

          saveButton.disabled = false;
          saveButton.textContent = "Save HR Verification";
        })
        .saveHRVerifiedAppointmentDate(
          staff.oracleID,
          verifiedDate.value,
          remarks.value.trim(),
          idToken
        );

    } catch (error) {
      message.textContent =
        "Authentication error: " + error.message;

      saveButton.disabled = false;
      saveButton.textContent = "Save HR Verification";
    }
  });

  details.appendChild(panel);
}
// CMD STAFF DIRECT EDIT PANEL
if (currentUserRole === "CMD STAFF") {

  const panel = document.createElement("div");
  panel.style.marginTop = "25px";
  panel.style.padding = "15px";
  panel.style.border = "1px solid #ccc";
  panel.style.borderRadius = "8px";

  const heading = document.createElement("h4");
  heading.textContent = "CMD STAFF — EDIT STAFF RECORD";
  heading.style.color = "#12345a";
  panel.appendChild(heading);

  const fields = [
    ["fullName", "fullName", "Full Name"],
    ["staffNumber", "staffNumber", "Commission File Number"],
    ["dob", "dateOfBirth", "Date of Birth", "date"],
    ["firstPost", "firstPost", "Post of First Appointment"],
    ["firstAppointment", "firstAppointment", "Date of First Appointment", "date"],
    ["confirmationDate", "confirmationDate", "Date of Confirmation", "date"],
    ["presentGradeDate", "presentGradeDate", "Present Grade Appointment Date", "date"],
    ["deploymentDate", "deploymentDate", "Date Deployed to Present Council", "date"],
    ["professionalQualification", "professionalQualification", "Professional Qualification"],
    ["phoneNumber", "phoneNumber", "Phone Number"],
    ["emailAddress", "emailAddress", "Email Address"],
    ["designation", "designation", "Present Post / Designation"],
    ["cadre", "cadre", "Cadre"],
    ["stateOrigin", "stateOrigin", "State of Origin"],
    ["gradeLevel", "gradeLevel", "Grade Level"],
    ["presentLGA", "presentLGA", "Present LGA / LCDA"],
    ["employmentStatus", "employmentStatus", "Employment Status"],
    ["gender", "gender", "Gender"],
    ["qualification", "qualification", "Educational Qualification"]
  ];

  const inputs = {};

  fields.forEach(function(field) {

    const label = document.createElement("label");
    label.textContent = field[2];
    label.style.display = "block";
    label.style.marginTop = "10px";
    panel.appendChild(label);

    const input = document.createElement("input");
    input.type = field[3] || "text";
    input.style.width = "100%";
    input.style.boxSizing = "border-box";
    input.style.padding = "8px";
    input.style.marginBottom = "8px";

    if (field[3] === "date") {
      input.value = convertHRDateToISO(staff[field[1]]);
    } else {
      input.value = staff[field[1]] || "";
    }

    inputs[field[0]] = input;
    panel.appendChild(input);
  });

  const saveButton = document.createElement("button");
  saveButton.type = "button";
  saveButton.textContent = "Save Staff Record";
  saveButton.style.marginTop = "15px";
  panel.appendChild(saveButton);

  const message = document.createElement("div");
  message.style.marginTop = "10px";
  message.setAttribute("role", "status");
  panel.appendChild(message);

  saveButton.addEventListener("click", async function() {

    if (!auth.currentUser) {
      message.textContent = "Please sign in again.";
      return;
    }

    const data = {};

    fields.forEach(function(field) {
      data[field[0]] = inputs[field[0]].value.trim();
    });

    saveButton.disabled = true;
    saveButton.textContent = "Saving...";

    try {
      const idToken = await auth.currentUser.getIdToken();

      google.script.run
        .withSuccessHandler(function(response) {

          fields.forEach(function(field) {
            staff[field[1]] = data[field[0]];
          });

          displayStaffRecord(staff);

          statusMessage.textContent =
            response.message || "Staff record updated successfully.";

        })
        .withFailureHandler(function(error) {

          message.textContent =
            "Save failed: " + error.message;

          saveButton.disabled = false;
          saveButton.textContent = "Save Staff Record";

        })
        .updateStaffRecordByCMD(
          staff.oracleID,
          data,
          idToken
        );

    } catch (error) {

      message.textContent =
        "Authentication error: " + error.message;

      saveButton.disabled = false;
      saveButton.textContent = "Save Staff Record";
    }
  });

  details.appendChild(panel);
}

  resultArea.style.display = "block";
}
// STAFF SEARCH ELEMENT REFERENCES

const searchButton = document.getElementById("searchButton");
const oracleInput = document.getElementById("oracleID");
const statusMessage = document.getElementById("statusMessage");
const resultArea = document.getElementById("resultArea");
// STAFF RECORD SEARCH FUNCTION

async function searchStaff() {

  const oracleID = oracleInput.value.trim();

  if (!oracleID) {
    statusMessage.textContent = "Please enter a Staff Oracle ID.";
    return;
  }

  if (!auth.currentUser) {
    statusMessage.textContent = "Please sign in to continue.";
    return;
  }

  searchButton.disabled = true;
  searchButton.textContent = "Searching...";

  statusMessage.textContent = "";
  resultArea.style.display = "none";

  try {

    const idToken = await auth.currentUser.getIdToken();

    google.script.run

      .withSuccessHandler(function(response) {

        searchButton.disabled = false;
        searchButton.textContent = "Search Staff Record";

        if (!response || !response.found) {
          statusMessage.textContent = response
            ? response.message
            : "No response received from the server.";
          return;
        }

        displayStaffRecord(response.staffRecord);

        statusMessage.textContent =
          "Staff record retrieved successfully.";

      })

      .withFailureHandler(function(error) {

        searchButton.disabled = false;
        searchButton.textContent = "Search Staff Record";

        statusMessage.textContent =
          "Search failed: " + error.message;

      })

      .searchStaffByOracleID(oracleID, idToken);

  } catch (error) {

    searchButton.disabled = false;
    searchButton.textContent = "Search Staff Record";

    statusMessage.textContent =
      "Authentication error: " + error.message;

  }

}
  function clearSearch() {

    oracleInput.value = "";

    resultArea.style.display = "none";

    statusMessage.textContent = "";

    oracleInput.focus();

  }


  searchButton.addEventListener("click", searchStaff);

  oracleInput.addEventListener("keydown", function(event) {

    if (event.key === "Enter") {
      searchStaff();
    }

  });

  document.getElementById("clearButton")
    .addEventListener("click", clearSearch);


// ICT ADMINISTRATOR – GET / GENERATE STAFF EDITING LINK

const editingLinkButton = document.getElementById(
  "getStaffEditingLinkButton"
);

const editingLinkResult = document.getElementById(
  "staffEditingLinkResult"
);

async function getStaffEditingLink() {

  if (currentUserRole !== "ICT ADMINISTRATOR") {
  editingLinkResult.textContent = "Access denied.";
  return;
}

  const oracleID = oracleInput.value.trim();

  if (!oracleID) {
    editingLinkResult.textContent =
      "Please enter the Staff Oracle ID.";
    return;
  }

  if (!auth.currentUser) {
    editingLinkResult.textContent =
      "Please sign in to continue.";
    return;
  }

  editingLinkButton.disabled = true;
  editingLinkButton.textContent = "Processing...";
  editingLinkResult.textContent =
    "Retrieving staff editing link...";

  try {

    const idToken = await auth.currentUser.getIdToken();

    google.script.run

      .withSuccessHandler(function(response) {

        editingLinkButton.disabled = false;
        editingLinkButton.textContent =
          "Get / Generate Staff Editing Link";

        if (!response || !response.success) {
          editingLinkResult.textContent =
            "Unable to retrieve the editing link.";
          return;
        }

        editingLinkResult.replaceChildren();

        const heading = document.createElement("p");
        heading.textContent =
          response.generated
            ? "A new editing link has been generated."
            : "Existing staff editing link retrieved.";

        const staffInfo = document.createElement("p");
        staffInfo.textContent =
          "Staff: " + response.fullName +
          " | Oracle ID: " + response.oracleID;

        const link = document.createElement("a");
        link.href = response.editUrl;
        link.textContent = "Open Staff Editing Form";
        link.target = "_blank";
        link.rel = "noopener noreferrer";
        link.style.display = "block";
        link.style.margin = "12px 0";

        const copyButton = document.createElement("button");
        copyButton.type = "button";
        copyButton.textContent = "Copy Editing Link";

        copyButton.addEventListener("click", async function() {

          try {

            await navigator.clipboard.writeText(response.editUrl);
            copyButton.textContent = "Link Copied Successfully";

          } catch (error) {

            const temporaryInput =
              document.createElement("textarea");

            temporaryInput.value = response.editUrl;
            document.body.appendChild(temporaryInput);
            temporaryInput.select();

            const copied = document.execCommand("copy");

            temporaryInput.remove();

            copyButton.textContent = copied
              ? "Link Copied Successfully"
              : "Copy failed. Please copy the link manually.";

          }

        });

        editingLinkResult.appendChild(heading);
        editingLinkResult.appendChild(staffInfo);
        editingLinkResult.appendChild(link);
        editingLinkResult.appendChild(copyButton);

      })

      .withFailureHandler(function(error) {

        editingLinkButton.disabled = false;
        editingLinkButton.textContent =
          "Get / Generate Staff Editing Link";

        editingLinkResult.textContent =
          "Error: " + error.message;

      })

      .getOrCreateStaffEditingLink(oracleID, idToken);

  } catch (error) {

    editingLinkButton.disabled = false;
    editingLinkButton.textContent =
      "Get / Generate Staff Editing Link";

    editingLinkResult.textContent =
      "Authentication error: " + error.message;

  }

}

editingLinkButton.addEventListener(
  "click",
  getStaffEditingLink
);

  // REPORT GENERATION MODULE
  let latestPortalReport = null;

  async function generatePortalReport() {
    const status = document.getElementById("reportStatus");
    const button = document.getElementById("generateReportButton");
    const reportType = document.getElementById("reportType").value;

    if (!auth.currentUser) {
      status.textContent = "Please sign in to continue.";
      return;
    }

    button.disabled = true;
    button.textContent = "Generating...";
    status.textContent = "Retrieving authorised report data...";
    document.getElementById("reportOutput").replaceChildren();
    document.getElementById("reportSummary").textContent = "";
    document.getElementById("exportReportButton").style.display = "none";
    document.getElementById("printReportButton").style.display = "none";
    latestPortalReport = null;

    try {
      const idToken = await auth.currentUser.getIdToken();

      google.script.run
        .withSuccessHandler(function(report) {
          button.disabled = false;
          button.textContent = "Generate Report";

          if (!report || !report.headers || !report.rows) {
            status.textContent = "The server returned an incomplete report.";
            return;
          }

          latestPortalReport = report;
          renderPortalReport(report);
          status.textContent = "Report generated successfully.";
          document.getElementById("reportSummary").textContent =
            report.title + " | Records: " + report.total +
            " | Generated: " + report.generatedAt;

          document.getElementById("exportReportButton").style.display =
            "inline-block";
          document.getElementById("printReportButton").style.display =
            "inline-block";
        })
        .withFailureHandler(function(error) {
          button.disabled = false;
          button.textContent = "Generate Report";
          status.textContent = "Report generation failed: " + error.message;
        })
        .getPortalReport(reportType, idToken);

    } catch (error) {
      button.disabled = false;
      button.textContent = "Generate Report";
      status.textContent = "Authentication error: " + error.message;
    }
  }

  function renderPortalReport(report) {
    const output = document.getElementById("reportOutput");
    output.replaceChildren();

    const table = document.createElement("table");
    table.className = "staff-table";

    const thead = table.createTHead();
    const headerRow = thead.insertRow();
    report.headers.forEach(function(header) {
      const cell = document.createElement("th");
      cell.textContent = header;
      cell.style.cssText =
        "padding:10px;border:1px solid #dce3eb;background:#062c80;color:white;text-align:left;";
      headerRow.appendChild(cell);
    });

    const tbody = table.createTBody();
    report.rows.forEach(function(values) {
      const row = tbody.insertRow();
      values.forEach(function(value) {
        const cell = row.insertCell();
        cell.textContent = value === null || value === undefined ? "" : value;
        cell.style.cssText =
          "padding:9px;border:1px solid #dce3eb;text-align:left;font-size:13px;";
      });
    });

    if (report.rows.length === 0) {
      const row = tbody.insertRow();
      const cell = row.insertCell();
      cell.colSpan = report.headers.length;
      cell.textContent = "No records are available for this report.";
      cell.style.padding = "12px";
    }

    output.appendChild(table);
  }

  function exportPortalReport() {
    if (!latestPortalReport) return;

    const allRows = [latestPortalReport.headers].concat(latestPortalReport.rows);
    const csv = allRows.map(function(row) {
      return row.map(function(value) {
        const text = String(value === null || value === undefined ? "" : value);
        return '"' + text.replace(/"/g, '""') + '"';
      }).join(",");
    }).join("\r\n");

    const blob = new Blob(["\uFEFF" + csv], {
      type: "text/csv;charset=utf-8;"
    });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = latestPortalReport.fileName || "CMD_HR57_Report.csv";
    document.body.appendChild(link);
    link.click();
    link.remove();
    URL.revokeObjectURL(url);
  }

  function printPortalReport() {
    if (!latestPortalReport) return;

    const printWindow = window.open("", "_blank");
    if (!printWindow) {
      document.getElementById("reportStatus").textContent =
        "Please allow pop-ups for this portal, then try Print / Save as PDF again.";
      return;
    }

    const escapeHtml = function(value) {
      return String(value === null || value === undefined ? "" : value)
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");
    };

    const headerHtml = latestPortalReport.headers.map(function(value) {
      return "<th>" + escapeHtml(value) + "</th>";
    }).join("");

    const rowsHtml = latestPortalReport.rows.map(function(row) {
      return "<tr>" + row.map(function(value) {
        return "<td>" + escapeHtml(value) + "</td>";
      }).join("") + "</tr>";
    }).join("");

    printWindow.document.write(
      "<!DOCTYPE html><html><head><title>" +
      escapeHtml(latestPortalReport.title) +
      "</title><style>" +
      "body{font-family:Arial,sans-serif;padding:20px;color:#142b50}" +
      "h2{text-align:center;color:#062c80}" +
      "p{text-align:center;font-size:12px}" +
      "table{width:100%;border-collapse:collapse;margin-top:18px}" +
      "th,td{border:1px solid #777;padding:7px;text-align:left;font-size:10px}" +
      "th{background:#062c80;color:white}" +
      "@media print{button{display:none}body{padding:0}}" +
      "</style></head><body><h2>" +
      escapeHtml(latestPortalReport.title) +
      "</h2><p>Lagos State Local Government Service Commission<br>" +
      "CMD/HR57 CONNECT PORTAL | Generated: " +
      escapeHtml(latestPortalReport.generatedAt) +
      " | Records: " + escapeHtml(latestPortalReport.total) +
      "</p><table><thead><tr>" + headerHtml +
      "</tr></thead><tbody>" + rowsHtml +
      "</tbody></table><script>window.onload=function(){window.print();};<\/script>" +
      "</body></html>"
    );
    printWindow.document.close();
  }


  // CONNECT PORTAL NAVIGATION BUTTONS

  document.getElementById("dashboardButton")
    .addEventListener("click", showDashboard);

  document.getElementById("staffSearchButton")
    .addEventListener("click", showStaffSearch);

  document.getElementById("refreshDashboardButton")
    .addEventListener("click", loadManagementDashboard);

  document.getElementById("reportsButton")
    .addEventListener("click", showReports);

  document.getElementById("nominalRollButton")
    .addEventListener("click", showNominalRoll);

  document.getElementById("generateNominalRollButton")
    .addEventListener("click", generateNominalRollDownloads);

  document.getElementById("generateReportButton")
    .addEventListener("click", generatePortalReport);

  document.getElementById("exportReportButton")
    .addEventListener("click", exportPortalReport);

  document.getElementById("printReportButton")
    .addEventListener("click", printPortalReport);


  // LOAD USER ROLE WHEN PORTAL OPENS



  // SECURE INVITATION REGISTRATION AND PASSWORD MANAGEMENT

  async function loadInvitationDetails() {
    if (!invitationToken) return;
    document.getElementById("loginSection").style.display = "none";
    document.getElementById("invitationRegistrationSection").style.display = "block";
    const info = document.getElementById("invitationInfo");
    info.textContent = "Validating your invitation...";
    google.script.run
      .withSuccessHandler(function(result) {
        if (!result || !result.valid) {
          info.textContent = "This invitation is invalid, expired or has already been used. Please contact the ICT Administrator.";
          document.getElementById("registerInvitationButton").disabled = true;
          return;
        }
        info.textContent = "Invitation verified for: " + result.email + ". Create your own password below.";
      })
      .withFailureHandler(function(error) {
        info.textContent = "Unable to validate invitation: " + error.message;
        document.getElementById("registerInvitationButton").disabled = true;
      })
      .getInvitationDetails(invitationToken);
  }

  
document.getElementById("registerInvitationButton").addEventListener("click", async function() {
  const password = document.getElementById("invitePassword").value;
  const confirm = document.getElementById("invitePasswordConfirm").value;
  const message = document.getElementById("invitationMessage");
  const button = document.getElementById("registerInvitationButton");
  let invitation = null;

  if (!invitationToken) {
    message.textContent = "The invitation link is missing.";
    return;
  }
  if (password.length < 8) {
    message.textContent = "Please use a password with at least 8 characters.";
    return;
  }
  if (password !== confirm) {
    message.textContent = "The passwords do not match.";
    return;
  }

  button.disabled = true;
  button.textContent = "Creating account...";
  message.textContent = "";
  invitationRegistrationInProgress = true;

  try {
    invitation = await new Promise(function(resolve, reject) {
      google.script.run
        .withSuccessHandler(resolve)
        .withFailureHandler(reject)
        .getInvitationDetails(invitationToken);
    });

    if (!invitation || !invitation.valid) {
      throw new Error("This invitation is no longer valid.");
    }

    const credential = await auth.createUserWithEmailAndPassword(
      invitation.email, password
    );

    await credential.user.sendEmailVerification();
    await auth.signOut();

    document.getElementById("invitationRegistrationSection").style.display = "none";
    document.getElementById("loginSection").style.display = "block";
    document.getElementById("loginMessage").textContent =
      "Account created. A verification email has been sent to " +
      invitation.email +
      ". Verify your email, then sign in here to activate your portal access.";

  } catch (error) {
    if (error.code === "auth/email-already-in-use") {
      document.getElementById("invitationRegistrationSection").style.display = "none";
      document.getElementById("loginSection").style.display = "block";

      if (invitation && invitation.email) {
        document.getElementById("loginEmail").value = invitation.email;
      }

      document.getElementById("loginMessage").textContent =
        "This email already has a portal account. Please sign in using your existing password or use Forgot Password.";
    } else {
      message.textContent = "Account creation failed: " + error.message;
    }

  } finally {
    invitationRegistrationInProgress = false;
    button.disabled = false;
    button.textContent = "Create Account";
  }
});

  document.getElementById("showInvitationLoginButton").addEventListener("click", function() {
    document.getElementById("invitationRegistrationSection").style.display = "none";
    document.getElementById("loginSection").style.display = "block";
  });

  document.getElementById("changePortalPasswordButton").addEventListener("click", async function() {
    const password = document.getElementById("newPortalPassword").value;
    const confirm = document.getElementById("confirmPortalPassword").value;
    const message = document.getElementById("passwordChangeMessage");
    if (!auth.currentUser) {
      message.textContent = "Please sign in again.";
      return;
    }
    if (password.length < 8) {
      message.textContent = "Use a password with at least 8 characters.";
      return;
    }
    if (password !== confirm) {
      message.textContent = "The passwords do not match.";
      return;
    }
    try {
      await auth.currentUser.updatePassword(password);
      document.getElementById("newPortalPassword").value = "";
      document.getElementById("confirmPortalPassword").value = "";
      message.textContent = "Your password has been updated successfully.";
    } catch (error) {
      message.textContent = error.code === "auth/requires-recent-login"
        ? "For security, sign out and sign in again before changing your password."
        : "Unable to update password: " + error.message;
    }
  });

  document.getElementById("forgotPasswordButton").addEventListener("click", async function() {
    const email = document.getElementById("loginEmail").value.trim();
    const message = document.getElementById("loginMessage");
    if (!email) {
      message.textContent = "Enter your registered email address first.";
      return;
    }
    try {
      await auth.sendPasswordResetEmail(email);
      message.textContent = "If the account exists, a password-reset email has been sent. Please check your inbox.";
    } catch (error) {
      message.textContent = "Unable to send password-reset email: " + error.message;
    }
  });

  document.getElementById("sendInvitationButton").addEventListener("click", async function() {
    const name = document.getElementById("inviteFullName").value.trim();
    const email = document.getElementById("inviteEmail").value.trim();
    const role = document.getElementById("inviteRole").value;
    const department = document.getElementById("inviteDepartment").value.trim();
    const message = document.getElementById("userManagementMessage");
    const button = document.getElementById("sendInvitationButton");

    if (!name || !email) {
      message.textContent = "Enter the user's full name and email address.";
      return;
    }
    if (role === "HR OFFICER" && !department) {
      message.textContent = "Enter the HR Officer's assigned LGA / LCDA.";
      return;
    }
    if (!auth.currentUser) {
      message.textContent = "Please sign in again.";
      return;
    }

    button.disabled = true;
    button.textContent = "Sending invitation...";
    try {
      const idToken = await auth.currentUser.getIdToken();
      google.script.run
        .withSuccessHandler(function(result) {
          message.textContent = result.message || "Invitation sent successfully.";
          document.getElementById("inviteFullName").value = "";
          document.getElementById("inviteEmail").value = "";
          document.getElementById("inviteDepartment").value = "";
          button.disabled = false;
          button.textContent = "Send Secure Invitation";
        })
        .withFailureHandler(function(error) {
          message.textContent = "Invitation failed: " + error.message;
          button.disabled = false;
          button.textContent = "Send Secure Invitation";
        })
        .createPortalInvitation(name, email, role, department, idToken);
    } catch (error) {
      message.textContent = "Authentication error: " + error.message;
      button.disabled = false;
      button.textContent = "Send Secure Invitation";
    }
  });

  
async function completeInvitationIfNeeded(firebaseUser) {
  if (!invitationToken || !firebaseUser) return false;

  await firebaseUser.reload();

  if (!firebaseUser.emailVerified) {
    document.getElementById("loginMessage").textContent =
      "Your invitation is valid, but your email is not yet verified. " +
      "Click Resend Verification Email below.";

    const resendButton = document.getElementById(
      "resendVerificationButton"
    );

    if (resendButton) {
      resendButton.style.display = "inline-block";
    }

    // Keep the user signed in so verification can be resent.
    return true;
  }

  const idToken = await firebaseUser.getIdToken(true);

  await new Promise(function(resolve, reject) {
    google.script.run
      .withSuccessHandler(resolve)
      .withFailureHandler(reject)
      .completePortalInvitation(invitationToken, idToken);
  });

  return false;
}

  if (invitationToken) loadInvitationDetails();

  console.log("HR Portal search interface loaded successfully.");






document.getElementById("resendVerificationButton")
  .addEventListener("click", async function() {

    const message = document.getElementById("loginMessage");
    const button = this;

    let user = auth.currentUser;

    button.disabled = true;
    button.textContent = "Sending...";

    try {

      if (!user) {
        const email = document.getElementById("loginEmail").value.trim();
        const password = document.getElementById("loginPassword").value;

        if (!email || !password) {
          throw new Error(
            "Please enter your registered email and password first."
          );
        }

        const credential = await auth.signInWithEmailAndPassword(
          email,
          password
        );

        user = credential.user;
      }

      await user.reload();

      if (user.emailVerified) {
        message.textContent =
          "Your email is already verified. Please sign in to continue.";
        button.style.display = "none";
        return;
      }

      await user.sendEmailVerification();

      message.textContent =
        "Verification email sent successfully to " +
        user.email +
        ". Please check your Inbox and Spam/Junk folder.";

    } catch (error) {

      console.error(
        "VERIFICATION RESEND ERROR:",
        error.code,
        error.message
      );

      message.textContent =
        "Unable to send verification email: " +
        (error.code || "") + " " + error.message;

    } finally {

      button.disabled = false;
      button.textContent = "Resend Verification Email";

    }
  });

document.getElementById("checkCmdStaffApprovalButton")
  .addEventListener("click", async function () {

    const email = document.getElementById("cmdStaffApprovalEmail")
      .value.trim();

    const status = document.getElementById("cmdStaffApprovalStatus");
    const button = document.getElementById("checkCmdStaffApprovalButton");

    if (!email) {
      status.textContent = "Enter the CMD Staff email address.";
      return;
    }

    if (!auth.currentUser) {
      status.textContent = "Please sign in again.";
      return;
    }

    button.disabled = true;
    status.textContent = "Checking approval status...";

    try {
      const idToken = await auth.currentUser.getIdToken();

      google.script.run
        .withSuccessHandler(function (result) {
          status.textContent = JSON.stringify(result, null, 2);
          button.disabled = false;
        })
        .withFailureHandler(function (error) {
          status.textContent = "Error: " + error.message;
          button.disabled = false;
        })
        .getCmdStaffApprovalStatus(email, idToken);

    } catch (error) {
      status.textContent = "Error: " + error.message;
      button.disabled = false;
    }
  });
  // CMD STAFF APPROVAL BUTTON ACTIONS

function performCmdStaffApproval(approve, approvalType, buttonId) {

  const email = document
    .getElementById("cmdStaffApprovalEmail")
    .value.trim();

  const status = document.getElementById("cmdStaffApprovalStatus");
  const button = document.getElementById(buttonId);

  if (!email) {
    status.textContent = "Please enter the CMD STAFF official email address.";
    return;
  }

  if (!auth.currentUser) {
    status.textContent = "Please sign in again.";
    return;
  }

  button.disabled = true;
  status.textContent = "Processing approval...";

  auth.currentUser.getIdToken()
    .then(function(idToken) {

      google.script.run
        .withSuccessHandler(function(result) {

          status.textContent =
            typeof result === "string"
              ? result
              : JSON.stringify(result);

          button.disabled = false;

        })
        .withFailureHandler(function(error) {

          status.textContent =
            "Approval failed: " + error.message;

          button.disabled = false;

        })
        .setCmdStaffApproval(
          email,
          approve,
          approvalType,
          idToken
        );

    })
    .catch(function(error) {

      status.textContent =
        "Authentication error: " + error.message;

      button.disabled = false;

    });
}


// MANAGEMENT APPROVAL

document
  .getElementById("managementApproveCmdStaffButton")
  .addEventListener("click", function() {

    performCmdStaffApproval(
      true,
      "MANAGEMENT",
      "managementApproveCmdStaffButton"
    );

  });


document
  .getElementById("managementRevokeCmdStaffButton")
  .addEventListener("click", function() {

    performCmdStaffApproval(
      false,
      "MANAGEMENT",
      "managementRevokeCmdStaffButton"
    );

  });


// ICT ADMINISTRATOR APPROVAL

document
  .getElementById("ictApproveCmdStaffButton")
  .addEventListener("click", function() {

    performCmdStaffApproval(
      true,
      "ICT",
      "ictApproveCmdStaffButton"
    );

  });


document
  .getElementById("ictRevokeCmdStaffButton")
  .addEventListener("click", function() {

    performCmdStaffApproval(
      false,
      "ICT",
      "ictRevokeCmdStaffButton"
    );

  });
  // GRANT TEMPORARY CMD STAFF EDIT ACCESS

document
  .getElementById("grantCmdStaffEditAccessButton")
  .addEventListener("click", async function() {

    const email = document
      .getElementById("cmdStaffApprovalEmail")
      .value.trim();

    const status = document.getElementById("cmdStaffApprovalStatus");
    const button = this;

    if (!email) {
      status.textContent = "Enter the CMD STAFF official email address.";
      return;
    }

    if (!auth.currentUser) {
      status.textContent = "Please sign in again.";
      return;
    }

    button.disabled = true;
    status.textContent = "Granting temporary editing access...";

    try {
      const idToken = await auth.currentUser.getIdToken();

      google.script.run
        .withSuccessHandler(function(result) {
          status.textContent = result.message;
          button.disabled = false;
        })
        .withFailureHandler(function(error) {
          status.textContent =
            "Grant failed: " + error.message;
          button.disabled = false;
        })
        .grantCmdStaffEditAccess(email, idToken);

    } catch (error) {
      status.textContent =
        "Authentication error: " + error.message;
      button.disabled = false;
    }
  });
</script>

</body>
</html>