// Main app — access gate + page router
const { useState: useS } = React;
const BBQ_SESSION_USER_KEY = 'bbq-na-biso-user-name';
const BBQ_SESSION_FAMILY_PASSWORD_KEY = 'bbq-na-biso-family-key';

function AccessGate({ onUnlock, validateFamilyAccess }) {
  const [loginName, setLoginName] = useState(() => sessionStorage.getItem(BBQ_SESSION_USER_KEY) || '');
  const [pw, setPw] = useState('');
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const submit = async () => {
    if (busy) return;
    const cleanName = loginName.trim();
    if (!cleanName) {
      setErr('Entrez votre nom pour que la famille sache qui est connecté.');
      return;
    }
    const localPassword = BBQ_EVENT.familyPassword;
    if (localPassword && pw.trim().toLowerCase() === localPassword) {
      sessionStorage.setItem('bbq-na-biso-unlocked', 'yes');
      sessionStorage.setItem(BBQ_SESSION_USER_KEY, cleanName);
      sessionStorage.setItem(BBQ_SESSION_FAMILY_PASSWORD_KEY, localPassword);
      onUnlock(cleanName);
      return;
    }
    if (!localPassword && validateFamilyAccess) {
      setBusy(true);
      const allowed = await validateFamilyAccess(cleanName, pw.trim());
      setBusy(false);
      if (allowed) {
        sessionStorage.setItem('bbq-na-biso-unlocked', 'yes');
        sessionStorage.setItem(BBQ_SESSION_USER_KEY, cleanName);
        sessionStorage.setItem(BBQ_SESSION_FAMILY_PASSWORD_KEY, pw.trim());
        onUnlock(cleanName, { recordLogin: false });
        return;
      }
    }
    setErr('Ce mot de passe ne fonctionne pas — réessayez ou demandez à Richard, Chantal ou Jules.');
  };
  return (
    <div style={{
      minHeight: '100vh', display: 'grid', placeItems: 'center',
      background: 'linear-gradient(160deg, #0E2E22 0%, #1B5240 100%)',
      padding: 24,
    }}>
      <div style={{ maxWidth: 420, width: '100%', textAlign: 'center', color: 'var(--cream)' }}>
        <div style={{ fontSize: 13, letterSpacing: '0.4em', color: 'var(--gold)', marginBottom: 12 }}>✦ ENSEMBLE. TOUJOURS. ✦</div>
        <h1 className="serif" style={{ fontSize: 48, color: 'white', margin: '0 0 12px' }}>BBQ na Biso<br/>2026</h1>
        <div style={{ fontSize: 14, color: 'var(--cream)', opacity: 0.8, marginBottom: 28 }}>
          Un espace privé pour notre famille. Entrez votre nom et le mot de passe famille pour continuer.
        </div>
        <div style={{
          background: 'rgba(255,255,255,0.06)',
          border: '1px solid rgba(212,168,87,0.2)',
          borderRadius: 14,
          padding: 22,
        }}>
          <div style={{ display: 'grid', gap: 10 }}>
            <input
              autoFocus
              placeholder="Votre nom"
              value={loginName}
              onChange={e => { setLoginName(e.target.value); setErr(''); }}
              onKeyDown={e => e.key === 'Enter' && submit()}
              style={{ border: 0, borderRadius: 10, padding: '13px 14px', outline: 'none', fontSize: 15, background: 'white', color: 'var(--ink)' }}
            />
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'white', borderRadius: 10, padding: '4px 4px 4px 14px', color: 'var(--ink)' }}>
              <span style={{ color: 'var(--green-700)' }}><Icon.Lock /></span>
              <input
              placeholder="Mot de passe famille"
              value={pw}
              onChange={e => { setPw(e.target.value); setErr(''); }}
              onKeyDown={e => e.key === 'Enter' && submit()}
              style={{ flex: 1, border: 0, padding: '10px 0', outline: 'none', fontSize: 15, background: 'transparent' }}
              type="password"
              />
              <button onClick={submit} className="btn btn-coral" style={{ padding: '8px 16px' }} disabled={busy}>
                {busy ? '...' : 'Entrer'} {!busy && <Icon.ArrowRight />}
              </button>
            </div>
          </div>
          {err && <div style={{ color: '#ffb1a3', fontSize: 12, marginTop: 10 }}>{err}</div>}
        </div>
        <div style={{ marginTop: 26, fontSize: 12, color: 'var(--cream)', opacity: 0.6 }}>
          Pas de la famille ? <a href={`mailto:${BBQ_EVENT.organizer.email}`} style={{ color: 'var(--gold)' }}>Contacter Jules</a>
        </div>
      </div>
    </div>
  );
}

function AdminGate({ onUnlock, setPage, validateAdminAccess }) {
  const [pw, setPw] = useState('');
  const [err, setErr] = useState(false);
  const [busy, setBusy] = useState(false);
  const submit = async () => {
    if (busy) return;
    const localPassword = BBQ_EVENT.adminPassword;
    if (localPassword && pw.trim().toLowerCase() === localPassword.toLowerCase()) {
      sessionStorage.setItem('bbq-na-biso-admin-unlocked', 'yes');
      onUnlock();
      return;
    }
    if (!localPassword && validateAdminAccess) {
      setBusy(true);
      const allowed = await validateAdminAccess(pw.trim());
      setBusy(false);
      if (allowed) {
        sessionStorage.setItem('bbq-na-biso-admin-unlocked', 'yes');
        onUnlock({ recordLogin: false });
        return;
      }
    }
    setErr(true);
  };
  return (
    <div className="container" style={{ padding: '42px 24px 56px', maxWidth: 520, margin: '0 auto' }}>
      <div className="card" style={{ textAlign: 'center', padding: 28 }}>
        <div style={{ color: 'var(--green-700)', marginBottom: 10 }}><Icon.Lock s={28} /></div>
        <h1 className="serif" style={{ fontSize: 34, color: 'var(--green-900)', margin: '0 0 8px' }}>Accès organisateur</h1>
        <div style={{ color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.5, marginBottom: 18 }}>
          Zone réservée pour suivre les inscriptions et détails du BBQ.
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <input
            className="input"
            autoFocus
            type="password"
            placeholder="Code admin"
            value={pw}
            onChange={(e) => { setPw(e.target.value); setErr(false); }}
            onKeyDown={(e) => e.key === 'Enter' && submit()}
          />
          <button className="btn btn-coral" onClick={submit} disabled={busy}>{busy ? '...' : 'Entrer'}</button>
        </div>
        {err && <div style={{ color: 'var(--coral)', fontSize: 12, marginTop: 10 }}>Code admin incorrect.</div>}
        <button className="btn btn-white" style={{ marginTop: 16 }} onClick={() => setPage('home')}>Retour à l'accueil</button>
      </div>
    </div>
  );
}

function App() {
  const [currentUserName, setCurrentUserName] = useS(() => sessionStorage.getItem(BBQ_SESSION_USER_KEY) || '');
  const hasFamilyAccessKey = () => !!BBQ_EVENT.familyPassword || !!sessionStorage.getItem(BBQ_SESSION_FAMILY_PASSWORD_KEY);
  const [unlocked, setUnlocked] = useS(() =>
    sessionStorage.getItem('bbq-na-biso-unlocked') === 'yes' && !!(sessionStorage.getItem(BBQ_SESSION_USER_KEY) || '').trim() && hasFamilyAccessKey()
  );
  const [adminUnlocked, setAdminUnlocked] = useS(() => sessionStorage.getItem('bbq-na-biso-admin-unlocked') === 'yes');
  const initialPage = () => {
    const requested = new URLSearchParams(window.location.search).get('page');
    const pages = ['home', 'rsvp', 'announcements', 'food', 'photos', 'schedule', 'kids', 'volunteers', 'faq', 'admin'];
    return pages.includes(requested) ? requested : 'home';
  };
  const [page, setPage] = useS(initialPage);
  const { state, actions } = useBBQStore();
  const unlockAs = (name, options = {}) => {
    setCurrentUserName(name);
    setUnlocked(true);
    if (options.recordLogin !== false) actions.recordLogin(name, 'Site');
  };
  const logout = () => {
    if (currentUserName) actions.recordActivity(currentUserName, 'logout', 'Déconnexion', { page });
    sessionStorage.removeItem('bbq-na-biso-unlocked');
    sessionStorage.removeItem('bbq-na-biso-admin-unlocked');
    sessionStorage.removeItem(BBQ_SESSION_USER_KEY);
    sessionStorage.removeItem(BBQ_SESSION_FAMILY_PASSWORD_KEY);
    sessionStorage.removeItem('bbq-volunteer-name');
    setCurrentUserName('');
    setAdminUnlocked(false);
    setUnlocked(false);
  };
  React.useEffect(() => {
    if (unlocked && currentUserName) actions.claimAnonymousVolunteerSignups(currentUserName);
  }, [unlocked, currentUserName, actions]);

  React.useEffect(() => {
    if (unlocked && currentUserName) {
      actions.recordActivity(currentUserName, 'page_visit', 'Page visitée', { page });
    }
  }, [unlocked, page, currentUserName, actions]);

  if (!unlocked) return <AccessGate onUnlock={unlockAs} validateFamilyAccess={actions.verifyFamilyAccess} />;

  let body;
  switch (page) {
    case 'home': body = <Landing setPage={setPage} state={state} currentUserName={currentUserName} />; break;
    case 'rsvp': body = <RSVP setPage={setPage} state={state} actions={actions} currentUserName={currentUserName} />; break;
    case 'announcements': body = <Announcements setPage={setPage} state={state} actions={actions} currentUserName={currentUserName} />; break;
    case 'food': body = <FoodPage setPage={setPage} state={state} actions={actions} currentUserName={currentUserName} />; break;
    case 'photos': body = <PhotosPage state={state} actions={actions} currentUserName={currentUserName} />; break;
    case 'schedule': body = <SchedulePage />; break;
    case 'kids': body = <KidsPage />; break;
    case 'volunteers': body = <VolunteersPage state={state} actions={actions} currentUserName={currentUserName} />; break;
    case 'faq': body = <FAQPage />; break;
    case 'admin': body = adminUnlocked ? <AdminPage state={state} actions={actions} currentUserName={currentUserName} /> : <AdminGate onUnlock={(options = {}) => { setAdminUnlocked(true); if (options.recordLogin !== false) actions.recordLogin(currentUserName, 'Admin'); }} validateAdminAccess={(password) => actions.verifyAdminAccess(currentUserName, password)} setPage={setPage} />; break;
    default: body = <Landing setPage={setPage} state={state} currentUserName={currentUserName} />;
  }

  return (
    <BrowserChrome url={`BBQnaBiso.com${page === 'home' ? '' : '/' + page}`}>
      <TopNav page={page} setPage={setPage} currentUserName={currentUserName} onLogout={logout} />
      {body}
    </BrowserChrome>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
