.gres-wrap{max-width:900px}
.gres-card{background:#fff;border:1px solid #ddd;padding:14px;margin:12px 0;border-radius:8px}
.gres-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
.gres-grid label{display:block;font-weight:600;margin-bottom:6px}
.gres-grid input,.gres-grid select{width:100%;padding:8px;border:1px solid #bbb;border-radius:6px}
.gres-actions{margin:12px 0;display:flex;gap:10px}
.gres-total{font-size:18px;margin-top:10px}
.gres-small{font-size:13px;color:#333;margin-top:8px}

/* Inline field errors (show directly under the field, in red) */
.gres-field-error{display:none;margin-top:4px;font-size:12px;line-height:1.35;color:#b00020}
.gres-block-head{display:flex;align-items:center;justify-content:space-between}
.gres-courts{display:flex;flex-wrap:wrap;gap:8px}
.gres-court-pill{display:inline-flex;align-items:center;gap:6px;border:1px solid #111;border-radius:999px;padding:6px 10px;cursor:pointer}
.gres-court-pill input{margin:0}
.gres-court-pill.is-disabled{opacity:.35;border-color:#555;cursor:not-allowed;pointer-events:none}
.gres-sum-line{display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #eee}
.gres-sum-right{font-weight:700}
.gres-line{margin-top:10px}
.gres-loading{opacity:.75}

/* Other Items */
.gres-items{display:flex;flex-direction:column;gap:12px}
.gres-item label{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap}
.gres-item-name{font-weight:600}
.gres-item-avail{font-weight:400;opacity:0.85}
.gres-item-qty{width:90px;max-width:120px}
.gres-item-inputs{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.gres-item-mini{font-size:12px;opacity:0.85;min-width:28px;text-align:right}
.gres-item-hours{width:90px;max-width:120px}
.gres-item-hours-label{font-size:12px;opacity:0.85}
.gres-item-note{font-size:12px;margin-top:6px;opacity:0.95}
@media (max-width: 760px){
  .gres-grid{grid-template-columns:1fr}
}


/* Reservation Lookup shortcode */
.gres-lookup-wrap{max-width:900px;margin:20px auto;padding:10px}
.gres-lookup-form{display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap;margin:10px 0 15px}
.gres-lookup-form label{display:block;font-weight:600;margin-bottom:6px}
.gres-lookup-form input[type=email]{min-width:260px;max-width:420px;width:100%}
.gres-lookup-errors{background:#fff3cd;border:1px solid #ffeeba;padding:10px;border-radius:6px;margin:10px 0}
.gres-lookup-card{border:1px solid rgba(0,0,0,0.15);border-radius:8px;padding:12px;margin:12px 0;background:#ffffff}
.gres-lookup-card-head{display:flex;justify-content:space-between;gap:10px;align-items:center;margin-bottom:6px}
.gres-lookup-id{font-weight:700}
.gres-lookup-status{text-transform:capitalize}
.gres-lookup-meta{display:flex;gap:20px;flex-wrap:wrap;margin:6px 0 10px}
.gres-lookup-section{margin-top:10px}
.gres-lookup-ul{margin:6px 0 0 18px}



/* === UI Controls (Admin-driven) === */
.gres-wrap h1,
.gres-wrap h2,
.gres-wrap h3,
.gres-wrap h4,
.gres-wrap .gres-title,
.gres-wrap .gres-heading,
.gres-wrap .gres-section-title {
  color: var(--gres-heading-color, #000000) !important;
}

.gres-wrap .gres-page-title,
.gres-wrap > h2,
.gres-wrap h2 {
  font-size: var(--gres-title-size, 28px) !important;
}

.gres-wrap h3,
.gres-wrap .gres-section-title,
.gres-wrap .gres-subheading {
  font-size: var(--gres-section-size, 18px) !important;
}

.gres-wrap .gres-theme-toggle {
  margin: 10px 0 15px 0;
  font-weight: var(--gres-button-weight, 600) !important;
}

/* Match button fonts with headings (optional) */
.gres-wrap button,
.gres-wrap .button,
.gres-wrap input[type="submit"] {
  font-weight: var(--gres-button-weight, 600) !important;
}

.gres-wrap .gres-btn-primary,
.gres-wrap #gres-add-court,
.gres-wrap #gres-pay-btn,
.gres-wrap .gres-theme-toggle {
  color: var(--gres-button-color, inherit) !important;
}

/* === Scoped Dark Theme (only inside .gres-wrap) === */
.gres-wrap.gres-theme-dark,
.gres-wrap.gres-theme-dark .gres-card,
.gres-wrap.gres-theme-dark .gres-box {
  background: #0f172a !important;
  color: #e5e7eb !important;
}

.gres-wrap.gres-theme-dark input,
.gres-wrap.gres-theme-dark select,
.gres-wrap.gres-theme-dark textarea {
  background: #111827 !important;
  color: #e5e7eb !important;
  border-color: #374151 !important;
}

.gres-wrap.gres-theme-dark label,
.gres-wrap.gres-theme-dark .description,
.gres-wrap.gres-theme-dark .gres-help {
  color: #e5e7eb !important;
}

.gres-wrap.gres-theme-dark .gres-section,
.gres-wrap.gres-theme-dark .gres-summary {
  border-color: #334155 !important;
}


.gres-approval-msg{margin-top:10px;padding:10px;border:1px solid #ccc;border-radius:6px;background:#fff3cd;color:#000;}


/* Collapsible Waiver / Court Rules */
.gres-collapse{border:1px solid #ddd; border-radius:10px; padding:10px; background:#fff;}
.gres-collapse > summary{cursor:pointer; font-size:16px;}
.gres-collapse-body{margin-top:10px;}
.gres-legal-text{font-size:14px; line-height:1.4;}
.gres-ack{display:block; margin-top:10px; font-weight:600;}
.gres-legal-missing{padding:10px; border:1px dashed #cc0000; border-radius:8px; background:#fff7f7;}


.gres-radio-row{display:flex;gap:14px;align-items:center;flex-wrap:wrap;}
.gres-radio-row label{display:flex;gap:6px;align-items:center;}


/* My Reservations: Pay link (always visible) */
.gres-wrap .gres-pay-link{
  color:#2271b1 !important;
  font-weight:600;
  text-decoration:underline;
  cursor:pointer;
  opacity:1 !important;
  visibility:visible !important;
}
.gres-wrap .gres-pay-link:hover{
  color:#135e96 !important;
}


/* ===== Premium My Reservations Portal ===== */
.gres-myres{max-width:1100px;margin:0 auto;}
.gres-myres-header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;}
.gres-myres-title{margin:0;font-size:28px;letter-spacing:.2px;}

.gres-table-wrap{max-width:100%;overflow:auto;-webkit-overflow-scrolling:touch;}
.gres-table-wrap table{max-width:100%;}
.gres-table-wrap th,.gres-table-wrap td{white-space:normal;word-break:normal;overflow-wrap:break-word;}
.gres-myres-table-wrap{width:100%;max-width:100%;display:block;overflow-x:auto;overflow-y:auto;-webkit-overflow-scrolling:touch;}
/* =========================
   My Reservations Portal
   SaaS-level UI (cards + optional table)
   ========================= */

.gres-myres{max-width:1100px;margin:0 auto;}

/* View toggle */
.gres-myres-viewtoggle{display:flex;gap:8px;align-items:center;margin:10px 0 14px 0;}
.gres-view-btn{appearance:none;border:1px solid rgba(0,0,0,.15);background:#fff;padding:8px 10px;border-radius:999px;font-weight:800;font-size:13px;cursor:pointer;}
.gres-view-btn.is-active{background:#111;color:#fff;border-color:#111;}

/* Status badges */
.gres-status-badge{display:inline-flex;align-items:center;gap:6px;padding:6px 10px;border-radius:999px;font-weight:900;font-size:12px;line-height:1;border:1px solid rgba(0,0,0,.10);white-space:nowrap;}
.gres-status-paid{background:#e7f7ee;}
.gres-status-request-payment{background:#fff3cd;}
.gres-status-awaiting-approval{background:#e7f1ff;}
.gres-status-pending{background:#f2f2f2;}
.gres-status-cancelled{background:#ffe6e6;}
.gres-soon-badge{display:inline-flex;align-items:center;padding:4px 8px;border-radius:999px;font-weight:900;font-size:11px;line-height:1;margin-left:8px;background:#e7f1ff;border:1px solid rgba(0,0,0,.10);white-space:nowrap;}

/* Cards */
.gres-myres-cards{display:grid;gap:14px;}
.gres-card{background:#fff;border:1px solid rgba(0,0,0,.10);border-radius:16px;box-shadow:0 10px 30px rgba(0,0,0,.06);padding:14px 14px 12px 14px;}
.gres-card-top{display:flex;justify-content:space-between;gap:14px;align-items:flex-start;}
.gres-card-title{font-weight:900;font-size:14px;}
.gres-card-id{font-weight:1000;}
.gres-card-subtle{font-size:12px;opacity:.7;margin-top:4px;}

.gres-card-grid{display:grid;grid-template-columns:repeat(4, minmax(0, 1fr));gap:10px;margin-top:12px;}
.gres-card-field{border:1px solid rgba(0,0,0,.08);border-radius:12px;padding:10px 10px;}
.gres-card-k{font-size:11px;letter-spacing:.3px;font-weight:900;opacity:.65;text-transform:uppercase;margin-bottom:4px;}
.gres-card-v{font-weight:800;word-break:break-word;}

.gres-card-actions{display:flex;gap:10px;align-items:flex-start;justify-content:space-between;margin-top:12px;flex-wrap:wrap;}

/* Buttons (theme-proof) */
.gres-btn{display:inline-flex !important;align-items:center;justify-content:center;gap:8px;border-radius:10px;font-weight:900;font-size:13px;text-decoration:none !important;white-space:nowrap;border:1px solid rgba(0,0,0,.14);padding:7px 11px !important;cursor:pointer;}
.gres-btn-pay,
.gres-myres a.gres-btn.gres-btn-pay{background:var(--gres-pay-btn-bg,#2271b1) !important;color:#fff !important;border-color:var(--gres-pay-btn-bg,#2271b1) !important;min-width:132px;text-align:center;}
.gres-myres a.gres-btn.gres-btn-pay:hover{background:var(--gres-pay-btn-bg,#2271b1) !important;color:#fff !important;opacity:1 !important;}

/* Details */
.gres-details{margin-top:0;}
.gres-details summary{cursor:pointer;font-weight:900;user-select:none;}
.gres-details-body{padding:10px 0 2px 0;}

/* Optional table view */
/* Keep the table aligned with the page (no fixed widths). Allow it to expand based on content,
   and provide horizontal/vertical scrollbars when needed to view more info. */
.gres-myres-table-wrap{width:100%;max-width:100%;display:block;overflow-x:auto;overflow-y:auto;-webkit-overflow-scrolling:touch;}
/* Let the table size to its content while still filling the container when content is small */
.gres-myres-table{border-collapse:separate;border-spacing:0;table-layout:auto;width:max-content;min-width:100%;max-width:none;}
.gres-myres-table thead th{position:sticky;top:0;background:#fbfbfb;z-index:1;text-align:left;font-weight:900;font-size:13px;letter-spacing:.2px;padding:14px 14px;border-bottom:1px solid rgba(0,0,0,.08);white-space:normal;word-break:keep-all;overflow-wrap:normal;}
.gres-myres-table tbody td{padding:14px 14px;border-bottom:1px solid rgba(0,0,0,.06);vertical-align:top;white-space:normal;word-break:keep-all;overflow-wrap:normal;}
.gres-myres-table tbody tr:hover td{background:rgba(0,0,0,.015);}
.gres-myres-table tbody tr:last-child td{border-bottom:none;}
.gres-myres-table th:last-child,.gres-myres-table td:last-child{white-space:nowrap;}

@media (max-width: 980px){
  .gres-card-grid{grid-template-columns:repeat(2, minmax(0,1fr));}
}

@media (max-width: 640px){
  .gres-card-grid{grid-template-columns:1fr;}
  .gres-card-actions{flex-direction:column;align-items:stretch;}
  .gres-btn{width:100%;}
  .gres-myres-viewtoggle{justify-content:flex-start;}
}


/* Reservation Login */
.gres-login-wrap{max-width:520px;margin:18px auto;padding:18px;border-radius:12px;background:#fff;border:1px solid rgba(0,0,0,.08);box-shadow:0 6px 18px rgba(0,0,0,.06)}
.gres-login-title{margin:0 0 6px 0;font-size:22px;line-height:1.2}
.gres-login-msg{margin:0 0 14px 0;color:#444}
.gres-login-wrap #gres-loginform{margin-top:10px}
.gres-login-wrap #gres-loginform p{margin:10px 0}
.gres-login-wrap #gres-loginform label{font-weight:600;display:block;margin-bottom:6px}
.gres-login-wrap #gres-loginform input[type="text"],
.gres-login-wrap #gres-loginform input[type="password"]{width:100%;max-width:100%;padding:10px 12px;border:1px solid rgba(0,0,0,.18);border-radius:8px}
.gres-login-wrap #gres-loginform input[type="submit"]{background:#2271b1;color:#fff;border:0;border-radius:8px;padding:10px 14px;font-weight:700;cursor:pointer}
.gres-login-links{margin-top:12px}
.gres-login-links a{text-decoration:underline}



/* Portal header + login/logout buttons */
.gres-portal-head,
.gres-myres-header{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
  flex-wrap:wrap;
}
.gres-portal-actions,
.gres-myres-actions{
  display:flex;
  align-items:center;
  gap:10px;
}
.gres-portal-topbtn{
  display:inline-block;
  padding:8px 12px;
  border-radius:12px;
  font-weight:700;
  text-decoration:none !important;
  border:1px solid rgba(0,0,0,0.12);
  line-height:1;
  box-shadow:0 1px 2px rgba(0,0,0,0.06);
}
.gres-portal-login{
  background:var(--gres-login-btn-bg,#2563eb);
  color:#fff !important;
  border-color:var(--gres-login-btn-bg,#2563eb);
}
.gres-portal-logout{
  background:#f3f4f6;
  color:#111 !important;
}
.gres-portal-topbtn:hover,
.gres-portal-topbtn:focus{
  opacity:1;
  filter:none;
}


/* Generic button links */
.gres-btn{
  display:inline-block;
  padding:10px 14px;
  border-radius:10px;
  border:1px solid rgba(0,0,0,.12);
  text-decoration:none !important;
  font-weight:600;
}
.gres-btn-secondary{
  background:#fff;
  color:#111 !important;
}
.gres-btn-secondary:hover,
.gres-btn-secondary:focus{
  background:#f5f7fb;
  color:#111 !important;
}


/* Email-first router (login) */
.gres-alert { padding: 10px 12px; border-radius: 10px; margin: 10px 0; font-weight: 600; }
.gres-alert-error { background: #fff2f2; border: 1px solid #f3b1b1; color: #7a1d1d; }
.gres-router-form .input { width: 100%; max-width: 420px; padding: 10px 12px; border-radius: 10px; border: 1px solid #cfd6df; }
.gres-field-label { display:block; margin-top: 10px; margin-bottom: 6px; font-weight: 700; }


/* Back to Reservations link: black, clickable, no hover effect */
.gres-back-to-reservations {
  color: #000 !important;
  text-decoration: none !important;
  font-weight: 600;
}
.gres-back-to-reservations:hover,
.gres-back-to-reservations:focus,
.gres-back-to-reservations:active {
  color: #000 !important;
  text-decoration: none !important;
  opacity: 1 !important;
}

/* Goldusters login button: lock hover color (no hover shift) */
.gres-goldusters-login #gres-gold-loginform .button-primary,
.gres-goldusters-login #gres-gold-loginform input[type=submit],
.gres-goldusters-login #gres-gold-loginform button,
.gres-goldusters-login #gres-gold-loginform input[type=button] {
  background: var(--gres-gold-btn-bg, #2563eb) !important;
  border-color: var(--gres-gold-btn-bg, #2563eb) !important;
  color: #fff !important;
}
.gres-goldusters-login #gres-gold-loginform .button-primary:hover,
.gres-goldusters-login #gres-gold-loginform input[type=submit]:hover,
.gres-goldusters-login #gres-gold-loginform button:hover,
.gres-goldusters-login #gres-gold-loginform input[type=button]:hover,
.gres-goldusters-login #gres-gold-loginform .button-primary:focus,
.gres-goldusters-login #gres-gold-loginform input[type=submit]:focus,
.gres-goldusters-login #gres-gold-loginform button:focus,
.gres-goldusters-login #gres-gold-loginform input[type=button]:focus {
  background: var(--gres-gold-btn-bg-hover, #1d4ed8) !important;
  border-color: var(--gres-gold-btn-bg-hover, #1d4ed8) !important;
  color: #fff !important;
  filter: none !important;
  opacity: 1 !important;
}
.gres-goldusters-login-btn:hover,
.gres-goldusters-login-btn:focus,
.gres-goldusters-login-btn:active {
  filter: none !important;
  opacity: 1 !important;
}


/* Availability Suggestions (Phase 3A-1) */
.gres-suggestions{ margin-top:10px; padding:10px; border:1px dashed #ccc; border-radius:10px; background:#fff; }
.gres-sug-title{ font-weight:600; margin-bottom:8px; }
.gres-sug-list{ display:flex; flex-wrap:wrap; gap:8px; }
.gres-sug-btn{ white-space:normal; text-align:left; }


/* ===== My Reservations Table View â€“ flexible width + scroll ===== */
.gres-myres-table-wrap{width:100%;max-width:100%;display:block;overflow-x:auto;overflow-y:auto;-webkit-overflow-scrolling:touch;}
.gres-myres-table-wrap .gres-table-wrap{display:block;width:100% !important;max-width:100% !important;overflow:auto !important;-webkit-overflow-scrolling:touch;}
.gres-myres-table-wrap .gres-table-wrap table{width:max-content !important;min-width:100% !important;max-width:none !important;table-layout:auto !important;}
.gres-myres-table-wrap .gres-table-wrap th,
.gres-myres-table-wrap .gres-table-wrap td{white-space:normal !important;word-break:normal !important;overflow-wrap:break-word !important;}


/* ===== My Reservations Table View: TRUE flexible width + scroll (override theme widefat) ===== */
.gres-myres #gresMyResTable.gres-table-wrap{max-width:100% !important; overflow-x:auto !important; overflow-y:auto !important;}

/* Let table size to content (no fixed/narrow columns). Wrapper provides scrollbars. */
.gres-myres #gresMyResTable.gres-table-wrap table.gres-myres-table{
  table-layout:auto !important;
  width:max-content !important;
  min-width:100% !important;
  max-width:none !important;
}

/* Prevent letter-by-letter stacking from theme rules like word-break:break-all */
.gres-myres #gresMyResTable.gres-table-wrap table.gres-myres-table th,
.gres-myres #gresMyResTable.gres-table-wrap table.gres-myres-table td{
  white-space:nowrap !important;
  word-break:keep-all !important;
  overflow-wrap:normal !important;
}

/* Keep action column from shrinking too much */
.gres-myres #gresMyResTable.gres-table-wrap table.gres-myres-table th[data-col="actions"],
.gres-myres #gresMyResTable.gres-table-wrap table.gres-myres-table td[data-col="actions"]{
  min-width:120px !important;
}



/* ===== My Reservations Table Reset (no fixed width, scrollable wrapper) ===== */
#gresMyResTable .gres-myres-table-wrap{
  width:100% !important;
  max-width:100% !important;
  overflow:auto !important;
  -webkit-overflow-scrolling:touch;
}

#gresMyResTable table.gres-myres-table{
  width:100% !important;
  /* allow natural column sizing; prevent cramped fixed-layout columns */
  table-layout:auto !important;
  /* ensure table can expand when content needs it (wrapper will scroll) */
  min-width:900px !important;
  max-width:none !important;
}

#gresMyResTable table.gres-myres-table th,
#gresMyResTable table.gres-myres-table td{
  white-space:normal !important;
  word-break:normal !important;
  overflow-wrap:break-word !important;
}

#gresMyResTable table.gres-myres-table td[data-col="date_time"],
#gresMyResTable table.gres-myres-table td[data-col="payment_due"],
#gresMyResTable table.gres-myres-table th[data-col="date_time"],
#gresMyResTable table.gres-myres-table th[data-col="payment_due"]{
  min-width:180px !important;
}
/* ===============================
   GOLDUSTERS BLACK + GOLD THEME
   (NO LOGIC CHANGE)
================================ */

.gres-wrap{
  --gold:#FBB040;
  --gold-soft:rgba(251,176,64,.35);
  --black:#050505;
  --panel:#0b0b0d;
  --border:rgba(251,176,64,.45);
  --text:#f5e6b8;

  background: radial-gradient(circle at top left, rgba(251,176,64,.08), transparent 30%),
              linear-gradient(135deg,#000,#0a0a0a,#140d02);
  padding:20px;
  border-radius:18px;
  border:1px solid var(--border);
}

/* ===== CARDS ===== */
.gres-card{
  background: linear-gradient(135deg,#000,#120c02) !important;
  border:1px solid var(--border) !important;
  border-radius:16px !important;
  box-shadow:0 12px 30px rgba(0,0,0,.6);
  color:var(--text) !important;
}

/* ===== HEADINGS ===== */
.gres-wrap h1,
.gres-wrap h2,
.gres-wrap h3{
  color:var(--gold) !important;
  letter-spacing:.5px;
}

/* ===== INPUTS ===== */
.gres-wrap input,
.gres-wrap select,
.gres-wrap textarea{
  background:#050505 !important;
  border:1px solid var(--border) !important;
  color:#fff !important;
  border-radius:10px !important;
}

.gres-wrap input:focus,
.gres-wrap select:focus{
  outline:none;
  border-color:var(--gold) !important;
  box-shadow:0 0 8px rgba(251,176,64,.6);
}

/* ===== LABELS ===== */
.gres-wrap label{
  color:var(--text) !important;
}

/* ===== BUTTONS ===== */
.gres-btn,
.gres-wrap button,
.gres-wrap input[type="submit"]{
  background:linear-gradient(135deg,#FBB040,#c8921a) !important;
  color:#000 !important;
  border:none !important;
  border-radius:12px !important;
  font-weight:800;
  box-shadow:0 4px 12px rgba(251,176,64,.4);
  transition:.2s ease;
}

.gres-btn:hover{
  transform:translateY(-1px);
  box-shadow:0 6px 18px rgba(251,176,64,.6);
}

/* ===== COURT PILLS ===== */
.gres-court-pill{
  background:#000;
  border:1px solid var(--border) !important;
  color:var(--gold);
}

.gres-court-pill input{
  accent-color:var(--gold);
}

/* ===== SUMMARY ===== */
.gres-sum-line{
  border-bottom:1px solid rgba(251,176,64,.25) !important;
  color:#fff;
}

.gres-sum-right{
  color:var(--gold);
}

/* ===== LOOKUP CARDS ===== */
.gres-lookup-card{
  background:linear-gradient(135deg,#000,#120c02) !important;
  border:1px solid var(--border) !important;
  color:#fff;
}

/* ===== STATUS BADGES ===== */
.gres-status-badge{
  border:1px solid var(--border) !important;
  font-weight:800;
}

.gres-status-paid{
  background:rgba(34,197,94,.15);
  color:#22c55e;
}

.gres-status-request-payment{
  background:rgba(251,176,64,.15);
  color:var(--gold);
}

/* ===== LOGIN BOX ===== */
.gres-login-wrap{
  background:linear-gradient(135deg,#000,#120c02) !important;
  border:1px solid var(--border) !important;
  color:#fff;
}

/* ===== LINKS ===== */
.gres-wrap a{
  color:var(--gold) !important;
}

/* ===== TABLE ===== */
.gres-myres-table thead th{
  background:#0a0a0a !important;
  color:var(--gold) !important;
  border-bottom:1px solid var(--border) !important;
}

.gres-myres-table tbody td{
  background:#050505 !important;
  color:#fff;
}

/* ===== GOLD GLOW EFFECT ===== */
.gres-card:hover{
  box-shadow:0 0 20px rgba(251,176,64,.35);
}
/* =========================
   GOLDUSTERS FOOTNOTE FIX
   ========================= */

/* Fix small notes / footnotes */
.gres-wrap .gres-small{
  color:#ffffff !important;
  opacity:1 !important;
}

/* Fix legal / waiver text */
.gres-wrap .gres-legal-text{
  color:#ffffff !important;
}

/* Fix item notes */
.gres-wrap .gres-item-note{
  color:#ffffff !important;
  opacity:1 !important;
}

/* Fix approval / notice messages */
.gres-wrap .gres-approval-msg{
  color:#000 !important; /* stays readable on yellow */
}

/* Force ALL small text inside plugin to be readable */
.gres-wrap small,
.gres-wrap .description,
.gres-wrap .note,
.gres-wrap p{
  color:#ffffff !important;
}
/* =========================
   GOLDUSTERS CLEAN UI SYSTEM (FINAL)
   ========================= */

.gres-wrap{
  --gold:#FBB040;
  --text-light:#ffffff;
  --text-dark:#111111;
  --panel-dark:#0b0b0d;
  --panel-light:#ffffff;
}

/* ===== GLOBAL TEXT FIX ===== */
.gres-wrap{
  color:var(--text-light) !important;
}

/* ===== HEADINGS ===== */
.gres-wrap h1,
.gres-wrap h2,
.gres-wrap h3,
.gres-wrap h4{
  color:var(--gold) !important;
}

/* Sub headings / labels */
.gres-wrap label,
.gres-wrap .gres-title,
.gres-wrap .gres-heading,
.gres-wrap .gres-section-title{
  color:var(--text-light) !important;
}

/* ===== PARAGRAPH / NOTES ===== */
.gres-wrap p,
.gres-wrap small,
.gres-wrap .gres-small,
.gres-wrap .gres-item-note,
.gres-wrap .gres-legal-text{
  color:var(--text-light) !important;
  opacity:1 !important;
}

/* ===== LIGHT BACKGROUND AREAS ===== */
.gres-lookup-errors,
.gres-collapse,
.gres-login-wrap,
.gres-suggestions{
  background:var(--panel-light) !important;
  color:var(--text-dark) !important;
}

/* Fix text inside white areas */
.gres-lookup-errors *,
.gres-collapse *,
.gres-login-wrap *,
.gres-suggestions *{
  color:var(--text-dark) !important;
}

/* ===== DARK CARD AREAS ===== */
.gres-card,
.gres-wrap{
  background:linear-gradient(135deg,#000,#120c02) !important;
  color:var(--text-light) !important;
}

/* ===== INPUTS ===== */
.gres-wrap input,
.gres-wrap select,
.gres-wrap textarea{
  background:#050505 !important;
  color:#ffffff !important;
}

/* ===== BUTTONS ===== */
.gres-wrap button,
.gres-wrap .gres-btn{
  color:#000 !important;
}

/* ===== REMOVE FADE ISSUES ===== */
.gres-wrap *{
  opacity:1 !important;
  filter:none !important;
}

/* ===== KILL OLD VARIABLE CONFLICT ===== */
.gres-wrap{
  --gres-heading-color: var(--gold) !important;
}
/* =========================
   GOLDUSTERS CLEAN FINAL (NO CONFLICTS)
   ========================= */

.gres-wrap{
  --gold:#FBB040;
  --bg:#050505;
  --panel:#0b0b0d;
  --border:rgba(251,176,64,.4);
  --text:#ffffff;
}

/* ===== BASE ===== */
.gres-wrap{
  color:var(--text);
}

/* ===== CARDS ===== */
.gres-card{
  background:linear-gradient(135deg,#000,#120c02) !important;
  border:1px solid var(--border) !important;
  color:#fff !important;
}

/* ===== HEADINGS ===== */
.gres-wrap h1,
.gres-wrap h2,
.gres-wrap h3{
  color:var(--gold) !important;
}

/* ===== TEXT ===== */
.gres-wrap p,
.gres-wrap label,
.gres-wrap .gres-small,
.gres-wrap .gres-item-note{
  color:#ffffff !important;
}

/* ===== INPUTS ===== */
.gres-wrap input,
.gres-wrap select,
.gres-wrap textarea{
  background:#050505 !important;
  color:#fff !important;
  border:1px solid var(--border) !important;
}

/* ================= WAIVER FIX ================= */

.gres-wrap .gres-collapse{
  background:#0b0b0d !important;
  border:1px solid var(--border) !important;
  color:#fff !important;
}

.gres-wrap .gres-collapse summary{
  color:var(--gold) !important;
  font-weight:800;
}

.gres-wrap .gres-collapse-body{
  color:#fff !important;
}

/* Kill white backgrounds inside waiver */
.gres-wrap .gres-collapse *{
  background:transparent !important;
  color:#fff !important;
}
/* =========================
   FINAL NOTICE BOX FIX
   ========================= */

.gres-wrap .gres-item-note{
  background: #0b0b0d !important;
  border: 1px solid rgba(251,176,64,.35) !important;
  border-radius: 12px;
  padding: 12px 14px;
  color: #ffffff !important;
  font-size: 14px;
  line-height: 1.5;
  opacity: 1 !important;
  box-shadow: 0 0 10px rgba(251,176,64,.15);
}

/* 3. TARGET THAT SPECIFIC MESSAGE BOX */
.gres-wrap .gres-item-note,
.gres-wrap p,
.gres-wrap div {
  color: #ffffff !important;
  opacity: 1 !important;
}

/* 4. FIX ANY HIDDEN CONTAINER */
.gres-wrap .gres-card,
.gres-wrap .gres-box,
.gres-wrap .gres-section {
  opacity: 1 !important;
  color: #ffffff !important;
}

/* 5. KEEP GOLD HEADINGS (override plugin variable system) */
.gres-wrap {
  --gres-heading-color: #FBB040 !important;
}
//* ===============================
   FIX ALL MAIN HEADINGS
================================ */

.gres-wrap h1,
.gres-wrap h2,
.gres-wrap h3 {
  color: #FBB040 !important;
  font-weight: 900 !important;
  font-size: 26px !important;
  margin-bottom: 12px !important;
  display: block !important;
  visibility: visible !important;
}

/* Add gold underline accent */
.gres-wrap h2::after,
.gres-wrap h3::after {
  content: "";
  display: block;
  width: 60px;
  height: 3px;
  background: #FBB040;
  margin-top: 6px;
  border-radius: 2px;
}

/* Remove blue highlight / selection look */
.gres-wrap h2::selection {
  background: transparent !important;
  color: #FBB040 !important;
}

/* Kill any inline highlight */
.gres-wrap h2 {
  box-shadow: none !important;
}
.gres-wrap h2{
  color:#FBB040 !important;
  font-weight:900;
  font-size:26px;
  margin-bottom:12px;
  position:relative;
}

.gres-wrap h2::after{
  content:"";
  display:block;
  width:60px;
  height:3px;
  background:#FBB040;
  margin-top:6px;
  border-radius:2px;
}
/* ===============================
   GOLDUSTERS HERO HEADER
================================ */

.g-header-wrap{
  max-width:900px;
  margin:20px auto 10px auto;
  padding:22px 20px;
  text-align:center;

  border-radius:20px;
  border:1px solid rgba(251,176,64,.35);

  background:
    radial-gradient(circle at top, rgba(251,176,64,.15), transparent 40%),
    linear-gradient(135deg,#000,#0a0a0a,#1a1206);

  box-shadow:0 15px 40px rgba(0,0,0,.5);
}

/* MAIN TITLE */
.g-header-title{
  font-size:32px;
  font-weight:900;
  color:#FBB040;
  letter-spacing:.6px;
  margin-bottom:14px;

  text-shadow:0 0 12px rgba(251,176,64,.5);
}

/* BUTTON */
.g-header-actions{
  margin-bottom:14px;
}

.g-header-btn{
  display:inline-block;
  padding:10px 18px;

  background:linear-gradient(135deg,#FBB040,#c8921a);
  color:#000 !important;

  border-radius:12px;
  font-weight:800;
  text-decoration:none;

  box-shadow:0 5px 15px rgba(251,176,64,.5);
  transition:.2s ease;
}

.g-header-btn:hover{
  transform:translateY(-2px);
  box-shadow:0 8px 22px rgba(251,176,64,.7);
}

/* DESCRIPTION */
.g-header-sub{
  color:#ffffff;
  font-size:15px;
  margin-bottom:6px;
}

/* NOTE */
.g-header-note{
  color:#dba6ff; /* slight purple highlight like your current */
  font-weight:600;
  font-size:14px;
}
.g-header-icon{
  font-size:28px;
  margin-right:8px;
  filter: drop-shadow(0 0 6px rgba(251,176,64,.6));
}
/* ===============================
   FIX CALENDAR VISIBILITY
================================ */

/* Calendar container */
.gres-calendar,
.gres-calendar table {
  background: #ffffff !important;
  color: #000000 !important;
}

/* Calendar headers (Sunâ€“Sat) */
.gres-calendar th {
  background: #f5f5f5 !important;
  color: #000 !important;
  font-weight: 700;
}

/* Calendar cells */
.gres-calendar td {
  background: #ffffff !important;
  color: #000 !important;
  border: 1px solid #ddd !important;
}

/* Calendar numbers (dates) */
.gres-calendar td span,
.gres-calendar td div {
  color: #000 !important;
}

/* Status dots text (Paid/Pending/etc) */
.gres-calendar .legend,
.gres-calendar .legend span {
  color: #fff !important; /* keep readable on dark header */
}
//* ===============================
   FIX EMPTY STATE TEXT
================================ */

.gres-empty,
.gres-no-results,
.gres-table-empty,
.gres-wrap td:empty::after {
  content: "";
  color: #000 !important;
  font-weight: 600;
}

/* If it's inside a white box */
.gres-results-container,
.gres-table-wrap {
  background: #fff !important;
  color: #000 !important;
}

/* ===============================
   FINAL CALENDAR FIX (WORKING)
================================ */

/* Force calendar cells */
.gres-calendar table td {
  background: #0b0b0b !important;
  border: 1px solid rgba(251,176,64,0.25) !important;
  position: relative;
}

/* FORCE DAY NUMBER (this is the key fix) */
.gres-calendar table td * {
  color: #ffffff !important;
  opacity: 1 !important;
}

/* Specifically target day number (common patterns) */
.gres-calendar td .day,
.gres-calendar td .date,
.gres-calendar td strong,
.gres-calendar td b,
.gres-calendar td:first-child,
.gres-calendar td::first-line {
  color: #FBB040 !important;
  font-weight: 800 !important;
}

/* Header (Sunâ€“Sat) */
.gres-calendar th {
  background: #111 !important;
  color: #FBB040 !important;
  font-weight: 800 !important;
}
/* ===============================
   FORCE SHOW MAIN HEADING (FIX)
================================ */

.gres-wrap h1,
.gres-wrap h2,
.gres-wrap h3 {
  display: block !important;
  visibility: visible !important;
  opacity: 1 !important;

  color: #FBB040 !important;
  font-weight: 900 !important;
  font-size: 28px !important;

  background: none !important;
  -webkit-text-fill-color: #FBB040 !important; /* ðŸ”¥ fixes hidden text */
}

/* Kill any Elementor or theme clipping */
.gres-wrap h2 span,
.gres-wrap h2 * {
  color: #FBB040 !important;
  -webkit-text-fill-color: #FBB040 !important;
}

/* Remove weird overlay highlight */
.gres-wrap h2::before,
.gres-wrap h2::after {
  opacity: 1 !important;
}
/* ===============================
   HARD FORCE CALENDAR VISIBILITY
================================ */

/* Target ALL tables inside reservation UI */
.gres-wrap table td {
  background: #0b0b0b !important;
  border: 1px solid rgba(251,176,64,0.25) !important;
  position: relative;
}

/* ðŸ”¥ THIS FIXES MISSING DATES */
.gres-wrap table td * {
  color: #ffffff !important;
  opacity: 1 !important;
}

/* Day numbers (top of cell) */
.gres-wrap table td:first-child,
.gres-wrap table td::first-line {
  color: #FBB040 !important;
  font-weight: 900 !important;
}

/* Headers (Sunâ€“Sat) */
.gres-wrap table th {
  background: #111 !important;
  color: #FBB040 !important;
  font-weight: 800 !important;
}

/* Fix small text inside cells */
.gres-wrap table td small,
.gres-wrap table td p {
  color: #ccc !important;
}
/* ===============================
   FIX EMPTY STATE VISIBILITY
================================ */

.gres-empty-state{
  display:block !important;
  background:#ffffff !important;   /* force visible box */
  color:#000000 !important;        /* black text as requested */
  font-weight:700;
  text-align:center;
  padding:20px;
  border-radius:12px;
  border:1px solid #ddd;
}
/* ===============================
   FORCE EMPTY STATE VISIBLE (FINAL FIX)
================================ */

.gres-empty-state{
  background:#f1f1f1 !important;
  color:#000000 !important;
  font-weight:700 !important;
  text-align:center;
  padding:18px;
  border-radius:12px;
  border:1px solid #ddd;
}

/* 🔥 FORCE ALL TEXT INSIDE TO BE BLACK */
.gres-empty-state,
.gres-empty-state *{
  color:#000000 !important;
  -webkit-text-fill-color:#000000 !important;
}
/* ===============================
   FIX COLUMN TOGGLE BAR ONLY
================================ */

/* Container */
.gres-table-tools{
  background:#ffffff !important;
  color:#000000 !important;
  border:1px solid #ddd !important;
}

/* Labels (Date/Time, Location, etc) */
.gres-table-tools label{
  background:transparent !important;
  color:#000000 !important;
  font-weight:600;
}

/* Checkboxes */
.gres-table-tools input[type="checkbox"]{
  accent-color:#FBB040 !important; /* Goldusters gold */
}

/* Kill WordPress blue highlight */
.gres-table-tools label,
.gres-table-tools input{
  box-shadow:none !important;
}

/* If anything still forcing blue */
.gres-table-tools *{
  color:#000000 !important;
  background:transparent !important;
}
/* ===============================
   FIX CARD VIEW TEXT VISIBILITY
================================ */

/* Force readable text inside cards */
#gresMyResCards .gres-res-card{
  background:#ffffff !important;
  color:#000000 !important;
}

/* Headings */
#gresMyResCards .gres-res-card h3{
  color:#000000 !important;
  font-weight:700;
}

/* Labels (Time, Resource, etc) */
#gresMyResCards .gres-res-meta .k{
  color:#666 !important;
}

/* Values */
#gresMyResCards .gres-res-meta div{
  color:#000000 !important;
}

/* Details text */
#gresMyResCards .gres-res-details{
  color:#000000 !important;
}

/* Buttons inside cards */
#gresMyResCards .button{
  color:#000 !important;
}

/* Nuclear fallback if anything still hidden */
#gresMyResCards *{
  -webkit-text-fill-color:unset !important;
}
/* ===============================
   FIX "COLUMNS" LABEL VISIBILITY
================================ */

.gres-table-tools div{
  color:#000 !important;
  font-weight:700;
}

.gres-reserved-court{
    opacity:0.45;
    filter:grayscale(100%);
}

.gres-reserved-court span{
    display:flex;
    flex-direction:column;
    align-items:center;
    gap:4px;
}

.gres-reserved-text{
    display:inline-block;
    background:#444;
    color:#fff;
    padding:3px 8px;
    border-radius:20px;
    font-size:10px;
    font-weight:700;
    text-transform:uppercase;
    line-height:1;
}

.gres-court-pill.is-disabled{
    cursor:not-allowed;
    background:#777 !important;
    border-color:#666 !important;
}

/* Also ensure checkboxes labels visible */
.gres-table-tools label{
  color:#000 !important;
}

/* ===============================
   RESERVED / UNAVAILABLE COURTS
================================ */

.gres-reserved-court{
    opacity:0.35 !important;
    pointer-events:none !important;
    filter:grayscale(100%) !important;
    background:#555 !important;
    border-color:#444 !important;
}

.gres-reserved-court span{
    color:#bdbdbd !important;
}

.gres-reserved-text{
    display:block;
    font-size:11px;
    color:#ff6b6b !important;
    margin-top:2px;
    font-weight:700;
}

.gres-court-unavailable{
    opacity:.35;
    pointer-events:none;
    filter:grayscale(100%);
}

.gres-court-reserved{
    display:block;
    color:#ff6b6b;
    font-size:11px;
    margin-top:4px;
    font-weight:700;
    text-align:center;
}

/* Fix native calendar/month picker icons */
input[type="date"]::-webkit-calendar-picker-indicator,
input[type="month"]::-webkit-calendar-picker-indicator {
    filter: invert(1) brightness(2);
    opacity: 1 !important;
    cursor: pointer;
}

/* jQuery UI datepicker arrows/icons */
.ui-datepicker .ui-datepicker-prev span,
.ui-datepicker .ui-datepicker-next span,
.ui-datepicker .ui-icon {
    filter: invert(1) brightness(3);
}

/* Force visibility */
.ui-datepicker-prev,
.ui-datepicker-next {
    opacity: 1 !important;
}

/* Always show number input spinner arrows */
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
    opacity: 1 !important;
    -webkit-appearance: inner-spin-button !important;
    margin: 0;
}

/* Fix hidden arrows in dark theme */
input[type="number"] {
    appearance: auto !important;jQuery(function($){
  'use strict';

  if (!window.GRES) return;
  var GRES = window.GRES;
  var _labels = (GRES && GRES.labels) ? GRES.labels : {};
  function L(key, fallback){
    var v = (_labels && Object.prototype.hasOwnProperty.call(_labels, key)) ? _labels[key] : '';
    if (v === null || v === undefined || v === '') return fallback;
    return v;
  }

  
  function getLocationId(){
    // Prefer explicit selector value
    var v = 0;
    var $loc = $('#gres-location');
    if($loc.length){
      v = parseInt($loc.val()||'0',10);
    }

    // Backward compat: some templates used a different id
    if(!v){
      var $loc2 = $('#gres_location');
      if($loc2.length){
        v = parseInt($loc2.val()||'0',10);
      }
    }

    // If still empty, fall back to URL param (?gres_loc=ID)
    if(!v){
      try {
        var params = new URLSearchParams(window.location.search || '');
        var p = params.get('gres_loc');
        if(p){ v = parseInt(p,10); }
      } catch(e){}
    }

    // Fall back to localized value
    if(!v && GRES && GRES.location_id) v = parseInt(GRES.location_id,10);
    if(!v) v = 1;
    return v;
  }

  function applyLocationUI(data){
    if(!data) return;
    // Update global
    if(GRES) {
      GRES.location_id = data.location_id || getLocationId();
      if(Array.isArray(data.court_types)) GRES.court_types = data.court_types;
      if(Array.isArray(data.items)) GRES.items = data.items;
    }

    // Messages
    var msg = (data.admin_message || '').toString();
    $('#gres-location-msg').html(msg);
    // Backward-compat: some templates used #gres-msg
    $('#gres-msg').html(msg);

    // Facility contact/address (optional)
    try {
      var showAddr = parseInt(data.show_address||0,10)===1;
      var lines = [];
      if(showAddr){
        var cn = (data.contact_name||'').toString().trim();
        var cp = (data.contact_phone||'').toString().trim();
        if(cn || cp){
          lines.push('<strong>Contact:</strong> ' + [cn, cp].filter(Boolean).join(' · '));
        }
        var a1 = (data.address1||'').toString().trim();
        var a2 = (data.address2||'').toString().trim();
        var city = (data.city||'').toString().trim();
        var st = (data.state||'').toString().trim();
        var zip = (data.zip||'').toString().trim();
        var country = (data.country||'').toString().trim();
        var addrParts = [];
        if(a1) addrParts.push(a1);
        if(a2) addrParts.push(a2);
        var csz = [city, st, zip].filter(Boolean).join(', ').replace(', ,', ',');
        if(csz) addrParts.push(csz);
        if(country) addrParts.push(country);
        if(addrParts.length){
          lines.push('<strong>Address:</strong> ' + addrParts.join(' · '));
        }
      }
      if(lines.length){
        $('#gres-location-contact').show().html(lines.join('<br>'));
      } else {
        $('#gres-location-contact').hide().html('');
      }
    } catch(e) {
      $('#gres-location-contact').hide().html('');
    }

    var blocked = parseInt(data.is_blocked||0,10)===1;
    if(blocked){
      $('#gres-location-block-msg').show().html((data.blocked_message||'Reservations for this location are currently unavailable.').toString());
      $('#gres-block-msg').show().html((data.blocked_message||'Reservations for this location are currently unavailable.').toString());
      $('#gres-checkout, #gres-add-block, #gres-submit-approval').prop('disabled', true);
    } else {
      $('#gres-location-block-msg').hide().html('');
      $('#gres-block-msg').hide().html('');
      $('#gres-checkout, #gres-add-block, #gres-submit-approval').prop('disabled', false);
    }

    // Reset form to avoid mixing types across locations
    if(typeof window.GRES_RESET_FORM === 'function'){
      window.GRES_RESET_FORM();
    }
  }

function gresParseDate(val){
    if(!val) return null;
    var parts = val.split('/');
    if(parts.length===3){
      var m=parseInt(parts[0],10)-1, d=parseInt(parts[1],10), y=parseInt(parts[2],10);
      if(!isNaN(m)&&!isNaN(d)&&!isNaN(y)){
        var dt=new Date(y,m,d);
        if(dt.getFullYear()===y && dt.getMonth()===m && dt.getDate()===d){ dt.setHours(0,0,0,0); return dt; }
      }
    }
    // try ISO
    var t=Date.parse(val);
    if(!isNaN(t)){ var dt2=new Date(t); dt2.setHours(0,0,0,0); return dt2; }
    return null;
  }
  function gresAddMonths(dt, m){ var d=new Date(dt.getTime()); d.setMonth(d.getMonth()+m); return d; }
  function gresDateOk(dateVal){
    var dt=gresParseDate(dateVal);
    if(!dt) return true;
    var today=new Date(); today.setHours(0,0,0,0);
    if(dt < today) return false;
    var maxM = (GRES && GRES.settings) ? parseInt(GRES.settings.max_months_ahead||6,10) : 6;
    if(!maxM||maxM<1) maxM=6;
    var maxDate=gresAddMonths(today, maxM);
    if(dt > maxDate) return false;
    return true;
  }


  const $blocks = $('#gres-blocks');
  const $summary = $('#gres-summary');
  const $total = $('#gres-total');
  const $msg = $('#gres-msg');

  // Inline field error helpers (global fields)
  function clearFieldErrorById(id){
    const $inp = $('#'+id);
    if($inp.length){
      $inp.closest('div').find('.gres-field-error').hide().text('');
    }
  }
  function showFieldErrorById(id, message){
    const msg = (message||'').toString().trim();
    const $inp = $('#'+id);
    if(!$inp.length || !msg) return;
    const $err = $inp.closest('div').find('.gres-field-error');
    if($err.length){
      $err.text(msg).show();
    }
  }

  let itemAvailability = {}; // { [itemId]: {configured_qty:number, available_qty:number} }

  
  // Age requirement support (DOB + guardian fields)
  function parseDateOnly(val){
    if(!val) return null;
    // Expect YYYY-MM-DD from <input type="date">
    const m = String(val).match(/^(\d{4})-(\d{2})-(\d{2})$/);
    if(!m) return null;
    const y = parseInt(m[1],10), mo=parseInt(m[2],10), d=parseInt(m[3],10);
    const dt = new Date(Date.UTC(y, mo-1, d));
    if(isNaN(dt.getTime())) return null;
    return {y, mo, d, dt};
  }

  function calcAgeYears(dob){
    if(!dob) return null;
    const now = new Date();
    let age = now.getUTCFullYear() - dob.y;
    const mNow = now.getUTCMonth() + 1;
    const dNow = now.getUTCDate();
    if(mNow < dob.mo || (mNow === dob.mo && dNow < dob.d)) age--;
    return age;
  }

  function isMinor(){
    const s = (GRES.settings||{});
    const enableAge = parseInt(s.enable_age_requirement||0,10) === 1;
    if(!enableAge) return false;
    const v = $('input[name="gres-is-minor"]:checked').val();
    return v === 'yes';
  }

  function applyAgeUi(){
    const s = (GRES.settings||{});
    const enableAge = parseInt(s.enable_age_requirement||0,10) === 1;
    const enableWaiver = parseInt(s.enable_waiver||0,10) === 1;

    if(!enableAge){
      $('#gres-dob-wrap').hide();
      $('#gres-minor-q-wrap').hide();
      $('#gres-guardian-wrap').hide();
      $('#gres-dob').prop('required', false);
      $('input[name="gres-is-minor"]').prop('required', false).prop('checked', false);
      $('#gres-guardian-name,#gres-guardian-relationship,#gres-guardian-email,#gres-guardian-phone').prop('required', false);
      // Ensure adult waiver is shown if waiver enabled
      if(enableWaiver){
        $('#gres-waiver-minor-text').hide().empty();
        $('#gres-waiver-adult-text').show();
        $('#gres-waiver-ack-label').text('I/we have read and acknowledge this waiver.');
      }
      return;
    }

    // Age requirement ON: show Minor question first.
    // DOB should ONLY show if they answer YES to "Are you a minor?"
    $('#gres-minor-q-wrap').show();
    $('input[name="gres-is-minor"]').prop('required', true);

    const minor = isMinor();

    if(minor){
      $('#gres-dob-wrap').show();
      $('#gres-dob').prop('required', true);
    } else {
      $('#gres-dob-wrap').hide();
      $('#gres-dob').prop('required', false).val('');
      $('#gres-dob-note').text('');
    }

    // Age note (informational only) - only meaningful if DOB is present
    const dob = minor ? parseDateOnly($('#gres-dob').val()) : null;
    const age = calcAgeYears(dob);
    const minorAge = parseInt(s.minor_age||18,10);
    if(dob && age !== null){
      $('#gres-dob-note').text(age < 0 ? '' : `Age: ${age} (Minor age threshold: ${minorAge})`);
    } else {
      $('#gres-dob-note').text('');
    }

    // Guardian fields only if they answered YES
    if(minor){
      $('#gres-guardian-wrap').show();
      $('#gres-guardian-name,#gres-guardian-relationship,#gres-guardian-email,#gres-guardian-phone').prop('required', true);
    } else {
      $('#gres-guardian-wrap').hide();
      $('#gres-guardian-name,#gres-guardian-relationship,#gres-guardian-email,#gres-guardian-phone').prop('required', false).val('');
    }

    // Waiver switch only if YES selected
    if(enableWaiver){
      if(minor){
        const useShort = parseInt(s.use_minor_short_on_mobile||0,10) === 1;
        const isMobile = window.matchMedia && window.matchMedia('(max-width: 600px)').matches;
        let minorHtml = (s.minor_waiver_text && String(s.minor_waiver_text).trim()) ? String(s.minor_waiver_text) : String(s.waiver_text||'');
        if(useShort && isMobile){
          const sh = (s.minor_waiver_short_text && String(s.minor_waiver_short_text).trim()) ? String(s.minor_waiver_short_text) : '';
          if(sh) minorHtml = sh;
        }
        $('#gres-waiver-minor-text').html(minorHtml).show();
        $('#gres-waiver-adult-text').hide();
        $('#gres-waiver-ack-label').text('I am the parent/legal guardian and I acknowledge this waiver on the minor’s behalf.');
      } else {
        $('#gres-waiver-minor-text').hide().empty();
        $('#gres-waiver-adult-text').show();
        $('#gres-waiver-ack-label').text('I/we have read and acknowledge this waiver.');
      }
    }
  }



  
  function applyTimeWindow($block){
    const $sel = $block.find('.gres-type');
    const $opt = $sel.find('option:selected');
    const wsRaw = ($opt.data('window-start') || '').toString().trim();
    const weRaw = ($opt.data('window-end') || '').toString().trim();

    const ws = (wsRaw.match(/^\d{2}:\d{2}(:\d{2})?$/) ? wsRaw.substring(0,5) : '06:00');
    const we = (weRaw.match(/^\d{2}:\d{2}(:\d{2})?$/) ? weRaw.substring(0,5) : '22:00');

    const toMin = (hhmm)=>{
      const m = String(hhmm||'').match(/^(\d{2}):(\d{2})$/);
      if(!m) return null;
      return parseInt(m[1],10)*60 + parseInt(m[2],10);
    };

    const minMin = toMin(ws);
    const maxMin = toMin(we);

    const $start = $block.find('.gres-start');
    if(!$start.length || minMin===null || maxMin===null) return;

    // Disable start-time options outside window
    $start.find('option').each(function(){
      const v = ($(this).val()||'').toString().trim();
      const vv = toMin(v);
      if(vv===null){ $(this).prop('disabled', false).show(); return; }
      const ok = (vv >= minMin) && (vv < maxMin); // start must be before window end
      $(this).prop('disabled', !ok);
      $(this).toggle(ok);
    });

    // If currently selected is invalid, clear it
    const cur = ($start.val()||'').toString().trim();
    const curMin = toMin(cur);
    if(curMin===null || curMin < minMin || curMin >= maxMin){
      $start.val('');
    }
  }

function resetForm(){
    // Clear contact fields
    $('#gres-first').val('');
    $('#gres-last').val('');
    $('#gres-email').val('');
    $('#gres-phone').val('');
    // Clear DOB/guardian
    $('#gres-dob').val('');
    $('#gres-guardian-name').val('');
    $('#gres-guardian-relationship').val('');
    $('#gres-guardian-email').val('');
    $('#gres-guardian-phone').val('');
    // Reset items
    $('.gres-item-qty').val('0');
    $('.gres-item-hours').val('1');
    // Reset waiver
    $('#gres-waiver-ack').prop('checked', false);
    // Remove all blocks and recreate first
    $blocks.empty();
    blockIndex = 0;
    newBlock();
    // Clear messages/summary
    $msg.text('');
    applyAgeUi();
  }
  window.GRES_RESET_FORM = resetForm;

  function getTypeById(id){
    id = parseInt(id,10);
    return (GRES.court_types||[]).find(t=>parseInt(t.id,10)===id) || null;
  }

  function approvalSelectedType(){
    let found = null;
    let reason = '';
    $('.gres-block').each(function(){
      const $blk = $(this);
      // Force approval (e.g., booking beyond normal window)
      if(parseInt($blk.data('forceApproval')||0,10) === 1){
        found = found || { approval_required: 1, approval_message: '' };
        const r = ($blk.data('approvalReason')||'').toString().trim();
        if(r && !reason) reason = r;
        return;
      }
      const tid = parseInt($blk.find('.gres-type').val()||'0',10);
      if(!tid) return;
      const t = getTypeById(tid);
      if(t && parseInt(t.approval_required||0,10) === 1){
        found = t;
        const msg = (t.approval_message||'').toString().trim();
        if(msg) reason = msg;
      }
    });
    if(found && reason){
      found = Object.assign({}, found, { approval_message: reason });
    }
    return found;
  }

  function applyApprovalMode(){
    const t = approvalSelectedType();
    const $add = $('#gres-add-block');
    const $checkout = $('#gres-checkout');
    const $submit = $('#gres-approval-submit');
    const $amsg = $('#gres-approval-msg');

    if(t){
      // enforce single block
      const $allBlocks = $('.gres-block');
      if($allBlocks.length > 1){
        $allBlocks.slice(1).remove();
      }

      $add.hide();
      $checkout.hide();
      $submit.show();

      const msg = (t.approval_message||'').toString().trim();
      if(msg){
        $amsg.text(msg).show();
      } else {
        $amsg.hide().text('');
      }
    } else {
      $add.show();
      $checkout.show();
      $submit.hide();
      $amsg.hide().text('');
    }
  }

let blockIndex = 0;

  // Blockouts hidden by default
  window.GRES_BLOCKOUTS_VISIBLE = false;

  // Calendar toggle (default hidden; button swaps text)
  function initCalendarToggle(){
    const $btn = $('#gres-toggle-cal');
    const $panel = $('#gres-cal-panel');
    const $boBtn = $('#gres-toggle-blockouts');
    if (!$btn.length || !$panel.length) return; // admin disabled or not on page

    $panel.hide(); // default hidden
    $btn.text(L('btn_view_calendar','View Calendar'));

    if ($boBtn.length) {
      $boBtn.hide();
      $boBtn.text('View Blockout Times');
    }

    $btn.off('click.gresCal').on('click.gresCal', function(){
      const willShow = !$panel.is(':visible');

      if (willShow) {
        $panel.show();
        $btn.text('Hide Calendar');

        if ($boBtn.length) {
          // reset blockouts hidden each time calendar is shown
          window.GRES_BLOCKOUTS_VISIBLE = false;
          $boBtn.text('View Blockout Times').show();
          setTimeout(function(){ $('#gres-cal').find('.gres-blockout').hide(); }, 250);
        }
      } else {
        $panel.hide();
        $btn.text(L('btn_view_calendar','View Calendar'));

        if ($boBtn.length) {
          window.GRES_BLOCKOUTS_VISIBLE = false;
          $boBtn.text('View Blockout Times').hide();
        }
      }
    });
  }



  
  // Toggle visibility of blockout entries inside the calendar
  function applyBlockoutVisibility(show){
    const $cal = $('#gres-cal');
    if(!$cal.length) return;
    if(show){
      $cal.find('.gres-blockout').show();
    } else {
      $cal.find('.gres-blockout').hide();
    }
  }

function initBlockoutToggle(){
    const $btn = $('#gres-toggle-blockouts');
    if(!$btn.length) return; // admin disabled
    // default hidden until calendar visible
    $btn.hide();
    $btn.text('View Blockout Times');
    window.GRES_BLOCKOUTS_VISIBLE = false;
    $btn.off('click.gresBO').on('click.gresBO', function(){
      window.GRES_BLOCKOUTS_VISIBLE = !window.GRES_BLOCKOUTS_VISIBLE;
      applyBlockoutVisibility(window.GRES_BLOCKOUTS_VISIBLE);
      $btn.text(window.GRES_BLOCKOUTS_VISIBLE ? 'Hide Blockout Times' : 'View Blockout Times');
    });
  }

  function money(n){ return '$' + (Math.round(n*100)/100).toFixed(2); }

  // UI-only time helpers (display AM/PM, keep values as HH:MM for server logic)
  function pad2(n){ n = parseInt(n,10); return (n<10?'0':'') + n; }

  function formatTimeLabel(hhmm){
    if(!hhmm) return '';
    const m = /^([0-9]{1,2}):([0-9]{2})$/.exec(String(hhmm).trim());
    if(!m) return String(hhmm);
    let h = parseInt(m[1],10);
    const min = m[2];
    const ampm = (h >= 12) ? 'PM' : 'AM';
    h = h % 12; if(h === 0) h = 12;
    return `${h}:${min} ${ampm}`;
  }

    // Client-side end-time preview so End Time stays correct immediately when
    // Start Time / Hours changes (even before the AJAX availability call returns).
    function gresComputeEndTimeLabel(startHHMM, hours){
      if(!startHHMM) return '';
      const m = /^([0-2]\d):([0-5]\d)$/.exec(String(startHHMM).trim());
      if(!m) return '';
      const startH = parseInt(m[1], 10);
      const startM = parseInt(m[2], 10);
      const hrs = parseFloat(hours);
      if(isNaN(hrs) || hrs <= 0) return '';
      const addMin = Math.round(hrs * 60);
      let total = (startH * 60) + startM + addMin;
      // Keep within 0-1439 for display; reservation creation should prevent crossing days.
      total = ((total % 1440) + 1440) % 1440;
      const endH24 = Math.floor(total / 60);
      const endM = total % 60;
      const endHHMM = String(endH24).padStart(2,'0') + ':' + String(endM).padStart(2,'0');
      return formatTimeLabel(endHHMM);
    }

    function gresUpdateEndTimePreview($block){
      if(!$block || !$block.length) return;
      const start = $block.find('.gres-start').val();
      const hours = $block.find('.gres-hours').val();
      const label = gresComputeEndTimeLabel(start, hours);
      if(label){
        // End time input is rendered as .gres-end
        $block.find('.gres-end').val(label);
      }
    }

  function buildTimeOptions(stepMinutes){
    const step = parseInt(stepMinutes||30,10);
    const out = [];
    // default window: 5:00 AM to 11:00 PM (covers most clubs); values remain 24h HH:MM
    for(let minutes = 5*60; minutes <= 23*60; minutes += step){
      const hh = Math.floor(minutes/60);
      const mm = minutes % 60;
      const value = `${pad2(hh)}:${pad2(mm)}`;
      const label = formatTimeLabel(value);
      out.push(`<option value="${value}">${label}</option>`);
    }
    return out.join('');
  }

  function newBlock(){
    const idx = blockIndex++;
    const html = `
      <div class="gres-card gres-block" data-idx="${idx}">
        <div class="gres-block-head">
          <h4>Reservation ${idx+1}</h4>
          <button type="button" class="button gres-remove" ${idx===0 ? 'style="display:none;"' : ''}>Remove</button>
        </div>
        <div class="gres-grid">
          <div><label>Date</label><input class="gres-date" type="date" required><div class="gres-field-error" data-field="date"></div></div>
          <div>
            <label>${L('field_court_type','Court Type')}</label>
            <select class="gres-type" required>
              <option value="">Select...</option>
              ${GRES.court_types.map(t=>`<option value="${t.id}" data-price="${t.price}" data-prefix="${t.prefix}" data-window-start="${t.window_start||''}" data-window-end="${t.window_end||''}">${t.name} ($${Number(t.price).toFixed(2)}/hr)</option>`).join('')}
            </select>
            <div class="gres-field-error" data-field="type"></div>
          </div>
          <div><label>${L('field_start_time','Start Time')}</label><select class="gres-start" required>${buildTimeOptions(30)}</select><div class="gres-field-error" data-field="start"></div></div>
          <div>
            <label>${L('field_available','Available')}</label>
            <div class="gres-courts"></div>
            <div class="gres-sug-toggle" style="margin-top:6px;">
              <button type="button" class="button button-small gres-sug-show">Show time suggestions</button>
            </div>
            <div class="gres-suggestions" style="display:none"></div>
          </div>
          <div><label>Hours</label><input class="gres-hours" type="number" min="0.5" step="0.5" value="1" required><div class="gres-field-error" data-field="hours"></div></div>
          <div><label>${L('field_end_time','End Time')}</label><input class="gres-end" type="text" readonly></div>
        </div>
        <div class="gres-rules"></div>
        <div class="gres-block-foot">
          <div class="gres-line">Rate: <span class="gres-rate">$0.00</span> • Line Total: <strong class="gres-line-total">$0.00</strong></div>
        </div>
      </div>`;
    $blocks.append(html);
    const $nb = $blocks.find(`.gres-block[data-idx="${idx}"]`);
    bindBlock($nb);
    applyTimeWindow($nb);
      gresUpdateEndTimePreview($nb);
    updateOtherItemsVisibility();
    renderSummary();
    refreshItemsAvailability();
  }

  
  function renderCourtRules($b){
    const s = (GRES.settings||{});
    const enableRules = parseInt(s.enable_court_rules||0,10) === 1;
    const $wrap = $b.find('.gres-rules');
    if(!$wrap.length){ return; }
    if(!enableRules){
      $wrap.empty().hide();
      return;
    }
    const typeId = parseInt($b.find('.gres-type').val()||'0',10);
    const t = getTypeById(typeId);
    const ruleHtml = (t && (t.court_rule||t.court_rules||t.rule||'')) ? String(t.court_rule||t.court_rules||t.rule||'') : '';
    if(!typeId){
      $wrap.empty().hide();
      return;
    }
    $wrap.show();
    if(!ruleHtml.trim()){
      $wrap.html(`<div class="gres-legal-missing"><strong>${L('label_rules','Rules of use')}:</strong> Rules are not set for this court type. Please contact the organizer.</div>`);
      return;
    }
    const idx = $b.data('idx');
    const ackId = `gres-rules-ack-${idx}`;
    $wrap.html(`
      <details class="gres-collapse">
        <summary><strong>${L('label_rules','Rules of use')}</strong> (Required)</summary>
        <div class="gres-collapse-body">
          <div class="gres-legal-text">${ruleHtml}</div>
          <label class="gres-ack"><input type="checkbox" class="gres-rules-ack" id="${ackId}"> I/we have read and will comply with these rules.</label>
        </div>
      </details>
    `);
  }

function bindBlock($b){
    // Inline per-field errors (red text under the field)
    function clearBlockErrors(){
      $b.find('.gres-field-error').hide().text('');

    }

    function showFieldError(field, message){
      const msg = (message||'').toString().trim();
      if(!msg) return;
      const $err = $b.find('.gres-field-error[data-field="'+field+'"]');
      if($err.length){
        $err.text(msg).show();
      }
    }

    // Safety: even if a user clicks a disabled label, never allow selecting an unavailable court.
    $b.on('click', '.gres-court-pill.is-disabled', function(e){
      // Extra safety: never allow selecting an unavailable court
      return false;
      e.preventDefault();
      e.stopPropagation();
      return false;
    });

      // Apply a suggestion (Phase 3A-1)
      function to24h(amPm){
        // Expect "h:mm AM" or "hh:mm PM"
        const s = String(amPm||'').trim();
        const m = /^(\d{1,2}):(\d{2})\s*(AM|PM)$/i.exec(s);
        if(!m) return '';
        let h = parseInt(m[1],10);
        const mm = m[2];
        const ap = m[3].toUpperCase();
        if(ap === 'PM' && h < 12) h += 12;
        if(ap === 'AM' && h === 12) h = 0;
        return String(h).padStart(2,'0') + ':' + mm;
      }

      $b.on('click', '.gres-sug-btn', function(){
        const $btn = $(this);
        const d = ($btn.data('date')||'').toString();
        const st = ($btn.data('start')||'').toString();
        const h = ($btn.data('hours')||'').toString();
        const cn = ($btn.data('court')||'').toString();
        if(d) $b.find('.gres-date').val(d);
        const st24 = to24h(st);
        if(st24) $b.find('.gres-start').val(st24);
        if(h) $b.find('.gres-hours').val(h);
        if(cn) $b.data('selectedCourt', cn);
        // Trigger the same flow as a user change
        $b.find('.gres-date').trigger('change');
      });

     $b.on('click', '.gres-sug-show', function(){

    const typeId = parseInt(
        $b.find('.gres-type').val() || '0',
        10
    );

  const dateRaw = $b.find('.gres-date').val();

const date = (
    dateRaw &&
    dateRaw !== 'mm/dd/yyyy'
)
? dateRaw.trim()
: '';

    const start = $b.find('.gres-start').val();

    const hours = parseFloat(
        $b.find('.gres-hours').val() || '1'
    );

console.log({
    typeId,
    date,
    start,
    hours
});

    const $sug = $b.find('.gres-suggestions');

    if(!typeId || !date || !start || !hours){

        $sug
            .show()
            .html('<div class="gres-sug-empty">Please select Date, Court Type, Start Time, and Hours first.</div>');

        return;
    }

    gresFetchSuggestions(
        $sug,
        typeId,
        date,
        start,
        hours,
        true
    );

});

    $b.on('click', '.gres-remove', function(){
      $b.remove();
      updateOtherItemsVisibility();
      refreshItemsAvailability();
      renderSummary();
    });

        function refreshCourts(){
      clearBlockErrors();
     const date = $b.find('.gres-date').val();
const start = $b.find('.gres-start').val();
const typeId = $b.find('.gres-type').val();
const hours = parseFloat($b.find('.gres-hours').val() || '0');

if(!date || !start || !typeId || !hours){
    return;
}

if(isNaN(hours) || hours <= 0){
    return;
}

/* DEBUG + SAFETY */
const startDate = new Date(date + 'T' + start + ':00');

const endDate = new Date(startDate.getTime());

endDate.setMinutes(
    endDate.getMinutes() + (hours * 60)
);

function sqlDateTime(dt){

    const y = dt.getFullYear();

    const m = String(dt.getMonth() + 1)
        .padStart(2, '0');

    const d = String(dt.getDate())
        .padStart(2, '0');

    const h = String(dt.getHours())
        .padStart(2, '0');

    const i = String(dt.getMinutes())
        .padStart(2, '0');

    const s = String(dt.getSeconds())
        .padStart(2, '0');

    return `${y}-${m}-${d} ${h}:${i}:${s}`;
}

const start_datetime = sqlDateTime(startDate);

const end_datetime = sqlDateTime(endDate);

console.log('START:', start_datetime);
console.log('END:', end_datetime);

console.log('START DATE:', startDate);
console.log('END DATE:', endDate);

$b.addClass('gres-loading');

$.post(GRES.ajax_url, {

    action: 'gres_available_courts',

    nonce: GRES.nonce,

    location_id: getLocationId(),

    court_type_id: typeId,

    date: date,

    start_time: start,

    hours: hours,

    start_datetime: start_datetime,

    end_datetime: end_datetime
    
}).done(function(resp){
        if(!resp || !resp.success){
          const m = (resp && resp.data && resp.data.message) ? resp.data.message : 'Could not load courts.';
          // Date/time validation errors should appear under Start Time.
          showFieldError('start', m);
          $b.removeClass('gres-loading');
          return;
        }

        const courts = resp.data.courts || [];
        const endTime = resp.data.end_time || '';
        const rate = parseFloat(resp.data.rate || 0);

        $b.find('.gres-end').val(endTime);
        $b.find('.gres-rate').text(money(rate));

const $c = $b.find('.gres-courts');

$c.empty();

let html = '';

courts.forEach(function(c){

   const disabled = !!c.disabled;

    html += `
    <label class="gres-court-pill ${disabled ? 'gres-court-unavailable' : ''}">

       <input
    type="radio"
    name="court_${$b.data('idx')}"
    value="${c.number}"
    ${disabled ? 'disabled' : ''}
>

        <span>
            ${c.code}

            ${
                disabled
                ? '<small class="gres-court-reserved">Reserved</small>'
                : ''
            }

        </span>

    </label>
    `;
});

$c.html(html);

        // Enforce previously selected court (if any) ONLY if it's still available
        const prevSel = ($b.data('selectedCourt')||'').toString();
        if(prevSel){
          const $inp = $c.find('input[type=radio][value="'+prevSel+'"]');
          if($inp.length && !$inp.is(':disabled')){
            $inp.prop('checked', true);
          } else {
            $b.removeData('selectedCourt');
          }
        }

        // If no courts are available, show availability suggestions (Phase 3A-1)
        const hasAvail = courts.some(ct => (ct && (ct.available === true || ct.available === 1 || ct.available === '1' || ct.available === 'true')));

        function gresFetchSuggestions($sug, typeId, date, start, hours, hasAvail){
          if(!$sug || !$sug.length) return;
          $sug.show().html(
            `<div><strong>${hasAvail ? 'Alternative options' : 'No courts are available'}</strong> for the selected time. Here are the closest available options:</div>
             <div class="gres-sug-list" style="margin-top:8px; display:flex; flex-direction:column; gap:6px;"></div>`
          );
          const $list = $sug.find('.gres-sug-list');

          $.post(GRES.ajax_url, {
            action: 'gres_availability_suggestions',
            nonce: GRES.nonce,
            location_id: getLocationId(),
            court_type_id: typeId,
            date: date,
           start_time: start,
            hours: hours
          }).done(function(r2){
            if(!r2 || !r2.success){
              $list.html(`<div class="gres-sug-empty">${(r2 && r2.data && r2.data.message) ? String(r2.data.message) : 'No suggestions found.'}</div>`);
              return;
            }
            const sug = (r2.data && r2.data.suggestions) ? r2.data.suggestions : [];
            if(!Array.isArray(sug) || !sug.length){
              $list.html('<div class="gres-sug-empty">No suggestions found.</div>');
              return;
            }
            sug.forEach(function(s){
              const label = (s && s.label) ? String(s.label) : '';
              const d = (s && s.date) ? String(s.date) : '';
              const st = (s && s.start_time) ? String(s.start_time) : '';
              const h = (s && s.hours) ? String(s.hours) : '';
              const cn = (s && s.court_number) ? String(s.court_number) : '';
              const btn = $(`<button type="button" class="button gres-sug-btn" data-date="${d}" data-start="${st}" data-hours="${h}" data-court="${cn}">${label}</button>`);
              $list.append(btn);
            });
          }).fail(function(xhr){
            var msg = 'Suggestions request failed.';
            try {
              if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                msg = String(xhr.responseJSON.data.message);
              }
            } catch(e){}
            $list.html('<div class="gres-sug-empty">' + msg + '</div>');
          });
        }

        // Auto-show suggestions if no courts are available
        const forceSug = !!$b.data('forceSuggestions');
        if((!hasAvail || forceSug) && $sug.length){
          gresFetchSuggestions($sug, typeId, date, start, hours, hasAvail);
          if(forceSug) $b.data('forceSuggestions', 0);
        }

        // Auto-select the first available court (reduces "Add at least one court reservation" errors)
        // unless the user already selected a court previously.
        const selectedNow = $c.find('input[type=radio]:checked').val();
        if(!selectedNow){
          const $firstAvail = $c.find('input[type=radio]:not(:disabled)').first();
          if($firstAvail.length){
            $firstAvail.prop('checked', true);
            $b.data('selectedCourt', $firstAvail.val());
          }
        } else {
          $b.data('selectedCourt', selectedNow);
        }

        $b.removeClass('gres-loading');
        updateOtherItemsVisibility();
        refreshItemsAvailability();
        renderSummary();
      }).fail(function(xhr){
        $b.removeClass('gres-loading');
        showFieldError('start', 'Could not load courts.');
      });
    }

    // expose per-block refresh for global rechecks (e.g., checkout conflict)
    $b.data('refreshCourtsFn', refreshCourts);


    function updateLineTotal(){
      const typeId = $b.find('.gres-type').val();
      const hours = parseFloat($b.find('.gres-hours').val() || '0');
      const $opt = $b.find('.gres-type option:selected');
      const rate = parseFloat($opt.data('price') || 0);
      const line = rate * hours;
      $b.find('.gres-line-total').text(money(line));
      renderSummary();
    }

    $b.on('change', '.gres-date,.gres-start,.gres-type', function(){
      refreshCourts();
      updateOtherItemsVisibility();
      updateLineTotal();
      refreshItemsAvailability();
      applyApprovalMode();
      applyTimeWindow($b);
      gresUpdateEndTimePreview($b);
      renderCourtRules($b);
    });

    $b.on('change', '.gres-hours', function(){
      refreshCourts();
      updateOtherItemsVisibility();
      updateLineTotal();
      refreshItemsAvailability();
      applyApprovalMode();
      gresUpdateEndTimePreview($b);
    });

    // Also update the preview when hours is typed (not only on change/blur).
    $b.on('input', '.gres-hours', function(){
      gresUpdateEndTimePreview($b);
      // Debounced refresh so End Time + availability stay synced even if user doesn't blur.
      clearTimeout($b.data('gresHoursDebounce')||0);
      const t = setTimeout(function(){ refreshCourts(); updateLineTotal(); refreshItemsAvailability(); }, 250);
      $b.data('gresHoursDebounce', t);
    });

    // Clear inline errors when user edits date/time/type/hours
    $b.on('change input', '.gres-date,.gres-start,.gres-type,.gres-hours', function(){
      $(this).closest('div').find('.gres-field-error').hide().text('');
    });

    $b.on('change', '.gres-courts input[type=radio]', function(){
      $b.data('selectedCourt', $(this).val());
      renderSummary();
    });
    // Expose a refresh function for external callers (e.g., after checkout conflict)
    $b.data('refreshCourtsFn', refreshCourts);
  }


  function validateLegal(payload){
    const s = (GRES.settings||{});
    const enableRules = parseInt(s.enable_court_rules||0,10) === 1;
    const enableWaiver = parseInt(s.enable_waiver||0,10) === 1;

    const enableAge = parseInt(s.enable_age_requirement||0,10) === 1;
    if(enableAge && !$('body').hasClass('wp-admin')){
      const dobVal = ($('#gres-dob').val() || '').trim();
      const dob = parseDateOnly(dobVal);
      if(!dob){
        $msg.text('Please enter a valid Date of Birth.');
        const $w = $('#gres-dob-wrap');
        if($w.length) $('html,body').animate({scrollTop: $w.offset().top - 20}, 300);
        return false;
      }
      const age = calcAgeYears(dob);
      const minorAge = parseInt(s.minor_age||18,10);
      if(age === null || age < 0 || age > 120){
        $msg.text('Please enter a valid Date of Birth.');
        const $w = $('#gres-dob-wrap');
        if($w.length) $('html,body').animate({scrollTop: $w.offset().top - 20}, 300);
        return false;
      }
      const v = $('input[name="gres-is-minor"]:checked').val();
      if(!v){
        $msg.text('Please answer: Are you a minor?');
        const $w = $('#gres-minor-q-wrap');
        if($w.length) $('html,body').animate({scrollTop: $w.offset().top - 20}, 300);
        return false;
      }
      const minor = (v === 'yes');
      if(minor){
        const $gName = $('#gres-guardian-name');
        const $gRel  = $('#gres-guardian-relationship');
        const $gEmail= $('#gres-guardian-email');
        const $gPhone= $('#gres-guardian-phone');

        const gName = ($gName.val() || '').trim();
        let gRel  = ($gRel.val() || '').trim();
        let gEmail= ($gEmail.val() || '').trim();
        let gPhone= ($gPhone.val() || '').trim();

        // Best-effort defaults to reduce friction (still validates)
        if(!gRel){ gRel = 'Parent / Legal Guardian'; $gRel.val(gRel); }
        if(!gEmail){
          const uEmail = ($('#gres-email').val() || '').trim();
          if(uEmail){ gEmail = uEmail; $gEmail.val(uEmail); }
        }
        if(!gPhone){
          const uPhone = ($('#gres-phone').val() || '').trim();
          if(uPhone){ gPhone = uPhone; $gPhone.val(uPhone); }
        }

        if(!gName || !gRel || !gEmail || !gPhone){
          $msg.text('Guardian information is required for minors (name, relationship, email, phone).');
          const $gw = $('#gres-guardian-wrap');
          if($gw.length) $('html,body').animate({scrollTop: $gw.offset().top - 20}, 300);
          return false;
        }
      }
    }

    if(enableRules){
      // Ensure each block has rules set and acknowledged
      const blocks = $blocks.find('.gres-block');
      let bad = null;
      blocks.each(function(i){
        const $b = $(this);
        const typeId = parseInt($b.find('.gres-type').val()||'0',10);
        if(!typeId) return;
        const t = getTypeById(typeId);
        const ruleHtml = (t && (t.court_rule||t.court_rules||t.rule||'')) ? String(t.court_rule||t.court_rules||t.rule||'') : '';
        if(!ruleHtml.trim()){
          bad = {msg:'Court rules are not set for the selected court type. Please choose a different court type or contact the organizer.', el:$b};
          return false;
        }
        const ack = $b.find('.gres-rules-ack').length ? $b.find('.gres-rules-ack').is(':checked') : false;
        if(!ack){
          bad = {msg:'Please acknowledge the court rules for each reservation.', el:$b};
          return false;
        }
      });
      if(bad){
        $msg.text(bad.msg);
        $('html,body').animate({scrollTop: bad.el.offset().top - 20}, 300);
        return false;
      }
    }

    if(enableWaiver){
      if(!$('#gres-waiver-ack').is(':checked')){
        $msg.text('Please acknowledge the waiver before submitting.');
        const $card = $('#gres-waiver-card');
        if($card.length) $('html,body').animate({scrollTop: $card.offset().top - 20}, 300);
        return false;
      }
    }
    return true;
  }

function collectPayload(){
    const blocks = [];
    $blocks.find('.gres-block').each(function(){
      const $b = $(this);
      const date = $b.find('.gres-date').val();
      const start_time = $b.find('.gres-start').val();
      const court_type_id = parseInt($b.find('.gres-type').val() || '0', 10);
      const hours = parseFloat($b.find('.gres-hours').val() || '0');
      const rawCourtVal = ($b.find('.gres-courts input:checked').val() || '').toString().trim();
      // Some installs may send values like "DH1" instead of "1"
      let court_number = parseInt(rawCourtVal || '0', 10);
      if(Number.isNaN(court_number) || court_number <= 0){
        const m = rawCourtVal.match(/(\d+)$/);
        court_number = m ? parseInt(m[1],10) : 0;
      }
      // Prefer visible court code text (e.g., "DH1") for emails/admin display if needed
      const court_code = $b.find('.gres-courts input:checked').closest('label').find('span').text().trim() || rawCourtVal;

      if(date && start_time && court_type_id && hours && court_number){
        blocks.push({date, start_time, court_type_id, hours, court_number, court_code});
      }
    });
    // Sort blocks: date, reservation type (court code/prefix), then start time
    blocks.sort(function(a,b){
      const ad = (a.date||''); const bd=(b.date||'');
      if(ad < bd) return -1;
      if(ad > bd) return 1;

      const ac = (a.court_code||'').toString();
      const bc = (b.court_code||'').toString();
      if(ac < bc) return -1;
      if(ac > bc) return 1;

      const at = (a.start_time||''); const bt=(b.start_time||'');
      if(at < bt) return -1;
      if(at > bt) return 1;
      return 0;
    });



    const items = [];
    $('.gres-item-qty').each(function(){
      const id = parseInt($(this).data('item-id'),10);
      const qty = parseInt($(this).val()||'0',10);
      const $h = $(`.gres-item-hours[data-item-id="${id}"]`);
      const hours = $h.length ? parseFloat($h.val()||'0') : 0;
      if(id && qty>0){
        const safeHours = (!hours || hours<=0) ? 0 : hours;
        items.push({id, qty, hours: safeHours});
      }
    });

        const waiver_ack = $('#gres-waiver-ack').length ? $('#gres-waiver-ack').is(':checked') : true;
    const rules_acks = [];
    $blocks.find('.gres-block').each(function(){
      const $b = $(this);
      const typeId = parseInt($b.find('.gres-type').val()||'0',10);
      const ack = $b.find('.gres-rules-ack').length ? $b.find('.gres-rules-ack').is(':checked') : true;
      rules_acks.push({court_type_id:typeId, acknowledged: !!ack});
    });

    const dob = $('#gres-dob').length ? ($('#gres-dob').val() || '').trim() : '';
    const guardian = {
      name: ($('#gres-guardian-name').val() || '').trim(),
      relationship: ($('#gres-guardian-relationship').val() || '').trim(),
      email: ($('#gres-guardian-email').val() || '').trim(),
      phone: ($('#gres-guardian-phone').val() || '').trim(),
    };
    const minor = isMinor();
    const has_dupr = ($('input[name="gres-has-dupr"]:checked').val() || '').toString();
    const dupr_id = ($('#gres-dupr-id').val() || '').trim();
    return {blocks, items, waiver_ack, rules_acks, dob, guardian, is_minor: minor, has_dupr, dupr_id};
  }

  function collectTimeBlocks(){
    const blocks = [];
    $blocks.find('.gres-block').each(function(){
      const $b = $(this);
      const date = $b.find('.gres-date').val();
      const start_time = $b.find('.gres-start').val();
      const hours = parseFloat($b.find('.gres-hours').val() || '0');
      if(date && start_time && hours){
        blocks.push({date, start_time, hours});
      }
    });
    return blocks;
  }

  function setItemUi(itemId, configuredQty, availableQty){
    const $avail = $(`.gres-item-avail[data-item-id="${itemId}"]`);
    const $qty = $(`.gres-item-qty[data-item-id="${itemId}"]`);
    const $note = $(`.gres-item-note[data-item-id="${itemId}"]`);

    if(availableQty === -1 || configuredQty === 0){
      $avail.text(' • Available: Unlimited');
      $qty.removeAttr('max');
      $note.text('');
      return;
    }

    $avail.text(` • Available: ${availableQty}`);
    $qty.attr('max', String(availableQty));

    const cur = parseInt($qty.val()||'0',10);
    if(cur > availableQty){
      $qty.val(String(availableQty));
      $note.text(`Only ${availableQty} available for the selected date/time.`);
    } else {
      // clear any previous note if within range
      $note.text('');
    }
  }

  // Filter ${L('label_other_items','Other Items')} based on selected court type(s).
  function updateOtherItemsVisibility(){
    const selectedTypes = [];
    $('#gres-blocks .gres-block').each(function(){
      const v = parseInt($(this).find('.gres-type').val() || '0', 10);
      if(v > 0) selectedTypes.push(v);
    });

    const hasSelection = selectedTypes.length > 0;

    const $card = $('#gres-items-card');
    let anyVisible = false;
    if($card.length && !hasSelection){
      $card.hide();
    }

    $('.gres-item').each(function(){
      const $row = $(this);
      const allowedRaw = String($row.data('allowed-court-types') || '').trim();
      let show = true;
      if(hasSelection && allowedRaw){
        const allowed = allowedRaw.split(',').map(s => parseInt(s.trim(),10)).filter(n => n>0);
        show = allowed.some(a => selectedTypes.indexOf(a) !== -1);
      }

      const $qty = $row.find('.gres-item-qty');
      if(show){
        $row.show();
        anyVisible = true;
        $qty.prop('disabled', false);
      } else {
        $row.hide();
        // Force qty to 0 so it won't be charged/sent.
        $qty.val('0');
        $qty.prop('disabled', true);
      }
    });
 

    if($card.length){
      $card.toggle(hasSelection && anyVisible);
    }
  }

  function refreshItemsAvailability(){
    const timeBlocks = collectTimeBlocks();

    // If no time blocks are set yet, show configured availability only.
    if(!timeBlocks.length){
      $('.gres-item-qty').each(function(){
        const id = parseInt($(this).data('item-id'),10);
        const configured = parseInt($(this).data('configured-qty')||'0',10);
        if(configured > 0){
          setItemUi(id, configured, configured);
        } else {
          setItemUi(id, 0, -1);
        }
      });
      return;
    }

    $.post(GRES.ajax_url, {
      action: 'gres_items_availability',
      nonce: GRES.nonce,
      location_id: getLocationId(),
      blocks: JSON.stringify(timeBlocks)
    }).done(function(resp){
      if(!resp || !resp.success){
        return;
      }
      const items = resp.data.items || [];
      items.forEach(it=>{
        const id = parseInt(it.id,10);
        itemAvailability[id] = {configured_qty: parseInt(it.configured_qty,10), available_qty: parseInt(it.available_qty,10)};
        setItemUi(id, itemAvailability[id].configured_qty, itemAvailability[id].available_qty);
      });
      renderSummary();
    });
  }

  
  function refreshAllBlocks(){
    $('#gres-blocks .gres-block').each(function(){
      const $b = $(this);
      $b.removeData('selectedCourt');
      $b.find('.gres-date').trigger('change');
    });
  }
function renderSummary(){
    const payload = collectPayload();
    const lines = [];
    let total = 0;

    // blocks summary
    payload.blocks.forEach((b, i)=>{
      const t = GRES.court_types.find(x=>parseInt(x.id,10)===b.court_type_id);
      const prefix = t ? t.prefix : '';
      const code = prefix + b.court_number;
      const rate = t ? parseFloat(t.price) : 0;
      const line = rate * b.hours;
      total += line;
      lines.push(`<div class="gres-sum-line"><strong>${code}</strong> — ${b.date} ${formatTimeLabel(b.start_time)} (${b.hours}h) <span class="gres-sum-right">${money(line)}</span></div>`);
    });


    // items summary (each item has its own hours selector)
    payload.items.forEach(it=>{
      const item = (GRES.items||[]).find(x=>parseInt(x.id,10)===it.id);
      const price = item ? parseFloat(item.price) : 0;
      const hours = parseFloat(it.hours||0) || 0;
      const line = price * it.qty * hours;
      total += line;
      const hoursLabel = hours ? ` × ${hours}h` : '';
      lines.push(`<div class="gres-sum-line">${item ? item.name : 'Item'} × ${it.qty}${hoursLabel}<span class="gres-sum-right">${money(line)}</span></div>`);
    });

    if(lines.length===0){
      $summary.html('<div class="gres-small">Add at least one reservation.</div>');
    } else {
      $summary.html(lines.join(''));
    }
    $total.text(money(total));
  }

  $('#gres-add-block').on('click', function(){
    newBlock();
  });

  // DUPR question support
  function applyDuprUi(){
    const s = (GRES.settings||{});
    const enabled = parseInt(s.enable_dupr_question||0,10) === 1;
    if(!enabled){
      $('#gres-dupr-wrap').hide();
      return;
    }
    const v = $('input[name="gres-has-dupr"]:checked').val();
    const noteHtml = (s.dupr_no_note || '');
    if(v === 'yes'){
      $('#gres-dupr-id-wrap').show();
      $('#gres-dupr-note').hide().html('');
    } else if(v === 'no'){
      $('#gres-dupr-id-wrap').hide();
      $('#gres-dupr-id').val('');
      $('#gres-dupr-note').html(noteHtml).show();
    } else {
      $('#gres-dupr-id-wrap').hide();
      $('#gres-dupr-note').hide().html('');
    }
  }

  $(document).on('change', '.gres-item-qty', function(){
    const $qty = $(this);
    const id = parseInt($qty.data('item-id'),10);
    const maxAttr = $qty.attr('max');
    const max = maxAttr ? parseInt(maxAttr,10) : null;
    const val = parseInt($qty.val()||'0',10);
    const $note = $(`.gres-item-note[data-item-id="${id}"]`);
    if(max !== null && !isNaN(max) && val > max){
      $qty.val(String(max));
      $note.text(`Only ${max} available for the selected date/time.`);
    } else {
      // Clear note if within limit
      if($note) $note.text('');
    }
    renderSummary();
  });

  $(document).on('change', '.gres-item-hours', function(){
    const v = parseFloat($(this).val()||'0');
    if(!v || v < 0.5){ $(this).val('1'); }
    renderSummary();
  });

  $('#gres-checkout').on('click', function(){
    $msg.text('');
    // Clear inline errors for global fields
    ['gres-first','gres-last','gres-email','gres-phone'].forEach(clearFieldErrorById);
    const first_name = $('#gres-first').val().trim();
    const last_name = $('#gres-last').val().trim();
    const email = $('#gres-email').val().trim();
    const phone = $('#gres-phone').val().trim();
    const payload = collectPayload();

    if(!first_name || !last_name || !email || !phone){
      if(!first_name){ showFieldErrorById('gres-first','First Name is required.'); $('#gres-first').focus(); return; }
      if(!last_name){ showFieldErrorById('gres-last','Last Name is required.'); $('#gres-last').focus(); return; }
      if(!email){ showFieldErrorById('gres-email','Email is required.'); $('#gres-email').focus(); return; }
      if(!phone){ showFieldErrorById('gres-phone','Phone is required.'); $('#gres-phone').focus(); return; }
      return;
    }
    if(!payload.blocks.length){
      $msg.text('Add at least one court reservation block and select a court.');
      return;
    }


    // Age requirement validation (minor question + required guardian/DOB when minor = YES)
    const s = (GRES.settings||{});
    const enableAge = parseInt(s.enable_age_requirement||0,10) === 1;
    if(enableAge){
      const sel = $('input[name="gres-is-minor"]:checked').val();
      if(!sel){
        $msg.text('Please answer: Are you a minor?');
        return;
      }
      if(payload.is_minor){
        if(!payload.dob){
          $msg.text('Date of Birth is required for minors.');
          $('#gres-dob').focus();
          return;
        }
        const g = payload.guardian || {};
        if(!g.name || !g.relationship || !g.email || !g.phone){
          $msg.text('Guardian Name, Relationship, Email, and Phone are required for minors.');
          $('#gres-guardian-name').focus();
          return;
        }
        // basic guardian email format check
        if(g.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(g.email)){
          $msg.text('Please enter a valid guardian email address.');
          $('#gres-guardian-email').focus();
          return;
        }
      }
    }
    $('#gres-checkout').prop('disabled', true).text('Creating checkout...');
    $.post(GRES.ajax_url, {
      action: 'gres_create_checkout',
      nonce: GRES.nonce,
      location_id: ($('#gres-location').val() || GRES.location_id || 1),
      first_name, last_name, email, phone,
      payload: JSON.stringify(payload)
    }).done(function(resp){
      if(!resp || !resp.success){
        const msgText = (resp && resp.data && resp.data.message) ? resp.data.message : 'Checkout failed.';
        const code = (resp && resp.data && resp.data.code) ? resp.data.code : '';
        if(code === 'needs_approval'){
          // Force approval mode for all blocks
          $('.gres-block').each(function(){
            $(this).data('forceApproval', 1);
            if(msgText){ $(this).data('approvalReason', msgText); }
          });
          $('#gres-approval-msg').text(msgText).show();
          applyApprovalMode();
          $msg.text(msgText);
          $('#gres-checkout').prop('disabled', false).text(L('btn_complete_pay','Complete Reservation & Pay'));
          return;
        }
        $msg.text(msgText);
        // Recheck availability and disable courts after a conflict or other checkout error
        refreshAllBlocks();
        $('#gres-checkout').prop('disabled', false).text(L('btn_complete_pay','Complete Reservation & Pay'));
        return;
      }
      window.location.href = resp.data.checkout_url;
    }).fail(function(){
      $msg.text('Checkout failed. Please try again.');
      $('#gres-checkout').prop('disabled', false).text(L('btn_complete_pay','Complete Reservation & Pay'));
    });
  });


  // Submit for approval (no payment)
  $('#gres-approval-submit').on('click', function(){
    $msg.text('');
    ['gres-first','gres-last','gres-email','gres-phone'].forEach(clearFieldErrorById);
    const first_name = ($('#gres-first').val() || '').trim();
    const last_name  = ($('#gres-last').val() || '').trim();
    const email      = ($('#gres-email').val() || '').trim();
    const phone      = ($('#gres-phone').val() || '').trim();

    const payload = collectPayload();

    // Basic checks
    if(!first_name || !last_name || !email || !phone){
      if(!first_name){ showFieldErrorById('gres-first','First Name is required.'); $('#gres-first').focus(); return; }
      if(!last_name){ showFieldErrorById('gres-last','Last Name is required.'); $('#gres-last').focus(); return; }
      if(!email){ showFieldErrorById('gres-email','Email is required.'); $('#gres-email').focus(); return; }
      if(!phone){ showFieldErrorById('gres-phone','Phone is required.'); $('#gres-phone').focus(); return; }
      return;
    }
    if(!payload.blocks || payload.blocks.length < 1){
      $msg.text('Please add a reservation block first.');
      return;
    }


    // Age requirement validation (minor question + required guardian/DOB when minor = YES)
    const s = (GRES.settings||{});
    const enableAge = parseInt(s.enable_age_requirement||0,10) === 1;
    if(enableAge){
      const sel = $('input[name="gres-is-minor"]:checked').val();
      if(!sel){
        $msg.text('Please answer: Are you a minor?');
        return;
      }
      if(payload.is_minor){
        if(!payload.dob){
          $msg.text('Date of Birth is required for minors.');
          $('#gres-dob').focus();
          return;
        }
        const g = payload.guardian || {};
        if(!g.name || !g.relationship || !g.email || !g.phone){
          $msg.text('Guardian Name, Relationship, Email, and Phone are required for minors.');
          $('#gres-guardian-name').focus();
          return;
        }
        // basic guardian email format check
        if(g.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(g.email)){
          $msg.text('Please enter a valid guardian email address.');
          $('#gres-guardian-email').focus();
          return;
        }
      }
    }

    // Should be enforced by UI, but validate here too
    if(payload.blocks.length > 1){
      $msg.text('Approval-required requests can only be submitted as a single reservation.');
      return;
    }

    const $btn = $('#gres-approval-submit');
    $btn.prop('disabled', true).text('Submitting...');
    $.post(GRES.ajax_url, {
      action: 'gres_submit_approval',
      nonce: GRES.nonce,
      location_id: ($('#gres-location').val() || GRES.location_id || 1),
      first_name, last_name, email, phone,
      payload: JSON.stringify(payload)
    }).done(function(resp){
      if(!resp || !resp.success){
        $msg.text(resp && resp.data && resp.data.message ? resp.data.message : 'Submission failed.');
        $btn.prop('disabled', false).text(L('btn_submit_approval','Submit for Approval'));
        return;
      }
      $msg.text(resp.data && resp.data.message ? resp.data.message : 'Submitted for approval.');
      $btn.prop('disabled', false).text(L('btn_submit_approval','Submit for Approval'));
      setTimeout(function(){ resetForm(); }, 3000);
    }).fail(function(){
      $msg.text('Submission failed. Please try again.');
      $btn.prop('disabled', false).text(L('btn_submit_approval','Submit for Approval'));
    });
  });

  // init
  newBlock();
  applyApprovalMode();
  initCalendarToggle();
  initBlockoutToggle();
  applyAgeUi();
  applyDuprUi();
  $('#gres-dob').on('change', function(){ applyAgeUi(); });
  $('input[name="gres-is-minor"]').on('change', function(){ applyAgeUi(); });
  $('input[name="gres-has-dupr"]').on('change', function(){ applyDuprUi(); });

  // Location switching: reload with gres_loc so server renders correct court types/items/messages
  $(document).on('change', '#gres-location', function(){
    var id = parseInt($(this).val()||'0',10);
    if(!id) id = 1;
    try {
      var url = new URL(window.location.href);
      url.searchParams.set('gres_loc', id);
      window.location.href = url.toString();
    } catch(e) {
      window.location.search = '?gres_loc=' + encodeURIComponent(id);
    }
  });
});

// === Theme toggle (scoped to G-Reservation wrappers) ===
(function(){
  function applyTheme($wrap, theme){
    if(!$wrap) return;
    $wrap.classList.remove('gres-theme-dark','gres-theme-light');
    $wrap.classList.add(theme === 'dark' ? 'gres-theme-dark' : 'gres-theme-light');
  }

  function init(){
    document.querySelectorAll('.gres-wrap[data-gres-page]').forEach(function($wrap){
      var btn = $wrap.querySelector('.gres-theme-toggle');
      var defaultTheme = (btn && btn.getAttribute('data-gres-default-theme')) ? btn.getAttribute('data-gres-default-theme') : 'light';
      var key = 'gres_theme_global';
      var saved = null;
      try { saved = localStorage.getItem(key); } catch(e){}
      var theme = (saved === 'dark' || saved === 'light') ? saved : defaultTheme;
      applyTheme($wrap, theme);

      if(btn){
        btn.textContent = (theme === 'dark') ? 'Light Mode' : 'Dark Mode';
        btn.addEventListener('click', function(){
          var current = $wrap.classList.contains('gres-theme-dark') ? 'dark' : 'light';
          var next = current === 'dark' ? 'light' : 'dark';
          applyTheme($wrap, next);
          btn.textContent = (next === 'dark') ? 'Light Mode' : 'Dark Mode';
          try { localStorage.setItem(key, next); } catch(e){}
        });
      }
    });
  }

  if(document.readyState === 'loading'){
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

function resetForm(){
  if(typeof window.GRES_RESET_FORM === 'function'){
    try { window.GRES_RESET_FORM(); } catch(e){}
  }
}
}

/* Make arrows visible on dark background */
input[type="number"]::-webkit-inner-spin-button {
    filter: invert(1);
}

.gres-suggestions,
.gres-suggestion,
.gres-sug-empty,
.gres-sug-loading{
    color:#111 !important;
    background:#fff !important;
}

.gres-suggestion{
    padding:10px;
    border-radius:8px;
    margin-bottom:6px;
    cursor:pointer;
}

/* FORCE SUGGESTION TEXT COLORS */

.gres-suggestions,
.gres-suggestions *,
.gres-sug-list,
.gres-sug-empty,
.gres-sug-btn{
    color:#111111 !important;
}

.gres-suggestions{
    background:#ffffff !important;
}

.gres-sug-btn{
    background:#f3f3f3 !important;
    border:1px solid #d0d0d0 !important;
}

/* Suggestions force dark text */

.gres-suggestions,
.gres-suggestions *{
    color:#111 !important;
}

.gres-suggestions{
    background:#fff !important;
}

/* FORCE suggestion colors */

.gres-wrap .gres-suggestions,
.gres-wrap .gres-suggestions *,
.gres-wrap .gres-sug-list,
.gres-wrap .gres-sug-empty,
.gres-wrap .gres-sug-btn{
    color:#111111 !important;
}

.gres-wrap .gres-suggestions{
    background:#ffffff !important;
}

.gres-wrap .gres-sug-btn{
    background:#f3f3f3 !important;
    border:1px solid #cccccc !important;
}

.gres-sug-help{
    margin-top:8px;
    font-size:13px;
    font-weight:600;
    color:#F5C518 !important;
    line-height:1.4;
}

/* Selected suggestion */

.gres-sug-btn.gres-sug-selected{

    background:#F5C518 !important;

    color:#111 !important;

    border:2px solid #ffffff !important;

    box-shadow:
        0 0 12px rgba(245,197,24,0.55);

    transform:scale(1.02);

    transition:all 0.2s ease;

}/* All-Day / Event Reservation */
.gres-all-day-note{margin-top:8px;padding:10px 12px;border:1px solid rgba(251,176,64,.55);border-radius:8px;background:rgba(251,176,64,.08);line-height:1.45}
.gres-all-day-selection-invalid .gres-courts{outline:2px solid #b32d2e;outline-offset:3px;border-radius:6px}

/* Larger Submit for Approval button */
.gres-wrap #gres-approval-submit{
    font-size:17px !important;
    font-weight:800 !important;
    padding:12px 24px !important;
    min-height:48px !important;
    line-height:1.2 !important;
    border-radius:8px !important;
}

@media (max-width:600px){
    .gres-wrap #gres-approval-submit{
        width:100% !important;
        padding:14px 20px !important;
    }
}

/* v6.77.3 multi-court reservation blocks */
.gres-court-pill.gres-selected-elsewhere{opacity:.48;cursor:not-allowed;}
.gres-court-selected-note{display:block;font-size:11px;line-height:1.2;margin-top:2px;opacity:.85;}

/* v6.87.2 - Rules of Use readability fix */
.gres-wrap .gres-legal-missing{
  background:#0b0b0d !important;
  color:#ffffff !important;
  border:1px dashed #FBB040 !important;
  opacity:1 !important;
}
.gres-wrap .gres-legal-missing,
.gres-wrap .gres-legal-missing *{
  color:#ffffff !important;
  background:transparent !important;
  opacity:1 !important;
}
.gres-wrap .gres-legal-missing strong{
  color:#FBB040 !important;
}


/* ==========================================================
   v6.88.14 — PbC Club Branding inheritance + wider layout
   Shared palette comes from PbC Club Provisioner.
   State rule: background/text pairs stay together on hover/focus.
   ========================================================== */
.gres-wrap{
  --gres-club-primary:var(--pbc-primary,#FBB040);
  --gres-club-secondary:var(--pbc-secondary,#c8921a);
  --gres-club-accent:var(--pbc-accent,#FBB040);
  --gres-club-page:var(--pbc-background,#ffffff);
  --gres-club-surface:var(--pbc-surface,#0b0b0b);
  --gres-club-page-text:var(--pbc-text,#111111);
  --gres-club-surface-text:var(--pbc-surface-text,#ffffff);

  /* Wider desktop reservation experience. */
  width:min(1200px,calc(100% - 32px)) !important;
  max-width:1200px !important;
  margin-left:auto !important;
  margin-right:auto !important;

  /* Club-owned surface palette replaces legacy hard-coded black/gold. */
  --gold:var(--gres-club-primary) !important;
  --border:color-mix(in srgb,var(--gres-club-primary) 55%,transparent) !important;
  --text:var(--gres-club-surface-text) !important;
  --text-light:var(--gres-club-surface-text) !important;
  --gres-heading-color:var(--gres-club-primary) !important;
  background:var(--gres-club-surface) !important;
  color:var(--gres-club-surface-text) !important;
  border-color:color-mix(in srgb,var(--gres-club-primary) 55%,transparent) !important;
}

/* Main reservation panels */
.gres-wrap .gres-card,
.gres-wrap .gres-box,
.gres-wrap .gres-section,
.gres-wrap .gres-summary,
.gres-wrap .gres-item-note,
.gres-wrap .gres-legal-missing{
  background:var(--gres-club-surface) !important;
  color:var(--gres-club-surface-text) !important;
  border-color:color-mix(in srgb,var(--gres-club-primary) 55%,transparent) !important;
}
.gres-wrap .gres-card *,
.gres-wrap .gres-box *,
.gres-wrap .gres-section *,
.gres-wrap .gres-summary *{
  color:inherit;
}

/* Headings / accents */
.gres-wrap h1,.gres-wrap h2,.gres-wrap h3,.gres-wrap h4,
.gres-wrap .gres-title,.gres-wrap .gres-heading,.gres-wrap .gres-section-title,
.gres-wrap .gres-sum-right,
.gres-wrap .gres-collapse summary,
.gres-wrap .gres-legal-missing strong{
  color:var(--gres-club-primary) !important;
  -webkit-text-fill-color:currentColor !important;
}
.gres-wrap h2::after,.gres-wrap h3::after{
  background:var(--gres-club-primary) !important;
}

/* Text on the dark/surface reservation UI */
.gres-wrap p,.gres-wrap small,.gres-wrap label,.gres-wrap .description,
.gres-wrap .gres-small,.gres-wrap .gres-help,.gres-wrap .gres-item-note,
.gres-wrap .gres-legal-text,.gres-wrap .gres-item-avail,
.gres-wrap .gres-item-hours-label,.gres-wrap .gres-sum-line{
  color:var(--gres-club-surface-text) !important;
  -webkit-text-fill-color:currentColor !important;
}

/* Form controls remain a surface pair, including hover/focus. */
.gres-wrap input:not([type="submit"]):not([type="button"]),
.gres-wrap select,.gres-wrap textarea{
  background:var(--gres-club-surface) !important;
  color:var(--gres-club-surface-text) !important;
  -webkit-text-fill-color:var(--gres-club-surface-text) !important;
  border-color:color-mix(in srgb,var(--gres-club-primary) 55%,transparent) !important;
}
.gres-wrap input:not([type="submit"]):not([type="button"]):focus,
.gres-wrap select:focus,.gres-wrap textarea:focus{
  background:var(--gres-club-surface) !important;
  color:var(--gres-club-surface-text) !important;
  border-color:var(--gres-club-primary) !important;
  box-shadow:0 0 0 2px color-mix(in srgb,var(--gres-club-primary) 28%,transparent) !important;
}

/* Buttons: never swap to a light/dark unknown color on hover. */
.gres-wrap button,.gres-wrap .gres-btn,.gres-wrap input[type="submit"],
.g-header-btn{
  background:var(--gres-club-primary) !important;
  color:var(--gres-club-surface-text) !important;
  -webkit-text-fill-color:var(--gres-club-surface-text) !important;
  border:1px solid var(--gres-club-primary) !important;
  box-shadow:none !important;
}
.gres-wrap button:hover,.gres-wrap button:focus,.gres-wrap button:focus-visible,
.gres-wrap .gres-btn:hover,.gres-wrap .gres-btn:focus,.gres-wrap .gres-btn:focus-visible,
.gres-wrap input[type="submit"]:hover,.gres-wrap input[type="submit"]:focus,
.g-header-btn:hover,.g-header-btn:focus,.g-header-btn:focus-visible{
  background:var(--gres-club-primary) !important;
  color:var(--gres-club-surface-text) !important;
  -webkit-text-fill-color:var(--gres-club-surface-text) !important;
  filter:brightness(1.08) !important;
}

/* Court choices keep a complete surface/text pair in every state. */
.gres-wrap .gres-court-pill{
  background:var(--gres-club-surface) !important;
  color:var(--gres-club-surface-text) !important;
  border-color:var(--gres-club-primary) !important;
}
.gres-wrap .gres-court-pill:hover,.gres-wrap .gres-court-pill:focus-within{
  background:var(--gres-club-surface) !important;
  color:var(--gres-club-surface-text) !important;
  filter:brightness(1.08) !important;
}
.gres-wrap input[type="checkbox"],.gres-wrap input[type="radio"]{
  accent-color:var(--gres-club-primary) !important;
}

/* Explicit light notice / lookup surfaces use page text, not surface text. */
.gres-wrap .gres-lookup-errors,
.gres-wrap .gres-approval-msg,
.gres-wrap .gres-suggestions{
  background:var(--gres-club-page) !important;
  color:var(--gres-club-page-text) !important;
  border-color:color-mix(in srgb,var(--gres-club-primary) 45%,transparent) !important;
}
.gres-wrap .gres-lookup-errors *,
.gres-wrap .gres-approval-msg *,
.gres-wrap .gres-suggestions *{
  color:var(--gres-club-page-text) !important;
  -webkit-text-fill-color:currentColor !important;
}

/* Reservation hero uses the same club palette. */
.g-header-wrap{
  width:min(1200px,calc(100% - 32px)) !important;
  max-width:1200px !important;
  background:var(--pbc-surface,#0b0b0b) !important;
  border-color:color-mix(in srgb,var(--pbc-primary,#FBB040) 55%,transparent) !important;
}
.g-header-title{color:var(--pbc-primary,#FBB040) !important;}
.g-header-sub{color:var(--pbc-surface-text,#ffffff) !important;}

/* Preserve compact/mobile usability. */
@media (max-width:760px){
  .gres-wrap,.g-header-wrap{width:calc(100% - 20px) !important;max-width:none !important;}
}


/* === v6.88.15: Contrast-safe reservation form + clearer field structure === */
/* Never force headings to an accent color: headings live on the dark club surface. */
.gres-wrap h1,.gres-wrap h2,.gres-wrap h3,.gres-wrap h4,
.gres-wrap .gres-title,.gres-wrap .gres-heading,.gres-wrap .gres-section-title,
.gres-wrap .gres-subheading{
  color:var(--gres-club-surface-text) !important;
  -webkit-text-fill-color:var(--gres-club-surface-text) !important;
}
.gres-wrap > h3{
  font-size:30px !important;
  font-weight:800 !important;
  margin:12px 0 18px !important;
  padding:0 0 12px !important;
  border-bottom:3px solid var(--gres-club-primary) !important;
}
/* Section labels get a clearly separated header treatment. */
.gres-wrap .gres-card > h4{
  display:block !important;
  margin:-2px -2px 16px !important;
  padding:12px 14px !important;
  border:1px solid color-mix(in srgb,var(--gres-club-primary) 48%,transparent) !important;
  border-radius:10px !important;
  background:color-mix(in srgb,var(--gres-club-surface-text) 7%,var(--gres-club-surface)) !important;
  color:var(--gres-club-surface-text) !important;
}
/* Give every logical field its own visible boundary. */
.gres-wrap .gres-card{
  border:1px solid color-mix(in srgb,var(--gres-club-surface-text) 24%,var(--gres-club-primary)) !important;
  box-shadow:0 8px 24px rgba(0,0,0,.18) !important;
  padding:18px !important;
}
.gres-wrap .gres-grid{
  gap:14px !important;
}
.gres-wrap .gres-grid > div{
  min-width:0;
  padding:12px !important;
  border:1px solid color-mix(in srgb,var(--gres-club-surface-text) 22%,transparent) !important;
  border-radius:10px !important;
  background:color-mix(in srgb,var(--gres-club-surface-text) 4%,var(--gres-club-surface)) !important;
}
.gres-wrap .gres-grid > div label{
  color:var(--gres-club-surface-text) !important;
  font-weight:700 !important;
}
/* Inputs/selects must remain visually identifiable, not disappear into the card. */
.gres-wrap input:not([type="submit"]):not([type="button"]):not([type="radio"]):not([type="checkbox"]),
.gres-wrap select,.gres-wrap textarea{
  min-height:42px !important;
  padding:9px 11px !important;
  border:1.5px solid color-mix(in srgb,var(--gres-club-surface-text) 55%,var(--gres-club-primary)) !important;
  border-radius:8px !important;
  background:color-mix(in srgb,var(--gres-club-surface-text) 3%,var(--gres-club-surface)) !important;
  color:var(--gres-club-surface-text) !important;
  -webkit-text-fill-color:var(--gres-club-surface-text) !important;
}
.gres-wrap input::placeholder,.gres-wrap textarea::placeholder{
  color:color-mix(in srgb,var(--gres-club-surface-text) 68%,transparent) !important;
  -webkit-text-fill-color:color-mix(in srgb,var(--gres-club-surface-text) 68%,transparent) !important;
  opacity:1 !important;
}
.gres-wrap input:focus,.gres-wrap select:focus,.gres-wrap textarea:focus{
  outline:none !important;
  border-color:var(--gres-club-primary) !important;
  box-shadow:0 0 0 3px color-mix(in srgb,var(--gres-club-primary) 30%,transparent) !important;
}
/* Small section labels and generated reservation block headings must stay readable. */
.gres-wrap .gres-small,.gres-wrap .gres-block-head,.gres-wrap .gres-block-head *,
.gres-wrap [id^="gres-block"] h4,.gres-wrap [id^="gres-block"] h3{
  color:var(--gres-club-surface-text) !important;
  -webkit-text-fill-color:var(--gres-club-surface-text) !important;
}
/* Primary is an accent/border; do not use it as text on a dark surface. */
.gres-wrap .gres-sum-right,.gres-wrap .gres-collapse summary,
.gres-wrap .gres-legal-missing strong{
  color:var(--gres-club-surface-text) !important;
}
@media (max-width:760px){
  .gres-wrap .gres-card{padding:13px !important;}
  .gres-wrap .gres-grid > div{padding:10px !important;}
  .gres-wrap > h3{font-size:25px !important;}
}

/* === v6.88.16: Always-visible field borders / Join-style form controls === */
/* Reservation fields must remain visually distinct regardless of theme reset CSS. */
.gres-wrap .gres-card input[type="text"],
.gres-wrap .gres-card input[type="email"],
.gres-wrap .gres-card input[type="tel"],
.gres-wrap .gres-card input[type="number"],
.gres-wrap .gres-card input[type="date"],
.gres-wrap .gres-card input[type="time"],
.gres-wrap .gres-card input[type="url"],
.gres-wrap .gres-card select,
.gres-wrap .gres-card textarea,
.gres-wrap [id^="gres-block"] input[type="text"],
.gres-wrap [id^="gres-block"] input[type="email"],
.gres-wrap [id^="gres-block"] input[type="number"],
.gres-wrap [id^="gres-block"] input[type="date"],
.gres-wrap [id^="gres-block"] input[type="time"],
.gres-wrap [id^="gres-block"] select,
.gres-wrap [id^="gres-block"] textarea{
  display:block !important;
  width:100% !important;
  min-height:44px !important;
  box-sizing:border-box !important;
  border:2px solid color-mix(in srgb,var(--gres-club-surface-text) 72%,var(--gres-club-primary)) !important;
  border-top-width:2px !important;
  border-right-width:2px !important;
  border-bottom-width:2px !important;
  border-left-width:2px !important;
  border-style:solid !important;
  border-radius:9px !important;
  background:color-mix(in srgb,var(--gres-club-surface-text) 5%,var(--gres-club-surface)) !important;
  color:var(--gres-club-surface-text) !important;
  -webkit-text-fill-color:var(--gres-club-surface-text) !important;
  box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--gres-club-surface-text) 12%,transparent) !important;
  opacity:1 !important;
}
.gres-wrap .gres-card select,
.gres-wrap [id^="gres-block"] select{
  appearance:auto !important;
  -webkit-appearance:menulist !important;
}
.gres-wrap .gres-card input:focus,
.gres-wrap .gres-card select:focus,
.gres-wrap .gres-card textarea:focus,
.gres-wrap [id^="gres-block"] input:focus,
.gres-wrap [id^="gres-block"] select:focus,
.gres-wrap [id^="gres-block"] textarea:focus{
  border-color:var(--gres-club-primary) !important;
  box-shadow:0 0 0 3px color-mix(in srgb,var(--gres-club-primary) 32%,transparent), inset 0 0 0 1px var(--gres-club-primary) !important;
}
/* Give standalone question groups the same visible container treatment. */
.gres-wrap #gres-dupr-wrap,
.gres-wrap #gres-minor-q-wrap{
  padding:12px 14px !important;
  border:1px solid color-mix(in srgb,var(--gres-club-surface-text) 24%,transparent) !important;
  border-radius:10px !important;
  background:color-mix(in srgb,var(--gres-club-surface-text) 4%,var(--gres-club-surface)) !important;
}
.gres-wrap .gres-radio-row label{
  color:var(--gres-club-surface-text) !important;
  -webkit-text-fill-color:var(--gres-club-surface-text) !important;
}

/* === v6.88.17: Legacy-browser-safe visible customer field borders ===
 * Do not rely on color-mix() here: older browsers can discard that declaration.
 * Core customer fields and all reservation controls receive a concrete fallback border.
 */
.gres-wrap #gres-first,
.gres-wrap #gres-last,
.gres-wrap #gres-email,
.gres-wrap #gres-phone,
.gres-wrap #gres-dob,
.gres-wrap #gres-dupr-id,
.gres-wrap input[type="text"],
.gres-wrap input[type="email"],
.gres-wrap input[type="tel"],
.gres-wrap input[type="number"],
.gres-wrap input[type="date"],
.gres-wrap input[type="time"],
.gres-wrap input[type="url"],
.gres-wrap select,
.gres-wrap textarea {
  display:block !important;
  visibility:visible !important;
  opacity:1 !important;
  box-sizing:border-box !important;
  min-height:44px !important;
  border:2px solid var(--gres-club-surface-text,#ffffff) !important;
  border-radius:9px !important;
  background:var(--gres-club-surface,#0b0b0b) !important;
  color:var(--gres-club-surface-text,#ffffff) !important;
  -webkit-text-fill-color:var(--gres-club-surface-text,#ffffff) !important;
  box-shadow:none !important;
}
.gres-wrap #gres-first:focus,
.gres-wrap #gres-last:focus,
.gres-wrap #gres-email:focus,
.gres-wrap #gres-phone:focus,
.gres-wrap #gres-dob:focus,
.gres-wrap #gres-dupr-id:focus,
.gres-wrap input[type="text"]:focus,
.gres-wrap input[type="email"]:focus,
.gres-wrap input[type="tel"]:focus,
.gres-wrap input[type="number"]:focus,
.gres-wrap input[type="date"]:focus,
.gres-wrap input[type="time"]:focus,
.gres-wrap input[type="url"]:focus,
.gres-wrap select:focus,
.gres-wrap textarea:focus {
  border-color:var(--gres-club-primary,#FBB040) !important;
  outline:2px solid var(--gres-club-primary,#FBB040) !important;
  outline-offset:2px !important;
}
/* Keep checkbox/radio controls compact; the generic field rule must never stretch them. */
.gres-wrap input[type="checkbox"],
.gres-wrap input[type="radio"] {
  display:inline-block !important;
  width:auto !important;
  min-height:0 !important;
  border:initial !important;
  box-shadow:none !important;
}

/* === v6.88.18: Join-style field palette + contrast-safe native menus ===
 * Keep Reservation visually consistent with Club Join:
 * dark controls, light text, visible club-accent border, and light native option menus.
 */
.gres-wrap #gres-first,
.gres-wrap #gres-last,
.gres-wrap #gres-email,
.gres-wrap #gres-phone,
.gres-wrap #gres-dob,
.gres-wrap #gres-dupr-id,
.gres-wrap input[type="text"],
.gres-wrap input[type="email"],
.gres-wrap input[type="tel"],
.gres-wrap input[type="number"],
.gres-wrap input[type="date"],
.gres-wrap input[type="time"],
.gres-wrap input[type="url"],
.gres-wrap select,
.gres-wrap textarea {
  background:#000000 !important;
  color:#ffffff !important;
  -webkit-text-fill-color:#ffffff !important;
  border:2px solid var(--gres-club-primary,#FBB040) !important;
  border-radius:10px !important;
  min-height:48px !important;
  padding:0 14px !important;
  line-height:1.35 !important;
  caret-color:#ffffff !important;
  color-scheme:dark !important;
}
.gres-wrap textarea {
  min-height:90px !important;
  padding:12px 14px !important;
}
.gres-wrap input::placeholder,
.gres-wrap textarea::placeholder {
  color:#bfc3cc !important;
  -webkit-text-fill-color:#bfc3cc !important;
  opacity:1 !important;
}
/* Native select dropdowns are commonly rendered on a light system surface. */
.gres-wrap select option,
.gres-wrap select optgroup {
  background:#ffffff !important;
  color:#111111 !important;
  -webkit-text-fill-color:#111111 !important;
}
.gres-wrap select option:checked {
  background:#e9eefb !important;
  color:#111111 !important;
  -webkit-text-fill-color:#111111 !important;
}
.gres-wrap #gres-first:focus,
.gres-wrap #gres-last:focus,
.gres-wrap #gres-email:focus,
.gres-wrap #gres-phone:focus,
.gres-wrap #gres-dob:focus,
.gres-wrap #gres-dupr-id:focus,
.gres-wrap input[type="text"]:focus,
.gres-wrap input[type="email"]:focus,
.gres-wrap input[type="tel"]:focus,
.gres-wrap input[type="number"]:focus,
.gres-wrap input[type="date"]:focus,
.gres-wrap input[type="time"]:focus,
.gres-wrap input[type="url"]:focus,
.gres-wrap select:focus,
.gres-wrap textarea:focus {
  border-color:var(--gres-club-secondary,#FBB040) !important;
  outline:2px solid var(--gres-club-secondary,#FBB040) !important;
  outline-offset:2px !important;
  background:#000000 !important;
  color:#ffffff !important;
  -webkit-text-fill-color:#ffffff !important;
}
/* Never let the broad field rules alter compact choice controls. */
.gres-wrap input[type="checkbox"],
.gres-wrap input[type="radio"] {
  min-height:0 !important;
  padding:0 !important;
  color-scheme:light !important;
}

/* === v6.88.19: Uniform visible field border system ===
 * Club primary can itself be very dark. Never use it as the only field edge.
 * Every editable/selectable reservation control gets a guaranteed high-contrast edge.
 */
.gres-wrap input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"]):not([type="submit"]):not([type="button"]),
.gres-wrap select,
.gres-wrap textarea {
  border:2px solid var(--gres-club-surface-text,#ffffff) !important;
  outline:none !important;
  box-shadow:inset 0 0 0 1px rgba(255,255,255,.08) !important;
  background:#000000 !important;
  color:var(--gres-club-surface-text,#ffffff) !important;
  -webkit-text-fill-color:var(--gres-club-surface-text,#ffffff) !important;
  opacity:1 !important;
}
.gres-wrap input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"]):not([type="submit"]):not([type="button"]):hover,
.gres-wrap select:hover,
.gres-wrap textarea:hover {
  border-color:var(--gres-club-surface-text,#ffffff) !important;
}
.gres-wrap input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"]):not([type="submit"]):not([type="button"]):focus,
.gres-wrap select:focus,
.gres-wrap textarea:focus,
.gres-wrap input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"]):not([type="submit"]):not([type="button"]):focus-visible,
.gres-wrap select:focus-visible,
.gres-wrap textarea:focus-visible {
  border-color:var(--gres-club-secondary,#5f29f5) !important;
  outline:2px solid var(--gres-club-secondary,#5f29f5) !important;
  outline-offset:2px !important;
  box-shadow:none !important;
}

/* === v6.88.20: Customer identity fields — single always-visible border ===
 * Keep these four fields consistent with the reservation controls.
 * One border only in normal, hover and focus states; no browser/theme focus ring.
 */
.gres-wrap #gres-first,
.gres-wrap #gres-last,
.gres-wrap #gres-email,
.gres-wrap #gres-phone,
.gres-wrap #gres-first:hover,
.gres-wrap #gres-last:hover,
.gres-wrap #gres-email:hover,
.gres-wrap #gres-phone:hover,
.gres-wrap #gres-first:focus,
.gres-wrap #gres-last:focus,
.gres-wrap #gres-email:focus,
.gres-wrap #gres-phone:focus,
.gres-wrap #gres-first:focus-visible,
.gres-wrap #gres-last:focus-visible,
.gres-wrap #gres-email:focus-visible,
.gres-wrap #gres-phone:focus-visible {
  border:2px solid #e6e6e6 !important;
  outline:none !important;
  outline-offset:0 !important;
  box-shadow:none !important;
  background:#000000 !important;
  color:#ffffff !important;
  -webkit-text-fill-color:#ffffff !important;
}

/* === v6.88.21: Strong checkout CTA + clear suggestion navigation === */
.gres-wrap #gres-checkout {
  display:inline-flex !important;
  align-items:center !important;
  justify-content:center !important;
  min-height:52px !important;
  padding:13px 26px !important;
  border:2px solid var(--gres-club-primary,#FBB040) !important;
  border-radius:10px !important;
  background:var(--gres-club-primary,#FBB040) !important;
  color:#111111 !important;
  -webkit-text-fill-color:#111111 !important;
  font-size:17px !important;
  font-weight:800 !important;
  line-height:1.2 !important;
  text-decoration:none !important;
  box-shadow:0 4px 14px rgba(0,0,0,.28) !important;
  cursor:pointer !important;
}
.gres-wrap #gres-checkout:hover,
.gres-wrap #gres-checkout:focus,
.gres-wrap #gres-checkout:focus-visible {
  background:var(--gres-club-secondary,#5f29f5) !important;
  border-color:var(--gres-club-secondary,#5f29f5) !important;
  color:#ffffff !important;
  -webkit-text-fill-color:#ffffff !important;
  outline:2px solid #ffffff !important;
  outline-offset:2px !important;
}
.gres-wrap #gres-checkout:disabled {
  opacity:.6 !important;
  cursor:not-allowed !important;
}

.gres-wrap .gres-sug-nav {
  display:flex !important;
  align-items:center !important;
  gap:12px !important;
  flex-wrap:wrap !important;
  margin-top:12px !important;
}
.gres-wrap .gres-sug-prev,
.gres-wrap .gres-sug-next {
  display:inline-flex !important;
  align-items:center !important;
  justify-content:center !important;
  min-height:40px !important;
  padding:8px 16px !important;
  border:2px solid var(--gres-club-primary,#FBB040) !important;
  border-radius:8px !important;
  background:var(--gres-club-primary,#FBB040) !important;
  color:#111111 !important;
  -webkit-text-fill-color:#111111 !important;
  font-size:14px !important;
  font-weight:800 !important;
  line-height:1.2 !important;
  text-shadow:none !important;
  opacity:1 !important;
}
.gres-wrap .gres-sug-prev:hover:not(:disabled),
.gres-wrap .gres-sug-next:hover:not(:disabled),
.gres-wrap .gres-sug-prev:focus:not(:disabled),
.gres-wrap .gres-sug-next:focus:not(:disabled) {
  background:var(--gres-club-secondary,#5f29f5) !important;
  border-color:var(--gres-club-secondary,#5f29f5) !important;
  color:#ffffff !important;
  -webkit-text-fill-color:#ffffff !important;
}
.gres-wrap .gres-sug-prev:disabled,
.gres-wrap .gres-sug-next:disabled {
  background:#3a3a3a !important;
  border-color:#777777 !important;
  color:#d7d7d7 !important;
  -webkit-text-fill-color:#d7d7d7 !important;
  opacity:1 !important;
  cursor:not-allowed !important;
}
.gres-wrap .gres-sug-page {
  color:var(--gres-club-surface-text,#ffffff) !important;
  font-weight:700 !important;
}

/* PbC Unified Public UI — v6.88.22. Scoped to reservation public surfaces.
   Uses club-level tokens when available; never modifies checkout behavior. */
.gres-wrap,.gres-lookup-wrap,.gres-myres,.gres-login-wrap{
  --pbc-ui-primary:var(--pbc-primary,#111827);
  --pbc-ui-secondary:var(--pbc-secondary,#2563eb);
  --pbc-ui-accent:var(--pbc-accent,#f5b942);
  --pbc-ui-page:var(--pbc-background,#f8fafc);
  --pbc-ui-text:var(--pbc-text,#1e293b);
  --pbc-ui-border:#dbe3ee;
  font-family:inherit; color:var(--pbc-ui-text); line-height:1.55;
}
.gres-wrap .gres-card,.gres-wrap .gres-block,.gres-lookup-wrap .gres-lookup-card,
.gres-myres .gres-card{
  border-radius:16px; border:1px solid var(--pbc-ui-border);
  box-shadow:0 6px 24px rgba(15,23,42,.065);
}
.gres-wrap :is(input:not([type="checkbox"]):not([type="radio"]):not([type="hidden"]),select,textarea),
.gres-lookup-wrap :is(input:not([type="checkbox"]):not([type="radio"]),select,textarea){
  font:inherit; min-height:42px; border-radius:9px; border:1px solid #aab8cc;
  padding:9px 12px; max-width:100%; box-sizing:border-box;
}
.gres-wrap :is(input,select,textarea):focus-visible,
.gres-lookup-wrap :is(input,select,textarea):focus-visible,
.gres-wrap :is(button,a.gres-btn):focus-visible{
  outline:2px solid var(--pbc-ui-secondary);outline-offset:2px;
}
.gres-wrap :is(button,.gres-btn,input[type="submit"]),
.gres-lookup-wrap :is(button,.gres-btn,input[type="submit"]){
  font-family:inherit; border-radius:10px; transition:box-shadow .15s ease,transform .15s ease;
}
.gres-wrap :is(button,.gres-btn,input[type="submit"]):not(:disabled):hover,
.gres-lookup-wrap :is(button,.gres-btn,input[type="submit"]):not(:disabled):hover{
  box-shadow:0 4px 14px rgba(15,23,42,.14);transform:translateY(-1px);
}
.gres-wrap :is(button,.gres-btn,input[type="submit"]):disabled{opacity:.55;cursor:not-allowed;}
@media(max-width:640px){
  .gres-wrap .gres-card,.gres-wrap .gres-block{border-radius:12px;}
  .gres-wrap :is(input,select,textarea){max-width:100%;}
}
@media(prefers-reduced-motion:reduce){
  .gres-wrap :is(button,.gres-btn,input[type="submit"]),.gres-lookup-wrap :is(button,.gres-btn,input[type="submit"]){transition:none;transform:none!important;}
}

/* v6.88.23 — readable checkout label at rest and visible native date icon. */
.gres-wrap #gres-checkout,
.gres-wrap #gres-checkout:not(:hover):not(:focus),
.gres-wrap #gres-checkout:disabled {
  background:#2563eb !important;
  border-color:#2563eb !important;
  color:#ffffff !important;
  -webkit-text-fill-color:#ffffff !important;
  text-shadow:none !important;
  opacity:1 !important;
}
.gres-wrap #gres-checkout:hover,
.gres-wrap #gres-checkout:focus-visible {
  background:#1d4ed8 !important;
  border-color:#1d4ed8 !important;
  color:#ffffff !important;
  -webkit-text-fill-color:#ffffff !important;
}
.gres-wrap input[type="date"] {
  color-scheme:dark !important;
  padding-right:12px !important;
}
.gres-wrap input[type="date"]::-webkit-calendar-picker-indicator {
  display:block !important;
  visibility:visible !important;
  opacity:1 !important;
  filter:invert(1) !important;
  cursor:pointer !important;
  width:18px !important;
  height:18px !important;
  margin-left:6px !important;
}
/* v6.88.24: Visible white calendar icon, independent of browser native icon styling. */
.gres-wrap input.gres-date[type="date"], .gres-wrap input#gres-dob[type="date"] {
  color-scheme:dark !important;
  background-color:#050505 !important;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='5' width='18' height='16' rx='2'/%3E%3Cpath d='M16 3v4M8 3v4M3 10h18'/%3E%3C/svg%3E") !important;
  background-repeat:no-repeat !important;
  background-position:right 13px center !important;
  background-size:21px 21px !important;
  padding-right:48px !important;
}
.gres-wrap input.gres-date[type="date"]::-webkit-calendar-picker-indicator, .gres-wrap input#gres-dob[type="date"]::-webkit-calendar-picker-indicator {
  display:block !important; visibility:visible !important; opacity:0 !important;
  filter:none !important; width:28px !important; height:28px !important;
  margin:0 !important; cursor:pointer !important;
}

/* v6.88.25 explicit calendar button inside field */
.gres-wrap .gres-date-control{display:block;position:relative;width:100%}
.gres-wrap .gres-date-control input.gres-date{width:100%;box-sizing:border-box;padding-right:52px!important;background-image:none!important}
.gres-wrap .gres-calendar-trigger{position:absolute!important;right:8px!important;top:50%!important;transform:translateY(-50%)!important;display:flex!important;align-items:center!important;justify-content:center!important;width:34px!important;height:34px!important;min-width:34px!important;padding:0!important;border:0!important;border-radius:6px!important;background:transparent!important;color:#fff!important;opacity:1!important;visibility:visible!important;cursor:pointer!important;z-index:5!important}
.gres-wrap .gres-calendar-trigger svg{display:block!important;stroke:#fff!important;opacity:1!important}
.gres-wrap .gres-calendar-trigger:hover,.gres-wrap .gres-calendar-trigger:focus-visible{background:#263b71!important;outline:2px solid #93c5fd}

/* v6.88.26 — visual parity with Tournament Creator gold field borders */
.gres-wrap{--pbc-ui-gold:var(--pbc-accent,#F5B942);--pbc-ui-blue:var(--pbc-secondary,#2563EB);font-family:inherit}
.gres-wrap :is(input:not([type=checkbox]):not([type=radio]):not([type=hidden]),select,textarea){border:2px solid var(--pbc-ui-gold)!important;border-radius:9px!important;min-height:44px}
.gres-wrap :is(input,select,textarea):focus-visible{outline:2px solid var(--pbc-ui-gold)!important;outline-offset:2px}
.gres-wrap .gres-calendar-trigger{border:0!important;background:transparent!important}
.gres-wrap .gres-calendar-trigger:focus-visible{outline:2px solid #fff!important}


/* Unified tournament-style field interiors: navy rather than black.
   Scoped to frontend form controls; retains gold borders and icons. */
.gres-wrap :is(input:not([type="checkbox"]):not([type="radio"]):not([type="hidden"]):not([type="submit"]):not([type="button"]), select, textarea) {
 background-color:transparent !important;
 color:#ffffff !important;
 -webkit-text-fill-color:#ffffff !important;
 caret-color:#ffffff !important;
 border-color:var(--pbc-ui-gold,#F5B942) !important;
}
.gres-wrap :is(input,textarea)::placeholder { color:#cbd5e1 !important;opacity:1 !important;-webkit-text-fill-color:#cbd5e1 !important; }
.gres-wrap select option {background:#192954 !important;color:#ffffff !important;}
.gres-wrap :is(input[type="date"],input[type="time"]) {color-scheme:dark !important;}
.gres-wrap :is(input,select,textarea):disabled {opacity:.68 !important;}
/* Override earlier forced-black date background without covering the calendar button. */
.gres-wrap input.gres-date[type="date"], .gres-wrap input#gres-dob[type="date"] {background-color:transparent !important;}
.gres-wrap .gres-date-control .gres-calendar-trigger {background:transparent !important;color:#ffffff !important;-webkit-text-fill-color:#ffffff !important;}

/* v6.88.28 — Your Info fields: override the older v6.88.20 forced-black
   identity-field rules with Tournament Creator-style clear navy interiors.
   Keep the original single-border/focus behavior and accessible white text. */
.gres-wrap[data-gres-page="reservation"] :is(#gres-first,#gres-last,#gres-email,#gres-phone,#gres-dob,#gres-dupr-id),
.gres-wrap[data-gres-page="reservation"] :is(#gres-first,#gres-last,#gres-email,#gres-phone,#gres-dob,#gres-dupr-id):is(:hover,:focus,:focus-visible) {
  background:transparent !important;
  background-color:transparent !important;
  background-image:none !important;
  border:2px solid var(--pbc-ui-gold,#F5B942) !important;
  color:#ffffff !important;
  -webkit-text-fill-color:#ffffff !important;
  caret-color:#ffffff !important;
  box-shadow:none !important;
  outline:none !important;
}
/* Retain the calendar icon for date of birth when the optional field appears. */
.gres-wrap[data-gres-page="reservation"] #gres-dob {background-image:initial !important;}

/* v6.88.29 — Tournament Creator-style section spacing and simple page title.
   Limited to the public reservation form; no changes to dashboards or payment flows. */
.gres-wrap[data-gres-page="reservation"] .gres-reservation-page-heading{
  text-align:center!important; padding:10px 12px 22px!important; margin:0 0 8px!important;
  background:transparent!important; border:0!important; box-shadow:none!important;
}
.gres-wrap[data-gres-page="reservation"] .gres-reservation-page-heading h2{
  color:#ffffff!important; font-size:clamp(27px,3vw,36px)!important;
  font-weight:700!important; line-height:1.2!important; margin:0 0 9px!important;
  letter-spacing:0!important; border:0!important; padding:0!important;
}
.gres-wrap[data-gres-page="reservation"] .gres-reservation-page-heading p{
  color:#cbd5e1!important; font-size:15px!important; line-height:1.5!important;
  margin:0!important;
}
.gres-wrap[data-gres-page="reservation"] > .gres-card{
  margin-top:0!important; margin-bottom:18px!important; padding:22px 20px!important;
  border:1px solid var(--pbc-ui-gold,#F5B942)!important;
  border-radius:15px!important; background:#192954!important;
  background-image:none!important; box-shadow:0 6px 18px rgba(15,23,42,.07)!important;
}
.gres-wrap[data-gres-page="reservation"] > .gres-card > h4{
  display:block!important; background:transparent!important; background-image:none!important;
  color:#ffffff!important; border:0!important; border-radius:0!important;
  box-shadow:none!important; padding:0!important; margin:0 0 22px!important;
  font-size:20px!important; line-height:1.35!important; font-weight:500!important;
  text-align:left!important;
}
.gres-wrap[data-gres-page="reservation"] > .gres-card .gres-grid{row-gap:20px!important;}
@media(max-width:640px){
  .gres-wrap[data-gres-page="reservation"] > .gres-card{padding:18px 14px!important;margin-bottom:15px!important;}
  .gres-wrap[data-gres-page="reservation"] .gres-reservation-page-heading{padding:6px 8px 18px!important;}
}
