// Top-level app shell, router-to-screen mapping, and persona switcher.

const { useState: aaUseState, useEffect: aaUseEffect } = React;

const MEMBER_ROUTES = new Set(['landing', 'login', 'register', 'dashboard', 'enter', 'membership', 'membership-success', 'stats', 'achievements', 'profile', 'occupancy']);
const ADMIN_ROUTES  = new Set(['admin', 'admin-members', 'admin-member-detail', 'admin-logs', 'admin-door-qr', 'admin-settings', 'admin-stub', 'admin-passes']);

const SCREEN_LABELS = {
  landing: 'Úvod',
  login: 'Prihlásenie',
  register: 'Registrácia',
  dashboard: 'Dashboard',
  enter: 'Vstup',
  membership: 'Permanentky',
  'membership-success': 'Platba úspešná',
  stats: 'Štatistiky',
  achievements: 'Odznaky',
  profile: 'Profil',
  occupancy: 'Obsadenosť gymu',
  admin: 'Admin · Dashboard',
  'admin-members': 'Admin · Členovia',
  'admin-member-detail': 'Admin · Detail člena',
  'admin-logs': 'Admin · Vstupy (live)',
  'admin-door-qr': 'Admin · QR poster',
  'admin-settings': 'Admin · Nastavenia',
};

function pickScreen(route) {
  switch (route) {
    case 'landing':            return <ScreenLanding />;
    case 'login':              return <ScreenLogin />;
    case 'register':           return <ScreenRegister />;
    case 'dashboard':          return <ScreenDashboard />;
    case 'enter':              return <ScreenEnter />;
    case 'membership':         return <ScreenMembership />;
    case 'membership-success': return <ScreenMembershipSuccess />;
    case 'stats':              return <ScreenStats />;
    case 'achievements':       return <ScreenAchievements />;
    case 'profile':            return <ScreenProfile />;
    case 'occupancy':          return <ScreenOccupancy />;
    case 'admin':              return <ScreenAdminDashboard />;
    case 'admin-members':      return <ScreenAdminMembers />;
    case 'admin-member-detail':return <ScreenAdminMemberDetail />;
    case 'admin-logs':         return <ScreenAdminLogs />;
    case 'admin-door-qr':      return <ScreenAdminDoorQR />;
    case 'admin-settings':     return <ScreenAdminSettings />;
    case 'admin-stub':         return <ScreenAdminStub />;
    default:                   return <ScreenLanding />;
  }
}

// Member screens that should NOT show the bottom nav (pre-auth / focused tasks)
const MEMBER_NO_NAV = new Set(['landing', 'login', 'register', 'membership-success']);

function Stage() {
  const { route, go } = useRouter();
  const isAdmin = ADMIN_ROUTES.has(route);
  const screen = pickScreen(route);

  const [bannerHidden, setBannerHidden] = aaUseState(() => {
    try { return localStorage.getItem('demo-banner-hidden') === '1'; } catch (e) { return false; }
  });
  const hideBanner = () => {
    setBannerHidden(true);
    try { localStorage.setItem('demo-banner-hidden', '1'); } catch (e) {}
  };

  // Persona switch
  const isAdminView = isAdmin;
  const onPersonaChange = (p) => {
    if (p === 'member') go('dashboard');
    else go('admin');
  };

  return (
    <div className="stage">
      <div className="stage-top">
        <div className="brand-mark">
          <div className="dot" />
          <span>Gym 24/7 · Poprad — klikateľný mockup</span>
        </div>
        <div className="persona-switch">
          <button className={!isAdminView ? 'active' : ''} onClick={() => onPersonaChange('member')}>
            <Icon name="user" size={14} color="currentColor" /> Pohľad člena
          </button>
          <button className={isAdminView ? 'active' : ''} onClick={() => onPersonaChange('admin')}>
            <Icon name="dashboard" size={14} color="currentColor" /> Pohľad majiteľa
          </button>
        </div>
      </div>

      <div className="stage-side">
        {!isAdminView && <SideNote isAdmin={isAdminView} route={route} />}

        <div className="frame-wrap">
          {/* current screen label, tiny */}
          <div style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#6B6B6B', fontWeight: 600 }} className="mono">
            {SCREEN_LABELS[route] || route}
          </div>

          {isAdminView && <AdminJumpBar />}

          {!isAdminView ? (
            <PhoneShell
              bannerHidden={bannerHidden}
              hideBanner={hideBanner}
              showBottomNav={!MEMBER_NO_NAV.has(route)}
            >
              {screen}
            </PhoneShell>
          ) : (
            <DesktopShell bannerHidden={bannerHidden || route === 'admin-door-qr'} hideBanner={hideBanner} route={route}>
              {screen}
            </DesktopShell>
          )}
        </div>

        {!isAdminView && <SideNoteRight isAdmin={isAdminView} />}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Phone wrapper — IOSDevice with custom dark theme
// ─────────────────────────────────────────────────────────────
function PhoneShell({ children, bannerHidden, hideBanner, showBottomNav }) {
  // iOS status bar (~54px) is absolutely-positioned at top:0, z=20 of the device frame.
  // Demo banner is parked just below the status bar (top:54px, z=15). We add equal
  // top-padding to the scroll area so screen content isn't tucked behind the banner.
  // BottomNav lives OUTSIDE the scroll area so it stays pinned to the bottom of the device.
  return (
    <div style={{ width: 402, position: 'relative' }}>
      <IOSDevice dark width={402} height={874}>
        <div style={{ position: 'relative', height: '100%', overflow: 'hidden' }}>
          <div
            style={{
              position: 'absolute', inset: 0, overflow: 'auto',
              paddingTop: bannerHidden ? 0 : 32,
            }}
            className="noscroll"
          >
            {children}
          </div>
          {!bannerHidden && (
            <div style={{ position: 'absolute', top: 54, left: 0, right: 0, zIndex: 15 }}>
              <DemoBanner hidden={false} onHide={hideBanner} />
            </div>
          )}
          {showBottomNav && <BottomNav />}
        </div>
      </IOSDevice>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Desktop wrapper — ChromeWindow
// ─────────────────────────────────────────────────────────────
function DesktopShell({ children, bannerHidden, hideBanner, route }) {
  const urlMap = {
    admin: 'gym247.sk/admin',
    'admin-members': 'gym247.sk/admin/clenovia',
    'admin-member-detail': 'gym247.sk/admin/clenovia/m15',
    'admin-logs': 'gym247.sk/admin/vstupy',
    'admin-door-qr': 'gym247.sk/admin/qr-poster',
    'admin-settings': 'gym247.sk/admin/nastavenia',
    'admin-stub': 'gym247.sk/admin',
  };
  return (
    <div style={{ width: 'min(1080px, calc(100vw - 32px))' }}>
      <ChromeWindow
        width="100%"
        height={720}
        tabs={[
          { title: 'Gym 24/7 · Admin' },
          { title: 'Účtovníctvo' },
        ]}
        activeIndex={0}
        url={urlMap[route] || 'gym247.sk/admin'}
      >
        <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
          <DemoBanner hidden={bannerHidden} onHide={hideBanner} />
          <div style={{ flex: 1, overflow: 'auto' }}>{children}</div>
        </div>
      </ChromeWindow>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Side notes — guide the viewer
// ─────────────────────────────────────────────────────────────
function SideNote({ isAdmin }) {
  return (
    <div className="side-note" style={{ alignSelf: 'flex-start', marginTop: 28 }}>
      <h4>{isAdmin ? 'Pohľad majiteľa' : 'Pohľad člena'}</h4>
      <p style={{ marginTop: 0, marginBottom: 12 }}>
        {isAdmin
          ? 'Čo vidíš ty, keď otvoríš admin v prehliadači na laptope. Tabuľky, live feed, jednoduchý cenník.'
          : 'Čo vidí klient na mobile. Plynulé tap-thru, animovaný vstup, gamifikácia.'}
      </p>
      <h4 style={{ marginTop: 18 }}>Brand</h4>
      <div className="swatch">
        <span style={{ background: '#E10600' }} title="Red primary" />
        <span style={{ background: '#0A0A0A' }} title="Near black" />
        <span style={{ background: '#fff' }} title="White" />
        <span style={{ background: '#22C55E' }} title="Success" />
        <span style={{ background: '#FCD34D' }} title="Warning" />
      </div>
      <p style={{ fontSize: 12, marginTop: 12, marginBottom: 0 }}>
        Inter + Geist Mono · ostré rohy, žiadne gradienty, žiadne emoji.
      </p>
    </div>
  );
}

function SideNoteRight({ isAdmin }) {
  const memberFlow = [
    { id: 'landing', label: '01 · Landing' },
    { id: 'register', label: '02 · Registrácia' },
    { id: 'dashboard', label: '03 · Dashboard' },
    { id: 'occupancy', label: '04 · Obsadenosť gymu', highlight: true },
    { id: 'enter', label: '05 · Vstup (NFC)', highlight: true },
    { id: 'membership', label: '06 · Permanentky' },
    { id: 'stats', label: '07 · Štatistiky', highlight: true },
    { id: 'achievements', label: '08 · Odznaky' },
    { id: 'profile', label: '09 · Profil' },
    { id: 'login', label: '10 · Login' },
  ];
  const adminFlow = [
    { id: 'admin', label: '01 · Dashboard', highlight: true },
    { id: 'admin-members', label: '02 · Členovia' },
    { id: 'admin-member-detail', label: '03 · Detail člena' },
    { id: 'admin-logs', label: '04 · Vstupy live' },
    { id: 'admin-door-qr', label: '05 · QR poster' },
    { id: 'admin-settings', label: '06 · Nastavenia + Wrapped', highlight: true },
  ];
  const flow = isAdmin ? adminFlow : memberFlow;
  const { route, go } = useRouter();
  return (
    <div className="side-note" style={{ alignSelf: 'flex-start', marginTop: 28 }}>
      <h4>Skoč na obrazovku</h4>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {flow.map(f => {
          const active = route === f.id;
          return (
            <button key={f.id} onClick={() => go(f.id)} style={{
              background: active ? 'var(--red-faded)' : 'transparent',
              border: '1px solid ' + (active ? 'var(--red-stronger)' : 'var(--border)'),
              color: active ? '#FF1A0F' : f.highlight ? '#fff' : 'var(--text-secondary)',
              padding: '8px 12px', borderRadius: 8,
              textAlign: 'left', fontSize: 12, fontWeight: f.highlight ? 600 : 500, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            }}>
              <span>{f.label}</span>
              {f.highlight && !active && <span style={{ fontSize: 10, color: 'var(--red-soft)' }}>★</span>}
            </button>
          );
        })}
      </div>
      <p style={{ fontSize: 11, marginTop: 14, marginBottom: 0, color: 'var(--text-tertiary)' }}>
        ★ = highlight: showpiece obrazovky.
      </p>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Admin horizontal jump bar (above the browser window)
// ─────────────────────────────────────────────────────────────
function AdminJumpBar() {
  const { route, go } = useRouter();
  const flow = [
    { id: 'admin',                label: 'Dashboard',     highlight: true },
    { id: 'admin-members',        label: 'Členovia' },
    { id: 'admin-member-detail',  label: 'Detail člena' },
    { id: 'admin-logs',           label: 'Vstupy live' },
    { id: 'admin-door-qr',        label: 'QR poster' },
    { id: 'admin-settings',       label: 'Nastavenia + Wrapped', highlight: true },
  ];
  return (
    <div style={{
      display: 'flex', gap: 6, flexWrap: 'wrap',
      width: 'min(1080px, calc(100vw - 32px))',
      background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border)',
      borderRadius: 10, padding: 6,
    }}>
      {flow.map(f => {
        const active = route === f.id || (f.id === 'admin-members' && route === 'admin-member-detail' && false);
        return (
          <button key={f.id} onClick={() => go(f.id)} style={{
            background: active ? 'var(--red-faded)' : 'transparent',
            border: '1px solid ' + (active ? 'var(--red-stronger)' : 'transparent'),
            color: active ? '#FF1A0F' : f.highlight ? '#fff' : 'var(--text-secondary)',
            padding: '8px 14px', borderRadius: 8,
            fontSize: 12, fontWeight: f.highlight ? 600 : 500,
            cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            <span>{f.label}</span>
            {f.highlight && !active && <span style={{ fontSize: 10, color: 'var(--red-soft)' }}>★</span>}
          </button>
        );
      })}
    </div>
  );
}

// Small note card shown next to the admin frame on wide screens.
function AdminTipsCard() {
  return null; // kept simple — jump bar above does the job; this slot intentionally empty.
}

// ─────────────────────────────────────────────────────────────
// Mount
// ─────────────────────────────────────────────────────────────
function App() {
  return (
    <RouterProvider initial="landing">
      <ToastProvider>
        <Stage />
      </ToastProvider>
    </RouterProvider>
  );
}

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