<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=1">
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<meta name="theme-color" content="#EEF2FF">
<title><?php echo e(config('mexco.apps.attend.name')); ?> · <?php echo e(config('mexco.apps.attend.tagline')); ?></title>
<?php echo $__env->make('partials.mexco-favicon', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsQR/1.4.0/jsQR.js"></script>
<style>
  :root{
    --primary:#7C3AED;
    --primary-deep:#5B21B6;
    --primary-soft:#F3EEFF;
    --ink:#0F172A;
    --muted:#64748B;
    --line:#E2E8F0;
    --ok:#059669;
    --warn:#D97706;
    --danger:#DC2626;
    --bg:#F8FAFC;
  }
  *{ box-sizing:border-box }
  html,body{ height:100%; margin:0 }
  body{
    font-family:"Plus Jakarta Sans",system-ui,sans-serif;
    background:
      radial-gradient(ellipse 80% 50% at 50% -10%, rgba(124,58,237,.12), transparent 55%),
      linear-gradient(180deg,#F8FAFC 0%,#EEF2FF 50%,#F1F5F9 100%);
    color:var(--ink);
    -webkit-tap-highlight-color:transparent;
  }
  .shell{
    max-width:480px; margin:0 auto; min-height:100dvh;
    background:transparent;
    display:flex; flex-direction:column; position:relative;
  }
  .view{ display:none; flex-direction:column; flex:1; min-height:0 }
  .view.on{ display:flex; animation:viewIn .35s ease both }
  @keyframes viewIn{
    from{ opacity:0; transform:translateY(8px) }
    to{ opacity:1; transform:translateY(0) }
  }
  @media (prefers-reduced-motion:reduce){
    .view.on{ animation:none }
    .event-btn:hover{ transform:none }
  }

  /* Login / event hub */
  #view-login{
    background:
      radial-gradient(ellipse 90% 55% at 50% -8%, rgba(124,58,237,.16), transparent 55%),
      radial-gradient(ellipse 55% 40% at 100% 30%, rgba(6,182,212,.1), transparent 50%),
      linear-gradient(180deg,#F8FAFC 0%,#EEF2FF 42%,#F1F5F9 100%);
  }
  .login-hero{
    position:relative; overflow:hidden;
    padding:1.75rem 1.25rem 1.35rem;
    text-align:center;
  }
  .login-hero::before{
    content:""; position:absolute; inset:0; pointer-events:none;
    background-image:radial-gradient(rgba(91,33,182,.07) 1px, transparent 1px);
    background-size:18px 18px;
    mask-image:linear-gradient(180deg,#000 40%,transparent);
  }
  .login-hero > *{ position:relative; z-index:1 }
  #view-login.is-picked .login-hero{
    padding:1.15rem 1.25rem .85rem;
  }
  #view-login.is-picked .login-hero p,
  #view-login.is-picked .login-kicker{ display:none }
  #view-login.is-picked .attend-logo{
    width:min(148px,48vw); margin-bottom:.35rem;
  }
  #view-login.is-picked .login-hero h1{
    font-size:1.15rem; margin:0;
  }
  .attend-logo{
    display:block; width:min(200px,62vw); height:auto; margin:0 auto .7rem;
    object-fit:contain; animation:logoIn .6s ease both;
  }
  @keyframes logoIn{
    from{ opacity:0; transform:scale(.94) }
    to{ opacity:1; transform:scale(1) }
  }
  .login-kicker{
    display:inline-flex; align-items:center; gap:.4rem;
    margin:0 0 .5rem; padding:.28rem .65rem;
    font-size:.66rem; font-weight:800; letter-spacing:.12em; text-transform:uppercase;
    color:var(--primary-deep); background:rgba(255,255,255,.75);
    border:1px solid rgba(196,181,253,.7); border-radius:999px;
  }
  .login-kicker::before{
    content:""; width:6px; height:6px; border-radius:50%; background:#34D399;
  }
  .login-hero h1{
    margin:0 0 .4rem; font-size:clamp(1.45rem,5vw,1.7rem); font-weight:800;
    letter-spacing:-.03em; color:var(--ink);
  }
  .login-hero p{
    margin:0 auto; max-width:19rem; font-size:.9rem; color:var(--muted); line-height:1.45;
  }

  .hub-scroll{
    flex:1; overflow:auto;
    padding:0 1.1rem calc(1.25rem + env(safe-area-inset-bottom));
  }

  .login-card{
    background:#fff; border:1px solid rgba(226,232,240,.95);
    border-radius:1.25rem; padding:1.15rem 1.1rem 1.05rem;
    box-shadow:0 10px 28px rgba(15,23,42,.06);
    animation:hubIn .4s ease both;
  }
  @keyframes hubIn{
    from{ opacity:0; transform:translateY(12px) }
    to{ opacity:1; transform:translateY(0) }
  }
  .login-card label{
    display:block; font-size:.78rem; font-weight:700; color:var(--ink); margin-bottom:.4rem;
  }
  .form-control{
    border-radius:.9rem; padding:.85rem .95rem; border-color:var(--line);
    font-weight:500; background:#F8FAFC;
  }
  .form-control:focus{
    border-color:#C4B5FD; background:#fff;
    box-shadow:0 0 0 3px rgba(124,58,237,.14);
  }
  .field-hint{ font-size:.75rem; color:var(--muted); margin-top:.45rem; line-height:1.4 }
  .demo-chip{
    margin-top:.9rem; padding:.7rem .8rem; border-radius:12px;
    background:#F8FAFC; border:1px dashed #CBD5E1;
    font-size:.74rem; color:var(--muted); line-height:1.45;
  }
  .demo-chip code{
    font-family:"JetBrains Mono",ui-monospace,monospace;
    font-size:.7rem; color:var(--primary-deep); background:#F3EEFF;
    padding:.08rem .3rem; border-radius:4px;
  }

  .identity{
    display:flex; align-items:center; gap:.85rem;
    background:#fff; border:1px solid var(--line); border-radius:1.2rem;
    padding:.9rem 1rem; margin-bottom:1.1rem;
    box-shadow:0 8px 24px rgba(15,23,42,.05);
    animation:hubIn .4s ease both;
  }
  .identity-avatar{
    flex:none; width:46px; height:46px; border-radius:15px;
    display:grid; place-items:center;
    background:linear-gradient(145deg,#7C3AED,#06B6D4);
    color:#fff; font-weight:800; font-size:1rem; letter-spacing:-.02em;
  }
  .identity-body{ min-width:0; flex:1 }
  .identity-label{
    font-size:.65rem; font-weight:800; letter-spacing:.1em;
    text-transform:uppercase; color:var(--muted);
  }
  .identity-name{
    font-weight:800; font-size:1.02rem; letter-spacing:-.02em;
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
  }
  .identity-email{
    font-size:.78rem; color:var(--muted);
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
  }
  .btn-switch{
    flex:none; border:0; background:#F1F5F9; color:var(--ink);
    font-size:.78rem; font-weight:700; padding:.5rem .75rem; border-radius:999px;
  }
  .btn-switch:hover{ background:#E2E8F0 }

  .hub-section{
    display:flex; align-items:flex-end; justify-content:space-between;
    gap:.75rem; margin:0 0 .75rem;
  }
  .hub-section h2{
    margin:0; font-size:1.05rem; font-weight:800; letter-spacing:-.02em;
  }
  .hub-section p{
    margin:.15rem 0 0; font-size:.78rem; color:var(--muted);
  }
  .hub-count{
    font-size:.72rem; font-weight:800; color:var(--primary-deep);
    background:#F3EEFF; border:1px solid #DDD6FE;
    padding:.28rem .6rem; border-radius:999px;
  }

  .event-btn{
    width:100%; text-align:left; border:1px solid var(--line); background:#fff;
    border-radius:1.15rem; padding:1rem 1rem 1rem 1.05rem; margin-bottom:.7rem;
    display:flex; align-items:center; gap:.9rem;
    box-shadow:0 4px 16px rgba(15,23,42,.04);
    transition:border-color .18s ease, box-shadow .18s ease, transform .18s ease;
    animation:hubIn .45s ease both;
  }
  .event-btn:nth-child(2){ animation-delay:.05s }
  .event-btn:nth-child(3){ animation-delay:.1s }
  .event-btn:hover{
    border-color:#C4B5FD; box-shadow:0 12px 28px rgba(91,33,182,.1); transform:translateY(-2px);
  }
  .event-btn:active{ transform:translateY(0) }
  .event-ico{
    flex:none; width:48px; height:48px; border-radius:14px;
    display:grid; place-items:center;
    background:linear-gradient(145deg,#F3EEFF,#E0F2FE);
    color:var(--primary-deep);
  }
  .event-ico svg{ width:22px; height:22px; stroke:currentColor; fill:none; stroke-width:1.8; stroke-linecap:round; stroke-linejoin:round }
  .event-body{ min-width:0; flex:1 }
  .event-btn .name{ font-weight:800; font-size:1.02rem; letter-spacing:-.02em; line-height:1.2 }
  .event-btn .meta{ display:flex; flex-wrap:wrap; gap:.35rem; margin-top:.4rem }
  .role-chip{
    display:inline-flex; align-items:center;
    font-size:.66rem; font-weight:800; letter-spacing:.04em; text-transform:uppercase;
    color:#5B21B6; background:#F3EEFF; border:1px solid #DDD6FE;
    padding:.18rem .5rem; border-radius:999px;
  }
  .event-cta{
    flex:none; display:grid; place-items:center;
    width:36px; height:36px; border-radius:12px;
    background:#F3EEFF; color:var(--primary-deep);
  }

  .btn{ border-radius:.9rem; font-weight:700 }
  .btn-primary{
    --bs-btn-bg:var(--primary); --bs-btn-border-color:var(--primary);
    --bs-btn-hover-bg:var(--primary-deep); --bs-btn-hover-border-color:var(--primary-deep);
    padding:.85rem 1rem; border-radius:14px;
  }
  .btn-ghost{
    background:#F1F5F9; border:1px solid transparent; color:var(--ink);
  }
  .btn-ghost:hover{ background:#E2E8F0 }

  .empty-events{
    text-align:center; padding:2rem 1.1rem; color:var(--muted); font-size:.88rem;
    background:rgba(255,255,255,.8); border:1px dashed var(--line); border-radius:1.15rem;
  }

  /* Scanner — camera-first check-in */
  #view-scan{
    background:#070B16;
    color:#fff;
  }
  #view-scan .scan-frame{
    flex:1; min-height:0; display:flex; flex-direction:column;
    position:relative;
  }
  .scan-top{
    position:absolute; top:0; left:0; right:0; z-index:5;
    display:flex; align-items:center; gap:.65rem;
    padding:max(.75rem, env(safe-area-inset-top)) .9rem .85rem;
    background:linear-gradient(180deg, rgba(7,11,22,.88) 0%, rgba(7,11,22,.45) 70%, transparent);
  }
  .scan-top .title{
    font-weight:800; font-size:1rem; letter-spacing:-.02em;
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
  }
  .scan-top .live{
    display:inline-flex; align-items:center; gap:.35rem;
    margin-top:.2rem; font-size:.68rem; font-weight:700;
    letter-spacing:.04em; text-transform:uppercase; color:#A5B4FC;
  }
  .scan-top .live i{
    width:7px; height:7px; border-radius:50%; background:#34D399;
    box-shadow:0 0 0 0 rgba(52,211,153,.55);
    animation:livePulse 1.6s ease infinite;
  }
  @keyframes livePulse{
    0%{ box-shadow:0 0 0 0 rgba(52,211,153,.55) }
    70%{ box-shadow:0 0 0 8px rgba(52,211,153,0) }
    100%{ box-shadow:0 0 0 0 rgba(52,211,153,0) }
  }
  .icon-btn{
    width:40px; height:40px; border-radius:14px; border:0;
    background:rgba(255,255,255,.1); color:#fff;
    display:grid; place-items:center; flex:none;
    backdrop-filter:blur(8px);
    transition:background .15s ease;
  }
  .icon-btn:hover{ background:rgba(255,255,255,.18) }

  .scan-stage{
    position:relative; flex:1; min-height:280px;
    background:#0B1020; overflow:hidden;
  }
  .scan-stage video{
    width:100%; height:100%; object-fit:cover; display:block;
  }
  .scan-metrics{
    position:absolute; top:4.6rem; left:.9rem; right:.9rem; z-index:4;
    display:grid; grid-template-columns:1fr 1fr; gap:.5rem;
    pointer-events:none;
  }
  .scan-metric{
    background:rgba(15,23,42,.55); border:1px solid rgba(255,255,255,.12);
    backdrop-filter:blur(12px); border-radius:14px; padding:.65rem .75rem;
  }
  .scan-metric .l{
    font-size:.62rem; font-weight:700; letter-spacing:.08em;
    text-transform:uppercase; color:rgba(226,232,240,.75);
  }
  .scan-metric .n{
    margin-top:.15rem; font-size:1.35rem; font-weight:800;
    letter-spacing:-.03em; line-height:1; color:#fff;
  }
  .scan-metric .n em{ font-style:normal; color:#C4B5FD }

  .viewfinder{
    position:absolute; inset:18% 14% 22%;
    border:1.5px solid rgba(255,255,255,.35);
    border-radius:1.25rem; pointer-events:none;
    box-shadow:0 0 0 9999px rgba(0,0,0,.42);
  }
  .viewfinder::before,.viewfinder::after,
  .viewfinder b:before,.viewfinder b:after{
    content:""; position:absolute; width:28px; height:28px;
    border:3px solid #A78BFA;
  }
  .viewfinder::before{ top:-2px; left:-2px; border-right:0; border-bottom:0; border-radius:12px 0 0 0 }
  .viewfinder::after{ top:-2px; right:-2px; border-left:0; border-bottom:0; border-radius:0 12px 0 0 }
  .vf-br,.vf-bl{
    position:absolute; width:28px; height:28px; border:3px solid #A78BFA;
  }
  .vf-bl{ bottom:-2px; left:-2px; border-right:0; border-top:0; border-radius:0 0 0 12px }
  .vf-br{ bottom:-2px; right:-2px; border-left:0; border-top:0; border-radius:0 0 12px 0 }
  .vf-pulse{
    position:absolute; left:16%; right:16%; top:50%; height:2px;
    background:linear-gradient(90deg,transparent,#C4B5FD 30%,#67E8F9 50%,#C4B5FD 70%,transparent);
    box-shadow:0 0 18px rgba(167,139,250,.55);
    animation:scanLine 2.4s ease-in-out infinite; pointer-events:none;
  }
  @keyframes scanLine{
    0%,100%{ transform:translateY(-78px); opacity:.25 }
    50%{ transform:translateY(78px); opacity:1 }
  }
  .scan-msg{
    position:absolute; left:0; right:0; bottom:0; z-index:3;
    padding:1.1rem 1rem 1rem;
    background:linear-gradient(transparent, rgba(0,0,0,.82));
    color:#fff; font-size:.88rem; text-align:center; font-weight:600;
  }

  .scan-dock{
    position:relative; z-index:6;
    background:#fff; color:var(--ink);
    border-radius:1.35rem 1.35rem 0 0;
    padding:1rem 1rem calc(1rem + env(safe-area-inset-bottom));
    box-shadow:0 -12px 40px rgba(0,0,0,.28);
    max-height:46dvh; overflow:auto;
  }
  .scan-dock-handle{
    width:36px; height:4px; border-radius:99px; background:#E2E8F0;
    margin:0 auto .85rem;
  }

  .result-card{
    border-radius:1.05rem; padding:1rem 1.05rem; margin-bottom:.85rem; color:#fff;
    animation:resultIn .28s ease both;
  }
  @keyframes resultIn{
    from{ opacity:0; transform:translateY(10px) scale(.98) }
    to{ opacity:1; transform:translateY(0) scale(1) }
  }
  .result-card.ok{ background:linear-gradient(145deg,#059669,#047857) }
  .result-card.warn{ background:linear-gradient(145deg,#D97706,#B45309) }
  .result-card.err{ background:linear-gradient(145deg,#DC2626,#B91C1C) }
  .result-card .who{ font-size:1.15rem; font-weight:800; margin:.15rem 0; letter-spacing:-.02em }
  .result-card .meta{ opacity:.92; font-size:.8rem; line-height:1.4 }
  .badge-role{
    display:inline-block; padding:.28rem .65rem; border-radius:99px;
    font-size:.7rem; font-weight:700; background:rgba(255,255,255,.22);
  }

  .actions{
    display:grid; grid-template-columns:1.4fr 1fr; gap:.55rem;
  }
  .actions .btn-primary{
    padding:.85rem 1rem; border-radius:14px; font-size:.95rem;
  }
  .actions .btn-ghost{
    padding:.85rem 1rem; border-radius:14px; font-size:.88rem;
    background:#F1F5F9; border:0; color:var(--ink); font-weight:700;
  }
  .manual-box{
    margin-top:.75rem; padding:.9rem; border-radius:14px;
    background:#F8FAFC; border:1px solid var(--line);
  }
  .manual-box label{ font-size:.75rem; font-weight:700; margin-bottom:.4rem; display:block }

  .recent-head{
    display:flex; align-items:center; justify-content:space-between;
    margin:1rem 0 .45rem; font-size:.82rem; font-weight:800;
  }
  .recent-head span:last-child{
    font-size:.7rem; font-weight:700; color:var(--muted);
  }
  .recent-item{
    display:flex; justify-content:space-between; align-items:center; gap:.75rem;
    padding:.7rem 0; border-bottom:1px solid #F1F5F9;
  }
  .recent-item:last-child{ border-bottom:0 }
  .recent-item .n{ font-weight:700; font-size:.88rem }
  .recent-item .s{ font-size:.72rem; color:var(--muted) }
  .pill-ok{ color:#166534; background:#DCFCE7; padding:.22rem .55rem; border-radius:99px; font-size:.68rem; font-weight:700 }
  .pill-dup{ color:#92400E; background:#FEF3C7; padding:.22rem .55rem; border-radius:99px; font-size:.68rem; font-weight:700 }

  .toast{
    position:fixed; left:50%; bottom:1.25rem; transform:translateX(-50%) translateY(120%);
    background:var(--ink); color:#fff; padding:.75rem 1.05rem; border-radius:.9rem;
    font-size:.85rem; font-weight:600; z-index:50; transition:transform .22s ease;
    max-width:min(420px, calc(100% - 2rem));
    box-shadow:0 12px 32px rgba(15,23,42,.25);
  }
  .toast.show{ transform:translateX(-50%) translateY(0) }
  .mono{ font-family:"JetBrains Mono",ui-monospace,monospace }
  @media (prefers-reduced-motion:reduce){
    .scan-top .live i,.vf-pulse,.login-card,.identity,.event-btn{ animation:none }
  }
</style>
</head>
<body>
<div class="shell">

  <!-- LOGIN / PICK EVENT -->
  <section id="view-login" class="view on">
    <div class="login-hero">
      <?php echo $__env->make('partials.mexco-brand', ['app' => 'attend', 'class' => 'attend-logo'], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
      <div class="login-kicker">Check-in ready</div>
      <h1><?php echo e(config('mexco.apps.attend.name')); ?></h1>
      <p>Sign in with the account your organiser registered. Then open an assigned event to start scanning.</p>
    </div>
    <div class="hub-scroll">
      <div class="login-card" id="loginForm">
        <label for="loginEmail">Email</label>
        <input type="email" id="loginEmail" class="form-control mb-3" placeholder="you@organisation.edu" autocomplete="username">
        <label for="loginIc">IC / ID number</label>
        <input type="password" id="loginIc" class="form-control" placeholder="Your IC number" autocomplete="current-password" inputmode="numeric">
        <div class="field-hint">Use the same email and IC saved under Committee Accounts.</div>
        <div class="text-danger small fw-semibold mt-2" id="loginErr" style="min-height:1.1rem"></div>
        <button type="button" class="btn btn-primary w-100 mt-2" id="btnLogin">Continue</button>
        <?php
          $attendDemo = collect(config('mexco.demo_sandbox.participants', []))->firstWhere('role', 'COMMITTEE');
        ?>
        <?php if($attendDemo): ?>
          <div class="demo-chip">
            Demo committee · <code><?php echo e($attendDemo['email']); ?></code>
            · IC <code><?php echo e($attendDemo['ic']); ?></code>
          </div>
        <?php endif; ?>
      </div>

      <div id="eventPicker" class="d-none">
        <div class="identity">
          <div class="identity-avatar" id="signedInAvatar" aria-hidden="true">C</div>
          <div class="identity-body">
            <div class="identity-label">Signed in</div>
            <div class="identity-name" id="signedInName">Committee</div>
            <div class="identity-email" id="signedInEmail"></div>
          </div>
          <button type="button" class="btn-switch" id="btnSwitchAccount">Switch</button>
        </div>

        <div class="hub-section">
          <div>
            <h2>Your events</h2>
            <p>Tap an event to open the scanner</p>
          </div>
          <span class="hub-count" id="eventCount">0</span>
        </div>
        <div id="eventList">
          <div class="empty-events">No assigned events yet.</div>
        </div>
      </div>
    </div>
  </section>

  <!-- SCANNER -->
  <section id="view-scan" class="view">
    <div class="scan-frame">
      <div class="scan-top">
        <button type="button" class="icon-btn" id="btnBack" aria-label="Back">
          <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M15 18l-6-6 6-6"/></svg>
        </button>
        <div style="min-width:0;flex:1">
          <div class="title" id="scanEventName">Event</div>
          <div class="live"><i aria-hidden="true"></i> Live check-in</div>
        </div>
        <button type="button" class="icon-btn" id="btnSignOut" aria-label="Sign out" title="Sign out">
          <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/><path d="M16 17l5-5-5-5"/><path d="M21 12H9"/></svg>
        </button>
      </div>

      <div class="scan-stage" id="scanStage">
        <video id="scanVideo" playsinline muted></video>
        <div class="scan-metrics">
          <div class="scan-metric">
            <div class="l">Today</div>
            <div class="n"><em id="statVerified">0</em></div>
          </div>
          <div class="scan-metric">
            <div class="l">Total</div>
            <div class="n" id="statTotal">0</div>
          </div>
        </div>
        <div class="viewfinder">
          <span class="vf-bl" aria-hidden="true"></span>
          <span class="vf-br" aria-hidden="true"></span>
        </div>
        <div class="vf-pulse" aria-hidden="true"></div>
        <div class="scan-msg" id="scanMsg">Starting camera…</div>
      </div>

      <div class="scan-dock">
        <div class="scan-dock-handle" aria-hidden="true"></div>
        <div id="resultBox" class="d-none"></div>
        <div class="actions">
          <button type="button" class="btn btn-primary" id="btnRescan">Scan next</button>
          <button type="button" class="btn btn-ghost" id="btnManual">Enter code</button>
        </div>
        <div class="manual-box d-none" id="manualBox">
          <label for="manualCode">UserID or pass code</label>
          <input type="text" id="manualCode" class="form-control mono" placeholder="UID:MXP-XXXXXXXX or UserID">
          <button type="button" class="btn btn-primary w-100 mt-2" id="btnManualGo">Verify</button>
        </div>
        <div class="recent-head">
          <span>Recent</span>
          <span id="recentCount">No scans yet</span>
        </div>
        <div id="recentList"></div>
      </div>
    </div>
  </section>
</div>

<div class="toast" id="toast"></div>

<script>
const API = <?php echo json_encode(url('/mexco/api'), 15, 512) ?>;
const CSRF = document.querySelector('meta[name="csrf-token"]').content;
const $ = id => document.getElementById(id);

let EV = null, events = [], busy = false, sessionUser = null;
let scanStream = null, scanTimer = null, detector = null, cvs = null, ctx = null;
let recent = [];

function show(id){
  document.querySelectorAll('.view').forEach(v => v.classList.toggle('on', v.id === id));
}
function toast(msg){
  const t = $('toast');
  t.textContent = msg;
  t.classList.add('show');
  clearTimeout(toast._t);
  toast._t = setTimeout(() => t.classList.remove('show'), 2600);
}
function esc(s){
  return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
async function api(path, opts = {}){
  const res = await fetch(API + path, {
    method: opts.method || 'GET',
    credentials: 'same-origin',
    headers: {
      'Accept': 'application/json',
      'X-CSRF-TOKEN': CSRF,
      'X-Requested-With': 'XMLHttpRequest',
      ...(opts.body ? { 'Content-Type': 'application/json' } : {}),
      ...(opts.headers || {}),
    },
    body: opts.body ? JSON.stringify(opts.body) : undefined,
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw Object.assign(new Error(data.error || data.msg || 'Request failed'), { data, status: res.status });
  return data;
}

function shortOf(e){
  return e.shortName || e.eventName || e.name || 'Event';
}

function showLoginForm(){
  $('loginForm').classList.remove('d-none');
  $('eventPicker').classList.add('d-none');
  $('view-login').classList.remove('is-picked');
  events = [];
  sessionUser = null;
}

function initialsOf(name){
  const parts = String(name || 'C').trim().split(/\s+/).filter(Boolean);
  if (!parts.length) return 'C';
  if (parts.length === 1) return parts[0].slice(0, 1).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

function showEventPicker(user, matches){
  sessionUser = user;
  events = matches || [];
  $('loginForm').classList.add('d-none');
  $('eventPicker').classList.remove('d-none');
  $('view-login').classList.add('is-picked');
  $('signedInName').textContent = user?.name || 'Committee';
  $('signedInEmail').textContent = user?.email || '';
  $('signedInAvatar').textContent = initialsOf(user?.name);
  paintEvents();
}

function paintEvents(){
  const list = $('eventList');
  const count = $('eventCount');
  if (!events.length) {
    count.textContent = '0';
    list.innerHTML = '<div class="empty-events">No assigned events. Ask the organiser to register you as COMMITTEE.</div>';
    return;
  }
  count.textContent = events.length === 1 ? '1 event' : (events.length + ' events');
  list.innerHTML = events.map(e => `
    <button type="button" class="event-btn" data-id="${esc(e.eventId)}">
      <div class="event-ico" aria-hidden="true">
        <svg viewBox="0 0 24 24"><path d="M3 7V5a2 2 0 012-2h2"/><path d="M17 3h2a2 2 0 012 2v2"/><path d="M21 17v2a2 2 0 01-2 2h-2"/><path d="M7 21H5a2 2 0 01-2-2v-2"/><path d="M7 8h10v8H7z"/></svg>
      </div>
      <div class="event-body">
        <div class="name">${esc(shortOf(e))}</div>
        <div class="meta">
          <span class="role-chip">${esc(e.role || 'VISITOR')}</span>
          <span class="role-chip">COMMITTEE</span>
        </div>
      </div>
      <div class="event-cta" aria-hidden="true">
        <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24"><path d="M9 18l6-6-6-6"/></svg>
      </div>
    </button>`).join('');
}

async function doLogin(){
  const email = $('loginEmail').value.trim();
  const ic = $('loginIc').value.trim();
  const err = $('loginErr');
  err.textContent = '';
  if (!email) { err.textContent = 'Enter your email.'; return; }
  if (!ic) { err.textContent = 'Enter your IC / ID number.'; return; }
  $('btnLogin').disabled = true;
  try {
    const r = await api('/auth/attend', { method: 'POST', body: { email, ic } });
    showEventPicker(
      { email: r.email, name: r.name, slug: r.slug },
      r.matches || []
    );
    toast('Signed in');
  } catch (e) {
    err.textContent = e.data?.error || e.message || 'Could not sign in.';
  } finally {
    $('btnLogin').disabled = false;
  }
}

async function openEvent(id){
  try {
    const r = await api('/events/' + id + '/attend', { method: 'POST' });
    EV = id;
    $('scanEventName').textContent = r.eventName || shortOf(events.find(x => x.eventId === id) || { name: id });
    show('view-scan');
    await refreshStats();
    startScan();
  } catch (e) {
    toast(e.data?.error || e.message || 'Could not open this event.');
  }
}

async function restoreSession(){
  const params = new URLSearchParams(window.location.search);
  const forceSwitch = params.has('switch') || params.has('logout');
  const prefillsEmail = (params.get('email') || '').trim();

  if (forceSwitch) {
    try { await api('/auth/signout', { method: 'POST' }); } catch {}
    showLoginForm();
    if (prefillsEmail) {
      $('loginEmail').value = prefillsEmail;
      $('loginIc').focus();
    }
    // Drop one-time params so refresh does not keep signing out.
    if (window.history?.replaceState) {
      window.history.replaceState({}, '', window.location.pathname);
    }
    return;
  }

  try {
    const s = await api('/auth/session');
    if (s.ok && s.attend && Array.isArray(s.matches) && s.matches.length) {
      showEventPicker(
        { email: s.email, name: s.name, slug: s.slug },
        s.matches
      );
      return;
    }
  } catch {
    /* stay on login */
  }

  if (prefillsEmail) {
    $('loginEmail').value = prefillsEmail;
    $('loginIc').focus();
  }
}

async function refreshStats(){
  try {
    const people = await api('/events/' + EV + '/people');
    const verified = people.filter(p => p.verified);
    const today = new Date().toDateString();
    const todayCount = verified.filter(p => p.verified && new Date(p.verified).toDateString() === today).length;
    $('statTotal').textContent = verified.length;
    $('statVerified').textContent = todayCount;
  } catch {
    /* ignore */
  }
}

function paintRecent(){
  const el = $('recentList');
  const count = $('recentCount');
  if (!recent.length) {
    el.innerHTML = '<div class="s" style="padding:.15rem 0 .35rem">No scans yet.</div>';
    if (count) count.textContent = 'No scans yet';
    return;
  }
  if (count) count.textContent = recent.length + (recent.length === 1 ? ' scan' : ' scans');
  el.innerHTML = recent.map(r => `
    <div class="recent-item">
      <div>
        <div class="n">${esc(r.name)}</div>
        <div class="s">${esc(r.role || '')}${r.org ? ' · ' + esc(r.org) : ''}</div>
      </div>
      <div class="text-end">
        <span class="${r.already ? 'pill-dup' : 'pill-ok'}">${r.already ? 'Already' : 'Verified'}</span>
        <div class="s mt-1">${new Date(r.at).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}</div>
      </div>
    </div>`).join('');
}

function showResult(kind, title, rec, msg){
  const box = $('resultBox');
  box.className = 'result-card ' + kind;
  const role = rec?.role ? `<span class="badge-role">${esc(rec.role)}</span>` : '';
  box.innerHTML = `
    <div class="d-flex justify-content-between align-items-start gap-2">
      <div>
        <div style="font-size:.72rem;opacity:.9;font-weight:700;letter-spacing:.06em;text-transform:uppercase">${esc(title)}</div>
        <div class="who">${esc(rec?.name || 'Participant')}</div>
        <div class="meta">${rec?.user_id ? esc(rec.user_id) + '<br>' : ''}${esc(rec?.email || '')}${rec?.org ? '<br>' + esc(rec.org) : ''}</div>
      </div>
      ${role}
    </div>
    <div class="meta mt-2">${esc(msg || '')}</div>`;
  box.classList.remove('d-none');
}

async function verifySlug(slug){
  if (busy) return;
  busy = true;
  stopTick();
  $('scanMsg').textContent = 'Checking pass…';
  try {
    const r = await api('/events/' + EV + '/verify/' + encodeURIComponent(slug), { method: 'POST' });
    if (!r.ok) {
      showResult('err', 'Not verified', { name: slug }, r.msg || 'Verification failed.');
      toast(r.msg || 'Verification failed');
      return;
    }
    const rec = r.rec || {};
    const already = !!r.already;
    showResult(already ? 'warn' : 'ok', already ? 'Already verified' : 'Attendance verified', rec, r.msg || '');
    recent.unshift({
      name: rec.name || slug,
      role: rec.role || '',
      org: rec.org || '',
      already,
      at: Date.now(),
    });
    recent = recent.slice(0, 12);
    paintRecent();
    await refreshStats();
    if (navigator.vibrate) navigator.vibrate(already ? [40, 40, 40] : [30, 60, 30]);
    toast(already ? 'Already verified' : 'Verified successfully');
  } catch (e) {
    showResult('err', 'Not verified', { name: slug }, e.data?.msg || e.data?.error || e.message || 'Verification failed.');
    toast(e.data?.msg || e.message || 'Verification failed');
  } finally {
    busy = false;
    $('scanMsg').textContent = 'Ready. Scan the next pass, or tap Scan next.';
  }
}

function parsePass(text){
  const raw = String(text || '').trim();
  const m = raw.match(/^(?:PASS|UID|USERID|USER|MEXCO):(.+)$/i);
  if (m) return m[1].trim();
  if (/^MXP-[A-Z0-9]+$/i.test(raw)) return raw.toUpperCase();
  if (/^[a-z0-9_]+$/i.test(raw)) return raw;
  return null;
}

async function handleScanText(text){
  const slug = parsePass(text);
  if (!slug) {
    $('scanMsg').textContent = 'That isn’t a participant pass QR.';
    toast('Scan a participant UserID QR');
    return;
  }
  await verifySlug(slug);
}

async function startScan(){
  stopScan();
  $('scanMsg').textContent = 'Starting camera…';
  if (!navigator.mediaDevices?.getUserMedia) {
    $('scanMsg').textContent = 'This browser can’t open the camera. Use manual entry.';
    return;
  }
  try {
    scanStream = await navigator.mediaDevices.getUserMedia({
      video: { facingMode: { ideal: 'environment' } },
      audio: false,
    });
  } catch (e) {
    $('scanMsg').textContent = e?.name === 'NotAllowedError'
      ? 'Camera blocked. Allow camera access, or enter the pass code manually.'
      : 'No camera available. Use manual entry.';
    return;
  }
  const v = $('scanVideo');
  v.srcObject = scanStream;
  try { await v.play(); } catch {}
  if ('BarcodeDetector' in window) {
    try { detector = new window.BarcodeDetector({ formats: ['qr_code'] }); }
    catch { detector = null; }
  }
  if (!cvs) {
    cvs = document.createElement('canvas');
    ctx = cvs.getContext('2d', { willReadFrequently: true });
  }
  $('scanMsg').textContent = 'Point at the participant’s pass QR.';
  scanTimer = setInterval(tickScan, 220);
}

function stopTick(){
  if (scanTimer) { clearInterval(scanTimer); scanTimer = null; }
}

function stopScan(){
  stopTick();
  if (scanStream) {
    scanStream.getTracks().forEach(t => t.stop());
    scanStream = null;
  }
  const v = $('scanVideo');
  if (v) v.srcObject = null;
  detector = null;
}

async function tickScan(){
  const v = $('scanVideo');
  if (!v?.videoWidth || busy) return;
  try {
    if (detector) {
      const codes = await detector.detect(v);
      if (codes?.[0]?.rawValue) {
        await handleScanText(codes[0].rawValue);
        return;
      }
    }
    cvs.width = v.videoWidth;
    cvs.height = v.videoHeight;
    ctx.drawImage(v, 0, 0);
    const img = ctx.getImageData(0, 0, cvs.width, cvs.height);
    const code = window.jsQR?.(img.data, img.width, img.height, { inversionAttempts: 'dontInvert' });
    if (code?.data) await handleScanText(code.data);
  } catch {
    /* keep scanning */
  }
}

$('eventList').addEventListener('click', e => {
  const btn = e.target.closest('[data-id]');
  if (btn) openEvent(btn.dataset.id);
});
$('btnLogin').onclick = () => doLogin();
$('loginIc').addEventListener('keydown', e => { if (e.key === 'Enter') doLogin(); });
$('loginEmail').addEventListener('keydown', e => { if (e.key === 'Enter') $('loginIc').focus(); });
$('btnSwitchAccount').onclick = async () => {
  try { await api('/auth/signout', { method: 'POST' }); } catch {}
  EV = null;
  recent = [];
  paintRecent();
  $('loginEmail').value = '';
  $('loginIc').value = '';
  $('loginErr').textContent = '';
  showLoginForm();
};
$('btnBack').onclick = async () => {
  stopScan();
  show('view-login');
  if (sessionUser) showEventPicker(sessionUser, events);
  else showLoginForm();
};
$('btnSignOut').onclick = async () => {
  stopScan();
  try { await api('/auth/signout', { method: 'POST' }); } catch {}
  EV = null;
  recent = [];
  paintRecent();
  $('loginEmail').value = '';
  $('loginIc').value = '';
  showLoginForm();
  show('view-login');
  toast('Signed out');
};
$('btnRescan').onclick = () => {
  $('resultBox').classList.add('d-none');
  busy = false;
  startScan();
};
$('btnManual').onclick = () => {
  $('manualBox').classList.toggle('d-none');
  if (!$('manualBox').classList.contains('d-none')) $('manualCode').focus();
};
$('btnManualGo').onclick = async () => {
  const slug = parsePass($('manualCode').value);
  if (!slug) { toast('Enter UID:MXP-… or the participant UserID'); return; }
  await verifySlug(slug);
};

document.addEventListener('visibilitychange', () => {
  if (document.hidden) stopTick();
  else if ($('view-scan').classList.contains('on') && scanStream && !busy) {
    scanTimer = setInterval(tickScan, 220);
  }
});

restoreSession();
</script>
</body>
</html>
<?php /**PATH C:\laragon\www\myapp\resources\views/mexco/committee.blade.php ENDPATH**/ ?>