/* 
=========================================
  CENTURIA SCHOOL & COLLEGE SYSTEM
  Main Frontend Driver Scripts (Portals Integrated)
=========================================
*/

document.addEventListener("DOMContentLoaded", () => {
  // 1. Sticky Navbar Scrolling Class
  const navbar = document.querySelector(".premium-navbar");
  if (navbar) {
    window.addEventListener("scroll", () => {
      if (window.scrollY > 50) {
        navbar.classList.add("scrolled");
      } else {
        navbar.classList.remove("scrolled");
      }
    });
  }

  // 2. Load Notices Dynamically (Marquee Feeder)
  const fetchNotices = async () => {
    const marqueeContainer = document.querySelector(".ticker-marquee-inner");
    if (!marqueeContainer) return;
    
    try {
      const response = await fetch("/api/notices");
      if (response.ok) {
        const notices = await response.json();
        if (notices.length > 0) {
          marqueeContainer.innerHTML = notices.map(notice => `
            <span class="ticker-item">
              📢 <strong>${notice.title}</strong> (${notice.date}): <span class="font-medium">${notice.content.substring(0, 150)}...</span>
            </span>
          `).join("");
        }
      }
    } catch (e) {
      console.warn("Dynamic notice sync failed.", e);
    }
  };
  fetchNotices();

  // 3. Online Admissions AJAX Form Handler
  const admissionsForm = document.getElementById("admissionsForm");
  const admissionsCardBody = document.getElementById("admissionsCardBody");

  if (admissionsForm && admissionsCardBody) {
    admissionsForm.addEventListener("submit", async (e) => {
      e.preventDefault();

      const studentName = document.getElementById("admStudentName").value.trim();
      const fatherName = document.getElementById("admFatherName").value.trim();
      const dateOfBirth = document.getElementById("admDob").value;
      const gender = document.getElementById("admGender").value;
      const classRequested = document.getElementById("admClass").value;
      const parentPhone = document.getElementById("admPhone").value.trim();
      const parentEmail = document.getElementById("admEmail").value.trim();
      const address = document.getElementById("admAddress").value.trim();
      const previousSchool = document.getElementById("admPrevSchool").value.trim();

      const submitBtn = admissionsForm.querySelector("button[type='submit']");
      const originalBtnText = submitBtn.innerHTML;
      submitBtn.disabled = true;
      submitBtn.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Submitting Application...`;

      try {
        const response = await fetch("/api/admissions/apply", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            studentName,
            fatherName,
            dateOfBirth,
            gender,
            classRequested,
            parentPhone,
            parentEmail,
            address,
            previousSchool
          })
        });

        const result = await response.json();

        if (response.ok) {
          admissionsCardBody.innerHTML = `
            <div class="success-card">
              <div class="success-icon">
                <i class="bi bi-check-lg"></i>
              </div>
              <h3 class="font-bold text-slate-800 text-xl uppercase">Application Logged!</h3>
              <p class="text-sm text-slate-500 max-w-md mx-auto my-3 leading-relaxed">
                Thank you for applying to Centuria. The application for <strong>${studentName}</strong> has been received successfully with reference code:
              </p>
              <div class="my-4">
                <span class="bg-amber-100 text-amber-800 border border-amber-200 font-mono font-bold px-4 py-2 rounded-xl text-lg tracking-wide">
                  ${result.registrationNumber || "CSCS-2026-REF"}
                </span>
              </div>
              <p class="text-xs text-slate-400 mt-2">
                A registrar will call your hotline <strong>${parentPhone}</strong> within 24 hours.
              </p>
              <button onclick="window.location.reload()" class="btn btn-gold mt-4">Submit Another Entry</button>
            </div>
          `;
        } else {
          alert(result.error || "Submission failed. Please check parameters.");
        }
      } catch (err) {
        console.error("Admissions error:", err);
        alert("Server communication failure. Please verify server status.");
      } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalBtnText;
      }
    });
  }

  // 4. Contact / Inquiries AJAX Form Handler
  const contactForm = document.getElementById("contactForm");
  const contactCardBody = document.getElementById("contactCardBody");

  if (contactForm && contactCardBody) {
    contactForm.addEventListener("submit", async (e) => {
      e.preventDefault();

      const name = document.getElementById("conName").value.trim();
      const email = document.getElementById("conEmail").value.trim();
      const phone = document.getElementById("conPhone").value.trim();
      const subject = document.getElementById("conSubject").value.trim();
      const message = document.getElementById("conMessage").value.trim();

      const submitBtn = contactForm.querySelector("button[type='submit']");
      const originalBtnText = submitBtn.innerHTML;
      submitBtn.disabled = true;
      submitBtn.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Sending Message...`;

      try {
        const response = await fetch("/api/contact", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ name, email, phone, subject, message })
        });

        const result = await response.json();

        if (response.ok) {
          contactCardBody.innerHTML = `
            <div class="success-card">
              <div class="success-icon">
                <i class="bi bi-envelope-check"></i>
              </div>
              <h3 class="font-bold text-slate-800 text-xl uppercase">Inquiry Delivered!</h3>
              <p class="text-sm text-slate-500 max-w-md mx-auto my-3 leading-relaxed">
                Dear <strong>${name}</strong>, your inquiry has been successfully cataloged. Our administrative team will reach out shortly.
              </p>
              <button onclick="window.location.reload()" class="btn btn-gold mt-4">Send New Message</button>
            </div>
          `;
        } else {
          alert(result.error || "Inquiry submission failed.");
        }
      } catch (err) {
        console.error("Contact error:", err);
        alert("Server communication failure.");
      } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalBtnText;
      }
    });
  }

  // ==========================================
  // 5. Portals Auth & Dashboard Orchestration
  // ==========================================
  const portalLoginForm = document.getElementById("portalLoginForm");
  const portalsAuthCard = document.getElementById("portalsAuthCard");
  const portalDashboardHub = document.getElementById("portalDashboardHub");
  
  // Dashboards Views
  const studentDashboardView = document.getElementById("studentDashboardView");
  const teacherDashboardView = document.getElementById("teacherDashboardView");
  const adminDashboardView = document.getElementById("adminDashboardView");

  if (portalLoginForm) {
    portalLoginForm.addEventListener("submit", async (e) => {
      e.preventDefault();

      const usernameInput = document.getElementById("portalUsername");
      const passwordInput = document.getElementById("portalPassword");
      const submitBtn = portalLoginForm.querySelector("button[type='submit']");
      
      const username = usernameInput.value.trim();
      const password = passwordInput.value;

      const originalBtnText = submitBtn.innerHTML;
      submitBtn.disabled = true;
      submitBtn.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Authenticating Credentials...`;

      try {
        const response = await fetch("/api/auth/login", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ username, password })
        });

        const result = await response.json();

        if (response.ok) {
          // Hide login card, show dashboard wrapper
          portalsAuthCard.classList.add("d-none");
          portalDashboardHub.classList.remove("d-none");
          
          // Clear credentials
          usernameInput.value = "";
          passwordInput.value = "";

          // Render corresponding portal dashboard
          if (result.role === "student") {
            renderStudentDashboard(result.user);
          } else if (result.role === "teacher") {
            renderTeacherDashboard(result.user);
          } else if (result.role === "admin") {
            renderAdminDashboard(result.user);
          }
        } else {
          alert(result.error || "Authentication failed. Invalid coordinates.");
        }
      } catch (err) {
        console.error("Auth error:", err);
        alert("Communication failure. Please verify backend status.");
      } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalBtnText;
      }
    });
  }

  // A. Render Student Dashboard View
  const renderStudentDashboard = (user) => {
    studentDashboardView.classList.remove("d-none");
    teacherDashboardView.classList.add("d-none");
    adminDashboardView.classList.add("d-none");

    // Populate profile greetings
    document.getElementById("portalNameGreeting").innerText = user.name;
    document.getElementById("portalSubDetails").innerText = `Roll Number: ${user.id} • ${user.program}`;
    document.getElementById("stdStatAttendance").innerText = user.attendance;
    document.getElementById("stdStatCgpa").innerText = user.cgpa;
    
    // Schedule Table
    const scheduleBody = document.getElementById("studentScheduleTableBody");
    scheduleBody.innerHTML = user.schedule.map(item => `
      <tr>
        <td class="font-bold text-primary-deep">${item.time}</td>
        <td><strong>${item.subject}</strong></td>
        <td>${item.instructor}</td>
        <td><span class="badge bg-slate-100 text-slate-700 font-mono">${item.room}</span></td>
      </tr>
    `).join("");

    // Assignments Table
    const assignmentsBody = document.getElementById("studentAssignmentsTableBody");
    assignmentsBody.innerHTML = user.assignments.map(item => {
      let badgeClass = "bg-warning text-dark";
      if (item.status === "Submitted") badgeClass = "bg-primary";
      if (item.status === "Graded") badgeClass = "bg-success";
      
      let urgencyBadge = "bg-secondary";
      if (item.urgency === "High") urgencyBadge = "bg-danger";
      if (item.urgency === "Medium") urgencyBadge = "bg-warning text-dark";
      
      return `
        <tr>
          <td><strong>${item.title}</strong></td>
          <td>${item.subject}</td>
          <td><span class="badge ${urgencyBadge} text-xs font-bold">${item.urgency}</span></td>
          <td class="font-mono text-xs">${item.due}</td>
          <td><span class="badge ${badgeClass} text-xs uppercase font-bold">${item.status}</span></td>
          <td class="font-bold text-center text-success">${item.grade || "—"}</td>
        </tr>
      `;
    }).join("");
  };

  // B. Render Teacher Dashboard View
  const renderTeacherDashboard = (user) => {
    studentDashboardView.classList.add("d-none");
    teacherDashboardView.classList.remove("d-none");
    adminDashboardView.classList.add("d-none");

    // Profile Greetings
    document.getElementById("portalNameGreeting").innerText = user.name;
    document.getElementById("portalSubDetails").innerText = `Instructor ID: ${user.id} • Department of ${user.dept}`;
    document.getElementById("tchrStatRoll").innerText = user.assignedRoll;
    document.getElementById("tchrStatPeriods").innerText = user.periods;
    document.getElementById("tchrStatAverage").innerText = user.average;
    document.getElementById("tchrStatTasks").innerText = user.openTasks;

    // Student Registry List
    const registerBody = document.getElementById("teacherClassRegisterBody");
    registerBody.innerHTML = user.students.map(item => {
      let submissionBadge = `<span class="badge bg-warning text-dark uppercase font-bold text-xs">Pending</span>`;
      if (item.assignment === "Submitted") submissionBadge = `<span class="badge bg-primary uppercase font-bold text-xs">Received</span>`;
      if (item.assignment === "Graded") submissionBadge = `<span class="badge bg-success uppercase font-bold text-xs">Graded</span>`;
      
      return `
        <tr>
          <td class="font-bold font-mono">${item.roll}</td>
          <td><strong>${item.name}</strong></td>
          <td class="text-center font-bold text-indigo-700">${item.attendance}</td>
          <td class="text-center font-bold text-amber-700">${item.score}</td>
          <td class="text-center font-bold text-success">${item.grade}</td>
          <td>${submissionBadge}</td>
          <td>
            <button class="btn btn-gold btn-xs py-1 px-2 text-xs" onclick="alert('Grade entry circular registered for ${item.name}!')"><i class="bi bi-pencil-square"></i> Record Marks</button>
          </td>
        </tr>
      `;
    }).join("");
  };

  // C. Render Admin Console Dashboard View
  const renderAdminDashboard = (user) => {
    studentDashboardView.classList.add("d-none");
    teacherDashboardView.classList.add("d-none");
    adminDashboardView.classList.remove("d-none");

    // Profile Greetings
    document.getElementById("portalNameGreeting").innerText = user.name;
    document.getElementById("portalSubDetails").innerText = `System Console • ${user.roleName}`;

    // Live Data Fetchers
    const loadAdmissionsGrid = async () => {
      const admissionsBody = document.getElementById("adminAdmissionsTableBody");
      if (!admissionsBody) return;
      admissionsBody.innerHTML = `<tr><td colspan="7" class="text-center py-4"><span class="spinner-border spinner-border-sm text-amber-500 me-2"></span> Loading Admissions Registry...</td></tr>`;

      try {
        const response = await fetch("/api/admissions");
        if (response.ok) {
          const admissions = await response.json();
          if (admissions.length === 0) {
            admissionsBody.innerHTML = `<tr><td colspan="7" class="text-center text-muted py-4">No admissions applications recorded in database.</td></tr>`;
            return;
          }
          admissionsBody.innerHTML = admissions.map(item => `
            <tr>
              <td class="font-bold font-mono text-amber-800 text-xs">${item.registrationNumber}</td>
              <td><strong>${item.studentName}</strong></td>
              <td>${item.fatherName}</td>
              <td><span class="badge bg-slate-100 text-slate-700">${item.classRequested}</span></td>
              <td class="font-mono text-xs">${item.parentPhone}</td>
              <td><span class="status-badge status-approved">${item.status}</span></td>
              <td><button class="btn btn-outline-dark btn-xs text-xs py-1 px-2" onclick="alert('Admissions circular updated for ${item.studentName}!')">Manage</button></td>
            </tr>
          `).join("");
        }
      } catch (err) {
        console.error("Admissions load error:", err);
        admissionsBody.innerHTML = `<tr><td colspan="7" class="text-center text-danger py-4">Failed to synchronize admissions from database.</td></tr>`;
      }
    };

    const loadParentInbox = async () => {
      const inboxBody = document.getElementById("adminInboxTableBody");
      if (!inboxBody) return;
      inboxBody.innerHTML = `<tr><td colspan="5" class="text-center py-4"><span class="spinner-border spinner-border-sm text-amber-500 me-2"></span> Synchronizing Message Stream...</td></tr>`;

      try {
        const response = await fetch("/api/contact/inquiries");
        if (response.ok) {
          const inquiries = await response.json();
          if (inquiries.length === 0) {
            inboxBody.innerHTML = `<tr><td colspan="5" class="text-center text-muted py-4">Administrative Inquiry Inbox is currently empty.</td></tr>`;
            return;
          }
          inboxBody.innerHTML = inquiries.map(item => `
            <tr>
              <td><strong>${item.name}</strong></td>
              <td class="text-xs font-mono">${item.phone}<br/>${item.email}</td>
              <td><span class="badge bg-slate-100 text-slate-800 font-bold">${item.subject}</span></td>
              <td class="text-slate-600 text-xs leading-relaxed" style="max-width: 300px;">${item.message}</td>
              <td><button class="btn btn-gold btn-xs text-xs py-1 px-2" onclick="alert('Reply circular dispatched to ${item.name}!')"><i class="bi bi-reply-fill"></i> Reply</button></td>
            </tr>
          `).join("");
        }
      } catch (err) {
        console.error("Inbox load error:", err);
        inboxBody.innerHTML = `<tr><td colspan="5" class="text-center text-danger py-4">Failed to synchronize messages from database.</td></tr>`;
      }
    };

    // Load first tabs default
    loadAdmissionsGrid();
    loadParentInbox();

    // ========================================================
    // EXPLICIT TAB SWITCHING FOR DYNAMIC ADMIN PANELS
    // ========================================================
    const adminTabsConfig = [
      { linkId: "adminTabAdmissionsLink", paneId: "adminAdmissionsTab", loader: loadAdmissionsGrid },
      { linkId: "adminTabInboxLink", paneId: "adminInboxTab", loader: loadParentInbox },
      { linkId: "adminTabNoticeFormLink", paneId: "adminNoticeTab", loader: null }
    ];

    adminTabsConfig.forEach(tab => {
      const btnLink = document.getElementById(tab.linkId);
      if (btnLink) {
        // Purge any preexisting listeners using cloning to ensure flawless callback registration
        const newBtnLink = btnLink.cloneNode(true);
        btnLink.parentNode.replaceChild(newBtnLink, btnLink);

        newBtnLink.addEventListener("click", (e) => {
          e.preventDefault();
          e.stopPropagation();

          // 1. Toggle Active Classes on Buttons
          adminTabsConfig.forEach(t => {
            const l = document.getElementById(t.linkId);
            if (l) l.classList.remove("active");
          });
          newBtnLink.classList.add("active");

          // 2. Hide All Panes and Show Selected Target
          adminTabsConfig.forEach(t => {
            const p = document.getElementById(t.paneId);
            if (p) {
              p.classList.remove("show", "active");
              p.style.display = "none";
            }
          });
          const targetPane = document.getElementById(tab.paneId);
          if (targetPane) {
            targetPane.classList.add("show", "active");
            targetPane.style.display = "block";
          }

          // 3. Load DB Content Dynamically
          if (tab.loader) {
            tab.loader();
          }
        });
      }
    });

    // Initialize default tab pane visible
    const firstPane = document.getElementById("adminAdmissionsTab");
    if (firstPane) firstPane.style.display = "block";
    const secondPane = document.getElementById("adminInboxTab");
    if (secondPane) secondPane.style.display = "none";
    const thirdPane = document.getElementById("adminNoticeTab");
    if (thirdPane) thirdPane.style.display = "none";
  };

  // D. Admin Notice Dynamic Board Publisher Form Handler
  const adminNoticeForm = document.getElementById("adminNoticeForm");
  if (adminNoticeForm) {
    adminNoticeForm.addEventListener("submit", async (e) => {
      e.preventDefault();

      const title = document.getElementById("notTitle").value.trim();
      const date = document.getElementById("notDate").value;
      const content = document.getElementById("notContent").value.trim();

      const submitBtn = adminNoticeForm.querySelector("button[type='submit']");
      const originalBtnText = submitBtn.innerHTML;
      submitBtn.disabled = true;
      submitBtn.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Publishing Notice...`;

      try {
        const response = await fetch("/api/notices/add", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ title, date, content })
        });

        const result = await response.json();

        if (response.ok) {
          alert("Dynamic Circular Notice posted successfully!");
          adminNoticeForm.reset();
          fetchNotices(); // Reload the circular notice ticker board instantly!
        } else {
          alert(result.error || "Notice posting failed.");
        }
      } catch (err) {
        console.error("Notice post error:", err);
        alert("Communication failure. Please verify server status.");
      } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalBtnText;
      }
    });
  }

  // ==========================================
  // 6. Separate Portal Switcher Gateway Action
  // ==========================================
  let currentActiveRole = "student";
  
  window.switchPortalGateway = (role) => {
    currentActiveRole = role;
    
    // Manage active state of switcher buttons
    const btnStudent = document.getElementById("btnGatewayStudent");
    const btnTeacher = document.getElementById("btnGatewayTeacher");
    const btnAdmin = document.getElementById("btnGatewayAdmin");
    
    if (btnStudent) btnStudent.classList.remove("active");
    if (btnTeacher) btnTeacher.classList.remove("active");
    if (btnAdmin) btnAdmin.classList.remove("active");
    
    const activeBtn = document.getElementById(`btnGateway${role.charAt(0).toUpperCase() + role.slice(1)}`);
    if (activeBtn) activeBtn.classList.add("active");
    
    // Auto pre-populate demo credentials circular
    const usernameInput = document.getElementById("portalUsername");
    const passwordInput = document.getElementById("portalPassword");
    
    if (usernameInput && passwordInput) {
      if (role === "student") {
        usernameInput.value = "CS-2026-101";
        passwordInput.value = "student123";
        usernameInput.placeholder = "e.g. CS-2026-101";
      } else if (role === "teacher") {
        usernameInput.value = "TR-2026-01";
        passwordInput.value = "teacher123";
        usernameInput.placeholder = "e.g. TR-2026-01";
      } else if (role === "admin") {
        usernameInput.value = "admin";
        passwordInput.value = "admin1010";
        usernameInput.placeholder = "e.g. admin";
      }
    }
    
    // Update labels and badges dynamically
    const portalsAuthCard = document.getElementById("portalsAuthCard");
    if (portalsAuthCard) {
      const badgeElement = portalsAuthCard.querySelector(".portal-header-banner .badge");
      const titleElement = portalsAuthCard.querySelector(".portal-header-banner h3");
      const descElement = portalsAuthCard.querySelector(".portal-header-banner p");
      
      if (badgeElement && titleElement && descElement) {
        if (role === "student") {
          badgeElement.className = "badge bg-warning text-dark uppercase font-bold px-3 py-1 mb-2";
          badgeElement.innerText = "Student Access Shield Active";
          titleElement.innerText = "Student Authentication Gateway";
          descElement.innerText = "Enter your reference student roll number or password coordinates";
        } else if (role === "teacher") {
          badgeElement.className = "badge bg-info text-white uppercase font-bold px-3 py-1 mb-2";
          badgeElement.innerText = "Faculty Directory Shield Active";
          titleElement.innerText = "Teacher Registry Gateway";
          descElement.innerText = "Enter your coordinator Instructor ID and institutional passphrase";
        } else if (role === "admin") {
          badgeElement.className = "badge bg-danger text-white uppercase font-bold px-3 py-1 mb-2";
          badgeElement.innerText = "System Admin Console Core Active";
          titleElement.innerText = "Administrator Access Shield";
          descElement.innerText = "Enter your administrative console passcode and system credentials";
        }
      }
    }
  };

  // Run initial prefill on load to make student portal ready
  setTimeout(() => {
    switchPortalGateway("student");
  }, 150);

  // E. Portal Sign Out Controls
  window.portalSignOut = () => {
    studentDashboardView.classList.add("d-none");
    teacherDashboardView.classList.add("d-none");
    adminDashboardView.classList.add("d-none");
    portalDashboardHub.classList.add("d-none");
    portalsAuthCard.classList.remove("d-none");
    
    // Return back to default active student role after signout
    switchPortalGateway("student");
    alert("Coordinate access portal cleared. Successfully logged out.");
  };
});
