<?php
require __DIR__ . '/_boot.php';
use App\Core\Auth;

function pyrk_login_redirect_url(?array $user): string
{
    $role = $user['role_name'] ?? '';
    return in_array($role, ['super_admin', 'event_manager', 'walk_leader'], true)
        ? 'admin/dashboard.php'
        : 'index.php';
}

if (isset($_GET['logout'])) {
    Auth::logout();
    header('Location: login-dev.php');
    exit;
}

// If already logged in, do not stay on the login page.
if ($user) {
    header('Location: ' . pyrk_login_redirect_url($user));
    exit;
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Pyrk Login</title>
  <link rel="stylesheet" href="assets/css/app.css">
  <link rel="stylesheet" href="assets/css/login_landing_pro.css?v=6">
  <style>
    .birthday-field-wrap {
      position: relative;
      display: block;
      width: 100%;
    }

    .birthday-field-wrap > input {
      width: 100%;
      padding-right: 54px;
    }

    .birthday-calendar-icon {
      position: absolute !important;
      right: 12px !important;
      top: 50% !important;
      transform: translateY(-50%) !important;
      width: 36px !important;
      height: 36px !important;
      min-width: 36px !important;
      min-height: 36px !important;
      padding: 0 !important;
      display: grid !important;
      place-items: center !important;
      border: 0 !important;
      border-radius: 12px !important;
      background: #ecfdf3 !important;
      color: #0f7f55 !important;
      font-size: 1.05rem !important;
      cursor: pointer !important;
      z-index: 2 !important;
    }

    #pyrkBdayModal[hidden] {
      display: none !important;
    }

    #pyrkBdayModal {
      position: fixed !important;
      inset: 0 !important;
      z-index: 999999 !important;
      display: grid !important;
      place-items: center !important;
      padding: 16px !important;
      background: rgba(15, 23, 42, .36) !important;
      backdrop-filter: blur(4px);
    }

    #pyrkBdayModal,
    #pyrkBdayModal * {
      box-sizing: border-box !important;
    }

    #pyrkBdayModal .bd-card {
      width: min(420px, calc(100vw - 24px)) !important;
      max-height: calc(100vh - 32px) !important;
      overflow: auto !important;
      padding: 18px !important;
      border: 1px solid rgba(15,23,42,.10) !important;
      border-radius: 28px !important;
      background: #ffffff !important;
      box-shadow: 0 34px 90px rgba(15,23,42,.34) !important;
      font-family: Inter, system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif !important;
    }

    #pyrkBdayModal .bd-top {
      display: flex !important;
      justify-content: space-between !important;
      align-items: flex-start !important;
      gap: 16px !important;
      margin-bottom: 14px !important;
    }

    #pyrkBdayModal .bd-top strong {
      color: #0f172a !important;
      font-size: 1.25rem !important;
      line-height: 1.1 !important;
      font-weight: 1000 !important;
    }

    #pyrkBdayModal .bd-top span {
      color: #64748b !important;
      font-size: .8rem !important;
      line-height: 1.2 !important;
      font-weight: 900 !important;
    }

    #pyrkBdayModal .bd-toolbar {
      display: grid !important;
      grid-template-columns: 40px 40px minmax(0, 1fr) 40px 40px !important;
      gap: 7px !important;
      align-items: center !important;
      width: 100% !important;
      margin-bottom: 14px !important;
    }

    #pyrkBdayModal .bd-btn,
    #pyrkBdayModal .bd-foot-btn {
      all: unset !important;
      box-sizing: border-box !important;
      cursor: pointer !important;
      user-select: none !important;
      text-align: center !important;
      -webkit-tap-highlight-color: transparent !important;
    }

    #pyrkBdayModal .bd-btn {
      width: 40px !important;
      height: 40px !important;
      display: grid !important;
      place-items: center !important;
      border-radius: 14px !important;
      background: #ecfdf3 !important;
      color: #0f7f55 !important;
      font-size: 1.1rem !important;
      font-weight: 1000 !important;
      line-height: 1 !important;
    }

    #pyrkBdayModal .bd-btn:hover,
    #pyrkBdayModal .bd-btn:focus,
    #pyrkBdayModal .bd-foot-btn:hover,
    #pyrkBdayModal .bd-foot-btn:focus {
      outline: 3px solid rgba(15,127,85,.16) !important;
    }

    #pyrkBdayModal .bd-title {
      min-width: 0 !important;
      height: 40px !important;
      display: grid !important;
      place-items: center !important;
      padding: 0 10px !important;
      border: 1px solid #dbe3ee !important;
      border-radius: 15px !important;
      background: #f8fafc !important;
      color: #0f172a !important;
      font-size: .98rem !important;
      line-height: 1 !important;
      font-weight: 1000 !important;
      white-space: nowrap !important;
      overflow: hidden !important;
      text-overflow: ellipsis !important;
    }

    #pyrkBdayModal .bd-weekdays,
    #pyrkBdayModal .bd-days {
      display: grid !important;
      grid-template-columns: repeat(7, minmax(0, 1fr)) !important;
      gap: 6px !important;
      width: 100% !important;
    }

    #pyrkBdayModal .bd-weekdays {
      margin: 0 0 8px !important;
    }

    #pyrkBdayModal .bd-weekdays span {
      display: block !important;
      text-align: center !important;
      color: #64748b !important;
      font-size: .68rem !important;
      font-weight: 1000 !important;
      letter-spacing: .04em !important;
      text-transform: uppercase !important;
    }

    #pyrkBdayModal .bd-day,
    #pyrkBdayModal .bd-empty {
      height: 40px !important;
      min-width: 0 !important;
      display: grid !important;
      place-items: center !important;
      border-radius: 13px !important;
      font-size: .92rem !important;
      line-height: 1 !important;
      font-weight: 900 !important;
    }

    #pyrkBdayModal .bd-empty {
      background: transparent !important;
    }

    #pyrkBdayModal .bd-day {
      all: unset !important;
      box-sizing: border-box !important;
      height: 40px !important;
      display: grid !important;
      place-items: center !important;
      border-radius: 13px !important;
      background: #f8fafc !important;
      color: #0f172a !important;
      font-size: .92rem !important;
      font-weight: 900 !important;
      cursor: pointer !important;
      user-select: none !important;
      text-align: center !important;
      -webkit-tap-highlight-color: transparent !important;
    }

    #pyrkBdayModal .bd-day:hover,
    #pyrkBdayModal .bd-day:focus {
      background: #e8f8ef !important;
      color: #0f7f55 !important;
      outline: none !important;
    }

    #pyrkBdayModal .bd-day.is-selected {
      background: linear-gradient(135deg, #0f7f55, #16a36d) !important;
      color: #fff !important;
      box-shadow: 0 10px 20px rgba(15,127,85,.20) !important;
    }

    #pyrkBdayModal .bd-foot {
      display: flex !important;
      justify-content: space-between !important;
      gap: 10px !important;
      margin-top: 14px !important;
      padding-top: 12px !important;
      border-top: 1px solid #eef2f6 !important;
    }

    #pyrkBdayModal .bd-foot-btn {
      min-width: 96px !important;
      min-height: 40px !important;
      padding: 0 18px !important;
      display: inline-grid !important;
      place-items: center !important;
      border-radius: 15px !important;
      font-size: .95rem !important;
      font-weight: 1000 !important;
    }

    #pyrkBdayModal .bd-foot-btn.light {
      border: 1px solid #dbe3ee !important;
      background: #f8fafc !important;
      color: #0f172a !important;
    }

    #pyrkBdayModal .bd-foot-btn.done {
      background: #0f7f55 !important;
      color: #fff !important;
    }

    @media (max-width: 430px) {
      #pyrkBdayModal {
        padding: 8px !important;
      }

      #pyrkBdayModal .bd-card {
        width: min(372px, calc(100vw - 16px)) !important;
        padding: 14px !important;
        border-radius: 24px !important;
      }

      #pyrkBdayModal .bd-toolbar {
        grid-template-columns: 36px 36px minmax(0, 1fr) 36px 36px !important;
        gap: 5px !important;
      }

      #pyrkBdayModal .bd-btn {
        width: 36px !important;
        height: 36px !important;
        border-radius: 12px !important;
        font-size: 1rem !important;
      }

      #pyrkBdayModal .bd-title {
        height: 36px !important;
        font-size: .82rem !important;
        padding: 0 6px !important;
      }

      #pyrkBdayModal .bd-day,
      #pyrkBdayModal .bd-empty {
        height: 34px !important;
        border-radius: 10px !important;
        font-size: .84rem !important;
      }

      #pyrkBdayModal .bd-foot-btn {
        min-height: 38px !important;
      }
    }

    .phone-combo {
      display: grid !important;
      grid-template-columns: 150px minmax(0, 1fr) !important;
      gap: 10px !important;
      width: 100% !important;
    }

    .phone-combo select,
    .phone-combo input {
      width: 100% !important;
      min-height: 48px !important;
    }

    .activation-success-card {
      margin-top: 12px;
      padding: 16px;
      border: 1px solid rgba(15,127,85,.18);
      border-radius: 20px;
      background: linear-gradient(135deg, #ecfdf3, #fff);
      color: #166534;
    }

    .activation-success-card strong,
    .activation-success-card span {
      display: block;
    }

    .activation-success-card span {
      margin-top: 4px;
      color: #475569;
      font-size: .92rem;
      line-height: 1.45;
    }

    @media (max-width: 520px) {
      .phone-combo {
        grid-template-columns: 1fr !important;
      }
    }


    /* Wider professional registration form */
    body.auth-page .auth-shell {
      width: min(1220px, 96vw) !important;
      max-width: 1220px !important;
      grid-template-columns: minmax(320px, .78fr) minmax(560px, 1.22fr) !important;
      gap: 28px !important;
      align-items: start !important;
    }

    body.auth-page .auth-shell > .panel {
      width: 100% !important;
      max-width: 760px !important;
    }

    #registerForm.compact-form {
      display: grid !important;
      grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) !important;
      gap: 13px !important;
      align-items: start !important;
    }

    #registerForm.compact-form > .field-label,
    #registerForm.compact-form > .birthday-field-wrap,
    #registerForm.compact-form > textarea,
    #registerForm.compact-form > .check,
    #registerForm.compact-form > button,
    #registerForm.compact-form > input[type="hidden"] {
      grid-column: 1 / -1 !important;
    }

    #registerForm.compact-form > input[name="full_name"],
    #registerForm.compact-form > input[name="email"],
    #registerForm.compact-form > input[name="password"],
    #registerForm.compact-form > select[name="gender"] {
      min-width: 0 !important;
    }

    .phone-combo {
      grid-template-columns: 132px minmax(300px, 1fr) !important;
      gap: 12px !important;
      align-items: center !important;
    }

    .phone-combo select {
      min-width: 132px !important;
    }

    .phone-combo input {
      min-width: 300px !important;
    }

    #pyrkBdayModal .bd-year-jump {
      display: grid !important;
      grid-template-columns: 58px minmax(0, 1fr) 58px !important;
      gap: 8px !important;
      align-items: end !important;
      margin: -4px 0 14px !important;
      padding: 10px !important;
      border: 1px solid #e2e8f0 !important;
      border-radius: 18px !important;
      background: #f8fafc !important;
    }

    #pyrkBdayModal .bd-year-jump label {
      display: grid !important;
      gap: 5px !important;
      color: #64748b !important;
      font-size: .72rem !important;
      font-weight: 1000 !important;
      text-transform: uppercase !important;
      letter-spacing: .04em !important;
    }

    #pyrkBdayModal .bd-year-jump input {
      width: 100% !important;
      height: 42px !important;
      min-height: 42px !important;
      padding: 0 12px !important;
      border: 1px solid #dbe3ee !important;
      border-radius: 14px !important;
      background: #fff !important;
      color: #0f172a !important;
      font-size: 1rem !important;
      font-weight: 1000 !important;
      text-align: center !important;
    }

    #pyrkBdayModal .bd-decade-btn {
      all: unset !important;
      box-sizing: border-box !important;
      height: 42px !important;
      display: grid !important;
      place-items: center !important;
      border-radius: 14px !important;
      background: #ecfdf3 !important;
      color: #0f7f55 !important;
      cursor: pointer !important;
      font-size: .9rem !important;
      font-weight: 1000 !important;
      text-align: center !important;
    }

    #pyrkBdayModal .bd-decade-btn:hover,
    #pyrkBdayModal .bd-decade-btn:focus {
      outline: 3px solid rgba(15,127,85,.16) !important;
    }

    @media (max-width: 980px) {
      body.auth-page .auth-shell {
        grid-template-columns: 1fr !important;
        width: min(760px, 96vw) !important;
      }
      body.auth-page .hero-card {
        display: none !important;
      }
    }

    @media (max-width: 680px) {
      #registerForm.compact-form {
        grid-template-columns: 1fr !important;
      }

      .phone-combo {
        grid-template-columns: 112px minmax(0, 1fr) !important;
      }

      .phone-combo input {
        min-width: 0 !important;
      }
    }

    @media (max-width: 430px) {
      .phone-combo {
        grid-template-columns: 1fr !important;
      }

      .phone-combo select,
      .phone-combo input {
        min-width: 0 !important;
      }

      #pyrkBdayModal .bd-year-jump {
        grid-template-columns: 50px minmax(0, 1fr) 50px !important;
      }
    }


    .group-code-register-card {
      grid-column: 1 / -1 !important;
      display: grid;
      gap: 7px;
      padding: 13px;
      border: 1px solid rgba(15,127,85,.16);
      border-radius: 20px;
      background: linear-gradient(135deg, #ecfdf3, #fff);
    }

    .group-code-register-card strong,
    .group-code-register-card small {
      display: block;
    }

    .group-code-register-card small {
      color: #64748b;
      font-weight: 800;
      line-height: 1.45;
    }

    .group-code-register-card input {
      text-transform: uppercase;
      letter-spacing: .04em;
      font-weight: 900;
    }


    .register-name-grid {
      display: grid !important;
      grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) !important;
      gap: 12px !important;
      grid-column: 1 / -1 !important;
    }

    .password-field-wrap {
      position: relative;
      display: block;
      width: 100%;
    }

    .password-field-wrap input {
      width: 100%;
      padding-right: 92px !important;
    }

    .password-toggle-btn {
      position: absolute !important;
      right: 10px !important;
      top: 50% !important;
      transform: translateY(-50%) !important;
      min-width: 68px !important;
      height: 34px !important;
      padding: 0 12px !important;
      border: 0 !important;
      border-radius: 12px !important;
      background: #ecfdf3 !important;
      color: #0f7f55 !important;
      font-size: .82rem !important;
      font-weight: 1000 !important;
      cursor: pointer !important;
      z-index: 3 !important;
    }

    .password-toggle-btn:hover,
    .password-toggle-btn:focus {
      outline: 3px solid rgba(15,127,85,.16) !important;
    }

    @media (max-width: 620px) {
      .register-name-grid {
        grid-template-columns: 1fr !important;
      }
    }

  </style>
</head>
<body class="auth-page">
<div class="auth-shell">
  <div class="hero-card">
    <div class="brand-badge">PYRK</div>
    <h1>Walking Club Platform</h1>
    <p>Members, routes, walks, waivers, attendance, kilometers, loyalty, photo upload, voting, and admin approval.</p>
  </div>
  <div class="auth-brand-lockup auth-logo-image-lockup" aria-hidden="true">
    <img src="assets/img/pyrk-logo-lockup-white.png?v=2" alt="Pyrk Longevity & Biohacking Hub">
  </div>


<div class="panel">
    <h2>Login</h2>
    <form id="loginForm">
      <input name="email" type="email" placeholder="Email" autocomplete="username" required>
      <input name="password" type="password" placeholder="Password" autocomplete="current-password" required>
      <button class="btn" type="submit">Login</button>
    </form>
    <p id="loginMsg" class="notice"></p>

    <hr>

    <h2>Create Account</h2>
    <form id="registerForm" class="compact-form">
      <div class="register-name-grid">
        <input name="first_name" id="firstName" placeholder="First Name" autocomplete="given-name" required>
        <input name="last_name" id="lastName" placeholder="Last Name" autocomplete="family-name" required>
      </div>
      <input name="full_name" id="fullName" type="hidden" required>
      <input name="email" type="email" placeholder="Email" required>
      <label class="group-code-register-card">
        <strong>Group code <span class="muted">(optional)</span></strong>
        <input name="signup_code" id="signupCodeRegister" placeholder="Enter group code if you have one" autocomplete="off">
        <small>If you received a group code, enter it here and you will be assigned automatically after signup.</small>
      </label>
      <label class="field-label">Mobile
        <span class="phone-combo">
          <select name="mobile_country_code" id="mobileCountryCode" aria-label="Mobile country code" required>
          <option value="+961" selected>🇱🇧 +961</option>
          <option value="+1">🇨🇦/🇺🇸 +1</option>
          <option value="+971">🇦🇪 +971</option>
          <option value="+966">🇸🇦 +966</option>
          <option value="+974">🇶🇦 +974</option>
          <option value="+965">🇰🇼 +965</option>
          <option value="+33">🇫🇷 +33</option>
          <option value="+49">🇩🇪 +49</option>
          <option value="+44">🇬🇧 +44</option>
          <option value="+90">🇹🇷 +90</option>
          <option value="+20">🇪🇬 +20</option>
          <option value="+962">🇯🇴 +962</option>
          <option value="+963">🇸🇾 +963</option>
          <option value="+964">🇮🇶 +964</option>
          </select>
          <input name="mobile_local" id="mobileLocal" placeholder="Mobile number" inputmode="tel" autocomplete="tel-national" required>
        </span>
      </label>
      <input name="mobile" id="mobileFull" type="hidden" required>
      <span class="password-field-wrap">
        <input name="password" id="registerPassword" type="password" placeholder="Password" autocomplete="new-password" required>
        <button class="password-toggle-btn" type="button" id="toggleRegisterPassword" aria-label="Show password">Show</button>
      </span>

      <div class="birthday-field-wrap">
        <input id="dateOfBirthDisplay" name="date_of_birth_display" type="text" inputmode="numeric" placeholder="Birthday dd/mm/yyyy" autocomplete="bday" required>
        <button class="birthday-calendar-icon" id="birthdayCalendarBtn" type="button" aria-label="Open birthday calendar" title="Open birthday calendar">📅</button>
      </div>
      <input id="dateOfBirthIso" name="date_of_birth" type="hidden" required>

      <select name="gender" required>
        <option value="">Gender</option>
        <option value="female">Female</option>
        <option value="male">Male</option>
        <option value="other">Other</option>
        <option value="prefer_not_to_say">Prefer not to say</option>
      </select>
      <input name="emergency_contact_name" placeholder="Emergency contact name">
      <label class="field-label">Emergency contact mobile
        <span class="phone-combo">
          <select name="emergency_contact_country_code" id="emergencyCountryCode" aria-label="Emergency country code" required>
          <option value="+961" selected>🇱🇧 +961</option>
          <option value="+1">🇨🇦/🇺🇸 +1</option>
          <option value="+971">🇦🇪 +971</option>
          <option value="+966">🇸🇦 +966</option>
          <option value="+974">🇶🇦 +974</option>
          <option value="+965">🇰🇼 +965</option>
          <option value="+33">🇫🇷 +33</option>
          <option value="+49">🇩🇪 +49</option>
          <option value="+44">🇬🇧 +44</option>
          <option value="+90">🇹🇷 +90</option>
          <option value="+20">🇪🇬 +20</option>
          <option value="+962">🇯🇴 +962</option>
          <option value="+963">🇸🇾 +963</option>
          <option value="+964">🇮🇶 +964</option>
          </select>
          <input name="emergency_contact_mobile_local" id="emergencyLocal" placeholder="Emergency mobile number" inputmode="tel" autocomplete="tel-national" required>
        </span>
      </label>
      <input name="emergency_contact_mobile" id="emergencyFull" type="hidden" required>
      <textarea name="medical_conditions" placeholder="Medical conditions"></textarea>
      <label class="check"><input type="checkbox" name="photo_consent" value="1"> I allow photos to be used in Pyrk gallery/club media.</label>
      <button class="btn" type="submit">Create Account</button>
    </form>
    <p id="registerMsg" class="notice"></p>
  </div>
</div>

<div id="pyrkBdayModal" hidden aria-hidden="true">
  <div class="bd-card" role="dialog" aria-modal="true" aria-labelledby="bdTitle">
    <div class="bd-top">
      <strong id="bdTitle">Select birthday</strong>
      <span>dd/mm/yyyy</span>
    </div>

    <div class="bd-toolbar">
      <div class="bd-btn" id="bdPrevYear" role="button" tabindex="0" aria-label="Previous year">«</div>
      <div class="bd-btn" id="bdPrevMonth" role="button" tabindex="0" aria-label="Previous month">‹</div>
      <div class="bd-title" id="bdCurrentLabel">January 1970</div>
      <div class="bd-btn" id="bdNextMonth" role="button" tabindex="0" aria-label="Next month">›</div>
      <div class="bd-btn" id="bdNextYear" role="button" tabindex="0" aria-label="Next year">»</div>
    </div>

    <div class="bd-year-jump">
      <button class="bd-decade-btn" id="bdBack10" type="button" aria-label="Go back 10 years">-10</button>
      <label>Jump to year
        <input id="bdYearJump" type="number" min="1900" max="<?= (int)date('Y') ?>" step="1" inputmode="numeric" placeholder="1970">
      </label>
      <button class="bd-decade-btn" id="bdForward10" type="button" aria-label="Go forward 10 years">+10</button>
    </div>

    <div class="bd-weekdays">
      <span>Sun</span><span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span><span>Sat</span>
    </div>
    <div class="bd-days" id="bdDays"></div>

    <div class="bd-foot">
      <div class="bd-foot-btn light" id="bdClear" role="button" tabindex="0">Clear</div>
      <div class="bd-foot-btn done" id="bdDone" role="button" tabindex="0">Done</div>
    </div>
  </div>
</div>

<script>
window.PYRK_API_BASE='../api';
window.PYRK_CSRF='<?= htmlspecialchars($csrf) ?>';
</script>
<script src="assets/js/api.js"></script>
<script>
function redirectAfterLogin(res, fallback = 'index.php') {
  const target = res?.data?.redirect_url || fallback;
  window.location.replace(target);
  setTimeout(() => { window.location.href = target; }, 400);
}

document.getElementById('loginForm').addEventListener('submit', async e => {
  e.preventDefault();
  const msg = document.getElementById('loginMsg');
  const btn = e.target.querySelector('button[type="submit"]');
  if (btn) btn.disabled = true;

  const data = Object.fromEntries(new FormData(e.target));
  const res = await Pyrk.post('auth.php', {action:'login', ...data});

  msg.textContent = res.ok ? 'Logged in. Redirecting...' : (res.message || 'Login failed.');
  msg.className = 'notice ' + (res.ok ? 'ok' : 'bad');

  if (res.ok) {
    redirectAfterLogin(res, 'index.php');
    return;
  }
  if (btn) btn.disabled = false;
});

function parseBirthdayDdMmYyyy(value) {
  const raw = String(value || '').trim();
  const match = raw.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
  if (!match) return null;

  const day = Number(match[1]);
  const month = Number(match[2]);
  const year = Number(match[3]);
  const date = new Date(year, month - 1, day);

  if (
    date.getFullYear() !== year ||
    date.getMonth() !== month - 1 ||
    date.getDate() !== day
  ) return null;

  const today = new Date();
  if (date > today || year < 1900) return null;

  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}

function ddMmYyyyFromIso(iso) {
  const match = String(iso || '').match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if (!match) return '';
  return `${match[3]}/${match[2]}/${match[1]}`;
}

const bdState = {
  month: 0,
  year: 1970
};

function setBirthdayValue(iso) {
  const display = document.getElementById('dateOfBirthDisplay');
  const hidden = document.getElementById('dateOfBirthIso');
  if (display) display.value = ddMmYyyyFromIso(iso);
  if (hidden) hidden.value = iso;
}

function moveBirthdayMonth(delta) {
  bdState.month += delta;
  while (bdState.month < 0) {
    bdState.month += 12;
    bdState.year -= 1;
  }
  while (bdState.month > 11) {
    bdState.month -= 12;
    bdState.year += 1;
  }

  const currentYear = new Date().getFullYear();
  if (bdState.year < 1900) {
    bdState.year = 1900;
    bdState.month = 0;
  }
  if (bdState.year > currentYear) {
    bdState.year = currentYear;
    bdState.month = new Date().getMonth();
  }
  renderBirthdayCalendar();
}

function setBirthdayYear(year) {
  const currentYear = new Date().getFullYear();
  const parsed = Number(year);
  if (!Number.isFinite(parsed)) return;
  bdState.year = Math.max(1900, Math.min(currentYear, Math.round(parsed)));
  renderBirthdayCalendar();
}

function moveBirthdayYear(delta) {
  setBirthdayYear(bdState.year + delta);
}

function renderBirthdayCalendar() {
  const grid = document.getElementById('bdDays');
  const label = document.getElementById('bdCurrentLabel');
  if (!grid) return;

  const monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  if (label) label.textContent = `${monthNames[bdState.month]} ${bdState.year}`;

  const yearJump = document.getElementById('bdYearJump');
  if (yearJump) {
    yearJump.max = String(new Date().getFullYear());
    yearJump.value = String(bdState.year);
  }

  const selectedIso = parseBirthdayDdMmYyyy(document.getElementById('dateOfBirthDisplay')?.value || '');
  const first = new Date(bdState.year, bdState.month, 1);
  const daysInMonth = new Date(bdState.year, bdState.month + 1, 0).getDate();

  let html = '';
  for (let i = 0; i < first.getDay(); i++) {
    html += '<span class="bd-empty"></span>';
  }

  for (let day = 1; day <= daysInMonth; day++) {
    const iso = `${bdState.year}-${String(bdState.month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    html += `<span class="bd-day ${selectedIso === iso ? 'is-selected' : ''}" role="button" tabindex="0" data-bd-date="${iso}">${day}</span>`;
  }

  grid.innerHTML = html;
}

function openBirthdayCalendar() {
  const modal = document.getElementById('pyrkBdayModal');
  const currentIso = parseBirthdayDdMmYyyy(document.getElementById('dateOfBirthDisplay')?.value || '');

  if (currentIso) {
    const parts = currentIso.split('-').map(Number);
    bdState.year = parts[0];
    bdState.month = parts[1] - 1;
  }

  renderBirthdayCalendar();
  modal.hidden = false;
  modal.setAttribute('aria-hidden', 'false');
}

function closeBirthdayCalendar() {
  const modal = document.getElementById('pyrkBdayModal');
  modal.hidden = true;
  modal.setAttribute('aria-hidden', 'true');
}

function activateOnEnterSpace(el, fn) {
  el?.addEventListener('click', e => { e.preventDefault(); fn(e); });
  el?.addEventListener('keydown', e => {
    if (e.key !== 'Enter' && e.key !== ' ') return;
    e.preventDefault();
    fn(e);
  });
}

activateOnEnterSpace(document.getElementById('birthdayCalendarBtn'), openBirthdayCalendar);
activateOnEnterSpace(document.getElementById('bdPrevMonth'), () => moveBirthdayMonth(-1));
activateOnEnterSpace(document.getElementById('bdNextMonth'), () => moveBirthdayMonth(1));
activateOnEnterSpace(document.getElementById('bdPrevYear'), () => moveBirthdayYear(-1));
activateOnEnterSpace(document.getElementById('bdNextYear'), () => moveBirthdayYear(1));
activateOnEnterSpace(document.getElementById('bdBack10'), () => moveBirthdayYear(-10));
activateOnEnterSpace(document.getElementById('bdForward10'), () => moveBirthdayYear(10));
document.getElementById('bdYearJump')?.addEventListener('input', e => {
  const value = String(e.target.value || '').replace(/[^\d]/g, '').slice(0, 4);
  e.target.value = value;
  if (value.length === 4) setBirthdayYear(value);
});
document.getElementById('bdYearJump')?.addEventListener('change', e => setBirthdayYear(e.target.value));
activateOnEnterSpace(document.getElementById('bdDone'), closeBirthdayCalendar);
activateOnEnterSpace(document.getElementById('bdClear'), () => {
  document.getElementById('dateOfBirthDisplay').value = '';
  document.getElementById('dateOfBirthIso').value = '';
    document.getElementById('fullName').value = '';
  renderBirthdayCalendar();
});

document.getElementById('bdDays')?.addEventListener('click', e => {
  const day = e.target.closest('[data-bd-date]');
  if (!day) return;
  setBirthdayValue(day.dataset.bdDate);
  closeBirthdayCalendar();
});

document.getElementById('bdDays')?.addEventListener('keydown', e => {
  if (e.key !== 'Enter' && e.key !== ' ') return;
  const day = e.target.closest('[data-bd-date]');
  if (!day) return;
  e.preventDefault();
  setBirthdayValue(day.dataset.bdDate);
  closeBirthdayCalendar();
});

document.getElementById('pyrkBdayModal')?.addEventListener('click', e => {
  if (e.target && e.target.id === 'pyrkBdayModal') closeBirthdayCalendar();
});

document.addEventListener('keydown', e => {
  if (e.key === 'Escape') closeBirthdayCalendar();
});

document.getElementById('dateOfBirthDisplay')?.addEventListener('input', e => {
  let value = e.target.value.replace(/[^\d]/g, '').slice(0, 8);
  if (value.length >= 5) value = `${value.slice(0,2)}/${value.slice(2,4)}/${value.slice(4)}`;
  else if (value.length >= 3) value = `${value.slice(0,2)}/${value.slice(2)}`;
  e.target.value = value;

  const iso = parseBirthdayDdMmYyyy(value);
  if (iso) document.getElementById('dateOfBirthIso').value = iso;
});



function cleanRegisterSignupCode(value) {
  return String(value || '').toUpperCase().replace(/[^A-Z0-9_-]+/g, '').slice(0, 64);
}

document.getElementById('signupCodeRegister')?.addEventListener('input', e => {
  e.target.value = cleanRegisterSignupCode(e.target.value);
});


function buildFullNameFromParts() {
  const first = String(document.getElementById('firstName')?.value || '').trim().replace(/\s+/g, ' ');
  const last = String(document.getElementById('lastName')?.value || '').trim().replace(/\s+/g, ' ');
  const full = [first, last].filter(Boolean).join(' ').trim();
  const hidden = document.getElementById('fullName');
  if (hidden) hidden.value = full;
  return full;
}

['firstName','lastName'].forEach(id => {
  document.getElementById(id)?.addEventListener('input', buildFullNameFromParts);
});

document.getElementById('toggleRegisterPassword')?.addEventListener('click', () => {
  const input = document.getElementById('registerPassword');
  const btn = document.getElementById('toggleRegisterPassword');
  if (!input || !btn) return;
  const show = input.type === 'password';
  input.type = show ? 'text' : 'password';
  btn.textContent = show ? 'Hide' : 'Show';
  btn.setAttribute('aria-label', show ? 'Hide password' : 'Show password');
  input.focus();
});

function cleanLocalPhone(value) {
  return String(value || '').replace(/[^\d]/g, '').replace(/^0+/, '');
}

function buildInternationalPhone(countryId, localId, hiddenId, label) {
  const country = String(document.getElementById(countryId)?.value || '').trim();
  const local = cleanLocalPhone(document.getElementById(localId)?.value || '');
  const hidden = document.getElementById(hiddenId);

  if (!country || !local) {
    throw new Error(`${label} is required.`);
  }

  const value = `${country}${local}`;
  if (!/^\+\d{7,15}$/.test(value)) {
    throw new Error(`${label} must be a valid international mobile number.`);
  }

  if (hidden) hidden.value = value;
  return value;
}

function syncPhoneHiddenFields() {
  try {
    buildInternationalPhone('mobileCountryCode', 'mobileLocal', 'mobileFull', 'Mobile number');
    buildInternationalPhone('emergencyCountryCode', 'emergencyLocal', 'emergencyFull', 'Emergency contact number');
    return true;
  } catch {
    return false;
  }
}

['mobileCountryCode','mobileLocal','emergencyCountryCode','emergencyLocal'].forEach(id => {
  document.getElementById(id)?.addEventListener('input', syncPhoneHiddenFields);
  document.getElementById(id)?.addEventListener('change', syncPhoneHiddenFields);
});

document.getElementById('registerForm').addEventListener('submit', async e => {
  e.preventDefault();

  const fullName = buildFullNameFromParts();
  if (!fullName || !document.getElementById('firstName')?.value.trim() || !document.getElementById('lastName')?.value.trim()) {
    const msg = document.getElementById('registerMsg');
    msg.textContent = 'Please enter first name and last name.';
    msg.className = 'notice bad';
    return;
  }

  const msg = document.getElementById('registerMsg');
  const birthdayDisplay = document.getElementById('dateOfBirthDisplay');
  const birthdayIso = parseBirthdayDdMmYyyy(birthdayDisplay?.value);

  if (!birthdayIso) {
    msg.textContent = 'Enter birthday as dd/mm/yyyy.';
    msg.className = 'notice bad';
    birthdayDisplay?.focus();
    return;
  }

  try {
    buildInternationalPhone('mobileCountryCode', 'mobileLocal', 'mobileFull', 'Mobile number');
    buildInternationalPhone('emergencyCountryCode', 'emergencyLocal', 'emergencyFull', 'Emergency contact number');
  } catch (err) {
    msg.textContent = err.message || 'Please enter valid phone numbers.';
    msg.className = 'notice bad';
    return;
  }

  document.getElementById('dateOfBirthIso').value = birthdayIso;

  const fd = new FormData(e.target);
  const data = Object.fromEntries(fd);
  delete data.date_of_birth_display;
  data.photo_consent = fd.get('photo_consent') ? 1 : 0;

  const btn = e.target.querySelector('button[type="submit"]');
  if (btn) btn.disabled = true;

  const res = await Pyrk.post('auth.php', {action:'register', ...data});

  if (res.ok && res.data?.activation_required) {
    const emailStatus = String(res.data.activation_email_status || '');
    const emailError = res.data.activation_email_error ? ` Technical message: ${Pyrk.esc(res.data.activation_email_error)}` : '';
    let title = 'Registration received.';
    let detail = '';

    if (emailStatus === 'sent') {
      detail = `We sent an activation email to <b>${Pyrk.esc(data.email)}</b>. Please open the email and activate the account within 2 hours. Check spam/junk if you do not see it.`;
      msg.className = 'notice ok';
    } else if (emailStatus === 'logged') {
      title = 'Registration received, but email was not delivered.';
      detail = `The activation email was only logged because mail delivery is not configured. Please contact the administrator to configure SMTP/PHP mail or activate the account manually.`;
      msg.className = 'notice bad';
    } else if (emailStatus === 'disabled') {
      title = 'Registration received, but email is disabled.';
      detail = `Email notifications are currently disabled, so the activation email was not sent. Please contact the administrator.`;
      msg.className = 'notice bad';
    } else {
      title = 'Registration received, but email failed.';
      detail = `The activation email could not be sent. Please contact the administrator.${emailError}`;
      msg.className = 'notice bad';
    }

    msg.innerHTML = `<div class="activation-success-card"><strong>${title}</strong><span>${detail}</span></div>`;
    e.target.reset();
    document.getElementById('dateOfBirthIso').value = '';
    document.getElementById('fullName').value = '';
    document.getElementById('mobileFull').value = '';
    document.getElementById('emergencyFull').value = '';
    if (btn) btn.disabled = false;
    return;
  }

  msg.textContent = res.message || (res.ok ? 'Registration completed.' : 'Registration failed.');
  msg.className = 'notice ' + (res.ok ? 'ok' : 'bad');

  if (res.ok) {
    redirectAfterLogin(res, 'index.php');
    return;
  }

  if (btn) btn.disabled = false;
});

</script>
</body>
</html>
