---
import Layout from '../layouts/Layout.astro';
import '../styles/apply.scss';
---

<Layout title="Registration | UP IECEP">
  <section class="registration-section">
    <div class="form-container">
      <h1>Registration Portal</h1>
      
      <!-- LOADING SCREEN -->
      <div id="loading-status" class="status-panel">
        <div class="spinner"></div>
        <p>Checking registration status...</p>
      </div>

      <!-- CLOSED SCREEN (Hidden by default) -->
      <div id="closed-message" class="status-panel" style="display: none;">
        <h3>Registration is Currently Closed</h3>
        <p>Thank you for your interest! Please follow our social media pages for updates on our next application period.</p>
      </div>

      <!-- THE ENTIRE FORM WRAPPER (Hidden by default) -->
      <div id="registration-content" style="display: none;">
        
        <div class="description-text">
          <p>UP IECEP is an organization based in the University of the Philippines College of Engineering, catering specifically to <strong>BS Electronics Engineering students</strong>. It is a student chapter affiliated with the Institute of Electronics Engineers of the Philippines NCR North-East Chapter.</p>
          <p class="privacy-notice">In accordance with the Data Privacy Act of 2012, all information you provide will be kept confidential and used exclusively for the organization's internal purposes.</p>
        </div>

        <!-- ELIGIBILITY CHECK -->
        <div id="eligibility-section" class="eligibility-card">
          <h3>Eligibility Check</h3>
          <p>Before proceeding, please answer the following questions to confirm your eligibility:</p>
          
          <div class="radio-group">
            <p>Are you currently a BS Electronics Engineering student?</p>
            <label><input type="radio" name="isBSECE" value="yes" /> Yes</label>
            <label><input type="radio" name="isBSECE" value="no" /> No</label>
          </div>

          <div class="radio-group">
            <p>Are you graduating this semester?</p>
            <label><input type="radio" name="isGraduating" value="yes" /> Yes</label>
            <label><input type="radio" name="isGraduating" value="no" /> No</label>
          </div>

          <button type="button" id="check-eligibility-btn" class="submit-btn">Continue</button>
        </div>

        <!-- INELIGIBLE MESSAGE -->
        <div id="ineligible-message" class="hidden-message">
          <p>Unfortunately, you are ineligible to join UP IECEP.</p>
          <p>We sincerely thank you for your interest in our organization and wish you the best in your academic journey ahead.</p>
        </div>

        <!-- THE ACTUAL FORM -->
        <form id="apply-form" class="hidden-form">
          <h3>Applicant Details</h3>
          
          <div class="input-group">
            <label for="fullName">Name <span>(Format: DELA CRUZ, Juan M.)</span></label>
            <input type="text" id="fullName" name="fullName" title="Please follow the format: LASTNAME, First Name M." required placeholder="DELA CRUZ, Juan M." />
          </div>

          <div class="input-group">
            <label for="nickname">Nickname</label>
            <input type="text" id="nickname" name="nickname" title="Please enter your preferred nickname" required placeholder="Juan" />
          </div>

          <div class="input-group">
            <label for="studentNumber">Student Number <span>(Format: 20XX-XXXXX)</span></label>
            <input type="text" id="studentNumber" name="studentNumber" pattern="20[0-9]{2}-[0-9]{5}" title="Please include the dash (e.g., 2022-12345)" required placeholder="202X-XXXXX" />
            <span class="realtime-error" id="sn-error">Format must be exactly 20XX-XXXXX (Don't forget the dash!)</span>
          </div>

          <div class="input-group">
            <label for="yearStanding">Year Standing</label>
            <select id="yearStanding" name="yearStanding" title="Please select your current year standing" required>
              <option value="" disabled selected>Select your year standing</option>
              <option value="I">I</option>
              <option value="II">II</option>
              <option value="III">III</option>
              <option value="IV">IV</option>
              <option value="Other">Other</option>
            </select>
          </div>

          <div class="input-group">
            <label for="mobileNumber">Mobile Number <span>(Format: 09XXXXXXXXX)</span></label>
            <input type="tel" id="mobileNumber" name="mobileNumber" pattern="09[0-9]{9}" title="Please enter an 11-digit mobile number starting with 09" required placeholder="09XXXXXXXXX" />
            <span class="realtime-error" id="mn-error">Must be an 11-digit number starting with 09</span>
          </div>

          <div class="input-group">
            <label for="email">Email Address</label>
            <input type="email" id="email" name="email" title="Please enter a valid email address" required placeholder="jdelacruz@up.edu.ph" />
          </div>

          <div class="input-group">
            <label for="facebookLink">Facebook Profile Link <span>(Format: facebook.com/username)</span></label>
            <input type="text" id="facebookLink" name="facebookLink" title="Please provide a link to your Facebook profile" required placeholder="facebook.com/IECEPUPD" />
          </div>

          <div class="input-group">
            <label for="source">How did you learn about UP IECEP?</label>
            <select id="source" name="source" title="Please select how you found out about our organization" required>
              <option value="" disabled selected>Select an option</option>
              <option value="Family">Family</option>
              <option value="Friends">Friends</option>
              <option value="Social Media">Social Media</option>
              <option value="Other">Other</option>
            </select>
          </div>

          <div class="input-group">
            <label for="funActivities">Do you have activities in mind that would add more fun to your application process?</label>
            <textarea id="funActivities" name="funActivities" rows="4" title="We would love to hear your ideas!" placeholder="Share your ideas here!"></textarea>
          </div>

          <button type="submit" id="submit-btn" class="submit-btn">Submit Application</button>
          <p id="loading-msg" style="display:none; text-align:center; margin-top:1rem;">Sending application...</p>
        </form>
        
        <!-- SUCCESS MESSAGE -->
        <div id="success-message" class="hidden-message success">
          <h3>Application Submitted!</h3>
          <p>Thank you for applying to UP IECEP. We have received your details and will be in touch soon.</p>
        </div>

      </div> <!-- End of Registration Content Wrapper -->
    </div>
  </section>
</Layout>

<script>
  // === PASTE YOUR GOOGLE SCRIPT URL HERE ONCE ===
  const SCRIPT_URL = 'https://script.google.com/macros/s/AKfycby_xG6EGVuLXvgs9ro20rMkK2zSyElPCHeMU_2F2Q_0WE08gtCNzrO-SEyjDAqS46Hr/exec';

  // --- ELEMENTS ---
  const loadingStatus = document.getElementById('loading-status');
  const closedMessage = document.getElementById('closed-message');
  const registrationContent = document.getElementById('registration-content');
  
  const eligibilitySection = document.getElementById('eligibility-section');
  const checkBtn = document.getElementById('check-eligibility-btn');
  const ineligibleMsg = document.getElementById('ineligible-message');
  const mainForm = document.getElementById('apply-form') as HTMLFormElement;
  const submitBtn = document.getElementById('submit-btn') as HTMLButtonElement;
  const loadingMsg = document.getElementById('loading-msg');
  const successMsg = document.getElementById('success-message');

  // --- STEP 1: CHECK GOOGLE SHEET STATUS ---
  // Added the protective if-statement here!
  if (loadingStatus && closedMessage && registrationContent) {
    fetch(SCRIPT_URL)
      .then(response => response.json())
      .then(data => {
        loadingStatus.style.display = 'none'; // Hide the spinner
        
        // Look at the B1 cell value from the Google Sheet
        if (data.status === 'OPEN') {
          registrationContent.style.display = 'block'; // Reveal the portal!
        } else {
          closedMessage.style.display = 'block'; // Show the closed message
        }
      })
      .catch(error => {
        console.error("Status check failed:", error); // Added this to clear the warning
        // If the internet is down or script fails, fail gracefully by showing closed
        loadingStatus.style.display = 'none';
        closedMessage.style.display = 'block';
      });
  }

  // --- ELIGIBILITY LOGIC ---
  if (checkBtn && eligibilitySection && ineligibleMsg && mainForm) {
    checkBtn.addEventListener('click', () => {
      const isBSECENode = document.querySelector('input[name="isBSECE"]:checked') as HTMLInputElement;
      const isGraduatingNode = document.querySelector('input[name="isGraduating"]:checked') as HTMLInputElement;

      if (!isBSECENode || !isGraduatingNode) {
        alert("Please answer both eligibility questions to proceed.");
        return;
      }

      const isBSECE = isBSECENode.value;
      const isGraduating = isGraduatingNode.value;

      eligibilitySection.style.display = 'none';

      if (isBSECE === 'yes' && isGraduating === 'no') {
        mainForm.style.display = 'block'; 
      } else {
        ineligibleMsg.style.display = 'block'; 
      }
    });
  }

  // --- REAL-TIME VALIDATION LOGIC ---
  const setupLiveValidation = (inputId: string, errorId: string) => {
    const input = document.getElementById(inputId) as HTMLInputElement;
    const errorSpan = document.getElementById(errorId);

    if (input && errorSpan) {
      input.addEventListener('input', () => {
        if (input.value.length > 0) {
          if (input.checkValidity()) {
            errorSpan.style.display = 'none';
            input.classList.remove('invalid-live');
          } else {
            errorSpan.style.display = 'block';
            input.classList.add('invalid-live');
          }
        } else {
          errorSpan.style.display = 'none';
          input.classList.remove('invalid-live');
        }
      });
    }
  };

  setupLiveValidation('studentNumber', 'sn-error');
  setupLiveValidation('mobileNumber', 'mn-error');

  // --- FORM SUBMISSION LOGIC ---
  if (mainForm) {
    mainForm.addEventListener('submit', (e) => {
      e.preventDefault(); 
      
      submitBtn.disabled = true;
      submitBtn.style.display = 'none';
      if(loadingMsg) loadingMsg.style.display = 'block';

      fetch(SCRIPT_URL, {
        method: 'POST',
        body: new FormData(mainForm)
      })
      .then(response => response.json())
      .then(data => {
        if(data.result === 'success') {
          mainForm.style.display = 'none'; 
          if(successMsg) successMsg.style.display = 'block'; 
        } else {
          alert('There was an error submitting your form. Please try again.');
          submitBtn.disabled = false;
          submitBtn.style.display = 'block';
          if(loadingMsg) loadingMsg.style.display = 'none';
        }
      })
      .catch(error => {
        console.error("Form submission failed:", error); // Added this to clear the warning
        alert('A network error occurred. Please try again.');
        submitBtn.disabled = false;
        submitBtn.style.display = 'block';
        if(loadingMsg) loadingMsg.style.display = 'none';
      });
    });
  }
</script>