<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Triple Threat Boxing - Kiosk Check-In</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>

  <!-- IMMERSIVE STAFF PIN LOCK OVERLAY (12-Hour Expiration) -->
  <div id="kioskLockOverlay">
    <div class="pin-modal">
      <h2 style="color:#fff; margin-bottom:8px; font-size: 1.5rem; text-transform: uppercase; letter-spacing: 1px; font-weight: 800;">Triple Threat</h2>
      <p style="color:#8b8b95; margin-bottom:28px; font-size:0.9rem;">Staff Pin Required to Unlock Kiosk</p>
      <input type="password" id="staffPinInput" placeholder="Enter PIN" class="form-control" style="text-align: center; font-size: 1.5rem; letter-spacing: 6px; margin-bottom: 20px;">
      <button onclick="unlockKiosk()" class="btn-submit">Unlock Terminal</button>
    </div>
  </div>

  <!-- MAIN KIOSK CONTAINER -->
  <div class="kiosk-container">

    <!-- TOP-CENTER LOGO HOME BUTTON -->
    <a href="index.html" class="logo-home-btn" title="Return to Home">
      <img src="Triple Threat Logo.jpeg" alt="Triple Threat Boxing Logo">
    </a>

    <div class="header">
      <h1>Front Desk Check-In</h1>
      <p>Scan barcode or enter member ID/phone</p>
    </div>

    <div id="alertBox" class="alert"></div>

    <!-- STEP 1: MEMBER SCAN / ID INPUT -->
    <div id="screenCheckIn" class="screen active">
      <form id="checkInForm" onsubmit="handleMemberLookup(event)">
        <div class="form-group">
          <label for="checkInInput">Member ID / Barcode / Phone</label>
          <input type="text" id="checkInInput" class="form-control" required placeholder="Scan barcode or type ID..." autofocus>
        </div>
        <button type="submit" id="btnLookup" class="btn-submit">Continue Check-In</button>
      </form>

      <!-- NEW MEMBER NAVIGATION BUTTON -->
      <div style="margin-top: 30px; border-top: 1px solid rgba(255,255,255,0.06); padding-top: 24px; text-align: center;">
        <p style="color: #666675; font-size: 0.75rem; margin-bottom: 12px; text-transform: uppercase; letter-spacing: 1px; font-weight: 700;">New to the gym?</p>
        <a href="register.html" class="btn-submit" style="background: #17171c; border: 1px solid #262630; color: #fff; box-shadow: none;">
          New Member Sign-Up &rarr;
        </a>
      </div>
    </div>

    <!-- STEP 2: CLASS SELECTION (Dynamic) -->
    <div id="screenClassSelect" class="screen">
      <div id="welcomeMemberText" style="text-align: center; margin-bottom: 20px; font-size: 1.2rem; color: #fff; font-weight: 700;"></div>
      
      <p style="color: #8b8b95; font-size: 0.75rem; margin-bottom: 12px; text-transform: uppercase; letter-spacing: 1px; font-weight: 700;">Select Class Attendance:</p>
      
      <div id="classListContainer" style="display: flex; flex-direction: column; gap: 12px; margin-bottom: 24px;">
        <!-- Dynamically injected classes go here -->
      </div>

      <button type="button" onclick="resetCheckIn()" class="btn-submit" style="background: #17171c; border: 1px solid #262630; color: #8b8b95; box-shadow: none;">
        Cancel / Back
      </button>
    </div>

  </div>

  <script>
    const APPS_SCRIPT_URL = "YOUR_APPS_SCRIPT_WEB_APP_URL";
    let currentMemberId = "";

    window.addEventListener('DOMContentLoaded', () => {
      const unlockedTime = localStorage.getItem('ttb_unlocked_time');
      const twelveHours = 12 * 60 * 60 * 1000;

      if (unlockedTime && (Date.now() - parseInt(unlockedTime) < twelveHours)) {
        document.getElementById('kioskLockOverlay').style.display = 'none';
        document.getElementById('checkInInput').focus();
      }
    });

    function unlockKiosk() {
      const pin = document.getElementById('staffPinInput').value;
      if (pin === "1234") { 
        localStorage.setItem('ttb_unlocked_time', Date.now().toString());
        document.getElementById('kioskLockOverlay').style.display = 'none';
        document.getElementById('checkInInput').focus();
      } else {
        alert("Incorrect Staff PIN");
      }
    }

    function showAlert(message, type) {
      const alertBox = document.getElementById('alertBox');
      alertBox.innerText = message;
      alertBox.className = `alert alert-${type}`;
      alertBox.style.display = 'block';
    }

    function hideAlert() {
      const alertBox = document.getElementById('alertBox');
      alertBox.style.display = 'none';
    }

    function resetCheckIn() {
      hideAlert();
      currentMemberId = "";
      document.getElementById('screenClassSelect').classList.remove('active');
      document.getElementById('screenCheckIn').classList.add('active');
      const input = document.getElementById('checkInInput');
      input.value = "";
      input.focus();
    }

    async function handleMemberLookup(event) {
      event.preventDefault();
      const btn = document.getElementById('btnLookup');
      const identifier = document.getElementById('checkInInput').value.trim();
      if (!identifier) return;

      btn.disabled = true;
      btn.innerText = "Verifying Member...";
      hideAlert();

      try {
        const response = await fetch(APPS_SCRIPT_URL, {
          method: "POST",
          headers: { "Content-Type": "text/plain" },
          body: JSON.stringify({ action: "lookupMember", identifier: identifier })
        });

        const data = await response.json();
        if (data.status === "success") {
          currentMemberId = data.memberId;
          document.getElementById('welcomeMemberText').innerText = `Welcome back, ${data.memberName}!`;
          
          let classesHtml = `<button onclick="submitAttendance('Open Gym')" class="btn-submit">Open Gym (General Access)</button>`;
          
          if (data.allowedClasses && data.allowedClasses.length > 0) {
            data.allowedClasses.forEach(cls => {
              classesHtml += `<button onclick="submitAttendance('${cls}')" class="btn-submit" style="background:#17171c; border:1px solid #0035cc; box-shadow:none;">${cls}</button>`;
            });
          }

          document.getElementById('classListContainer').innerHTML = classesHtml;
          
          document.getElementById('screenCheckIn').classList.remove('active');
          document.getElementById('screenClassSelect').classList.add('active');
        } else {
          showAlert(data.message || "Member not found. Please check ID or register.", "error");
        }
      } catch (err) {
        showAlert("Error connecting to server: " + err.message, "error");
      } finally {
        btn.disabled = false;
        btn.innerText = "Continue Check-In";
      }
    }

    async function submitAttendance(className) {
      hideAlert();
      try {
        const response = await fetch(APPS_SCRIPT_URL, {
          method: "POST",
          headers: { "Content-Type": "text/plain" },
          body: JSON.stringify({
            action: "checkInRecord",
            memberId: currentMemberId,
            className: className
          })
        });

        const data = await response.json();
        if (data.status === "success") {
          alert(`Checked in successfully for ${className}!`);
          resetCheckIn();
        } else {
          showAlert(data.message || "Failed to record attendance.", "error");
        }
      } catch (err) {
        showAlert("Error recording attendance: " + err.message, "error");
      }
    }
  </script>
</body>
</html>
