// Saddle Alert — main app
const { useState: useState_a, useEffect: useEffect_a } = React;
const ENABLED_REGIONS = ['AU', 'SG'];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentColor": "#C8541F",
  "navStyle": "sidebar",
  "density": "comfortable",
  "showSeed": true
}/*EDITMODE-END*/;

function App() {
  const [tweaks, setTweak] = window.useTweaks ? window.useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, () => {}];

  // Apply accent color live
  useEffect_a(() => {
    document.documentElement.style.setProperty('--orange', tweaks.accentColor);
  }, [tweaks.accentColor]);

  const [route, setRoute] = useState_a('feed'); // feed | alerts | matches | add | settings
  const [editingAlertId, setEditingAlertId] = useState_a(null);
  const [prefillFromItem, setPrefillFromItem] = useState_a(null);
  const [selectedItem, setSelectedItem] = useState_a(null);
  const [user, setUser] = useState_a(null);
  const [sessionLoading, setSessionLoading] = useState_a(true);
  const [showOnboarding, setShowOnboarding] = useState_a(false);
  const [notifications, setNotifications] = useState_a([]);
  const [inboxOpen, setInboxOpen] = useState_a(false);
  const bellAnchorRef = React.useRef(null);
  const deepLinkHandledRef = React.useRef(false);
  const [alerts, setAlerts] = useState_a([]);
  const [activeRegions, setActiveRegions] = useState_a(ENABLED_REGIONS);
  const [notif, setNotif] = useState_a({ push: true, email: true, sms: false, sound: true });
  const [toast, setToast] = useState_a(null);
  const [isMobile, setIsMobile] = useState_a(typeof window !== 'undefined' ? window.innerWidth < 880 : false);
  const [accountMenuOpen, setAccountMenuOpen] = useState_a(false);

  useEffect_a(() => {
    const onResize = () => setIsMobile(window.innerWidth < 880);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 2200);
  };

  const loadNotifications = () => {
    return fetch('/api/notifications')
      .then(res => res.json())
      .then(json => {
        const list = Array.isArray(json.notifications) ? json.notifications : [];
        setNotifications(list);
        return list;
      })
      .catch(() => []);
  };

  useEffect_a(() => {
    fetch('/api/auth/me')
      .then(res => res.json())
      .then(json => {
        setUser(json.user || null);
      })
      .catch(() => setUser(null))
      .finally(() => setSessionLoading(false));
  }, []);

  useEffect_a(() => {
    if (!user) {
      setAlerts([]);
      setNotifications([]);
      return;
    }
    fetch('/api/alerts')
      .then(res => res.json())
      .then(json => {
        if (Array.isArray(json.alerts)) setAlerts(json.alerts);
      })
      .catch(() => {});
    loadNotifications();
  }, [user && user.id]);

  useEffect_a(() => {
    if (!user || deepLinkHandledRef.current) return;
    const params = new URLSearchParams(window.location.search || '');
    const notifId = params.get('notif');
    if (!notifId) return;
    deepLinkHandledRef.current = true;
    loadNotifications().then((list) => {
      const target = list.find((n) => String(n.id) === String(notifId));
      if (target) {
        setRoute('feed');
        handleSelectNotif(target);
      } else {
        showToast('Notification link expired or not found');
      }
      params.delete('notif');
      const clean = `${window.location.pathname}${params.toString() ? `?${params.toString()}` : ''}`;
      window.history.replaceState({}, document.title, clean);
    });
  }, [user && user.id]);

  // Alert handlers
  const handleToggle = (id) => {
    const alert = alerts.find(a => a.id === id);
    if (!alert) return;
    const nextActive = !alert.active;
    setAlerts(alerts.map(a => a.id === id ? { ...a, active: nextActive } : a));
    fetch(`/api/alerts/${encodeURIComponent(id)}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ active: nextActive }),
    })
      .then(res => res.json())
      .then(json => {
        if (json.alert) setAlerts(current => current.map(a => a.id === id ? json.alert : a));
      })
      .catch(() => {
        setAlerts(current => current.map(a => a.id === id ? { ...a, active: alert.active } : a));
        showToast('Could not save alert');
      });
  };
  const handleEdit = (id) => {
    setEditingAlertId(id);
    setRoute('add');
  };
  const handleDelete = (id) => {
    const existing = alerts.find(a => a.id === id);
    setAlerts(alerts.filter(a => a.id !== id));
    fetch(`/api/alerts/${encodeURIComponent(id)}`, { method: 'DELETE' })
      .then(res => {
        if (!res.ok) throw new Error('Delete failed');
        showToast('Alert deleted');
      })
      .catch(() => {
        if (existing) setAlerts(current => [existing, ...current]);
        showToast('Could not delete alert');
      });
  };
  const handleSave = (data) => {
    if (editingAlertId) {
      fetch(`/api/alerts/${encodeURIComponent(editingAlertId)}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
        .then(res => res.json())
        .then(json => {
          if (!json.alert) throw new Error('Update failed');
          setAlerts(current => current.map(a => a.id === editingAlertId ? json.alert : a));
          showToast('Alert updated');
        })
        .catch(() => showToast('Could not save alert'));
    } else {
      const newAlert = {
        ...data,
        active: true,
      };
      fetch('/api/alerts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newAlert),
      })
        .then(res => res.json())
        .then(json => {
          if (!json.alert) throw new Error('Create failed');
          setAlerts(current => [json.alert, ...current]);
          showToast('Alert created');
        })
        .catch(() => showToast('Could not create alert'));
    }
    setEditingAlertId(null);
    setPrefillFromItem(null);
    setRoute('alerts');
  };

  const handleCreateAlertFromItem = (item) => {
    setSelectedItem(null);
    setPrefillFromItem(item);
    setEditingAlertId(null);
    setRoute('add');
  };

  const editingAlert = editingAlertId ? alerts.find(a => a.id === editingAlertId) : null;

  // ----------- Landing (logged out) -----------
  if (sessionLoading) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'grid',
        placeItems: 'center',
        background: 'var(--bg)',
        color: 'var(--ink-3)',
      }}>
        Loading Saddle Alert...
      </div>
    );
  }

  if (!user) {
    return <LandingPage onAuthSuccess={(nextUser, isNew) => {
      setUser(nextUser);
      setShowOnboarding(Boolean(isNew));
    }} />;
  }

  // ----------- Onboarding handlers -----------
  const finishOnboarding = ({ regions: pickedRegions, model }) => {
    const allowed = pickedRegions.filter(r => ENABLED_REGIONS.includes(r));
    setActiveRegions(allowed.length ? allowed : ENABLED_REGIONS);
    setShowOnboarding(false);
    // Send them into the new-alert form prefilled with their chosen model
    setPrefillFromItem({ model });
    setRoute('add');
    showToast('Welcome aboard');
  };

  // ----------- Inbox handlers -----------
  const openInbox = () => {
    loadNotifications();
    setInboxOpen(true);
  };

  const handleSelectNotif = (n) => {
    setNotifications(current => current.map(x => x.id === n.id ? { ...x, read: true } : x));
    fetch(`/api/notifications/${encodeURIComponent(n.id)}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ read: true }),
    })
      .then(res => res.json())
      .then(json => {
        if (json.notification) {
          setNotifications(current => current.map(x => x.id === n.id ? json.notification : x));
        }
      })
      .catch(() => {});
    setInboxOpen(false);
    if (n.item) {
      // Build a stock-detail-shaped item from the notification
      const item = {
        id: n.item.id || 'N-' + n.id,
        title: n.item.title,
        url: n.item.url,
        imageUrl: n.item.imageUrl || null,
        model: n.item.model || n.alertName,
        size: n.item.size || '',
        leather: n.item.leather || n.item.material || 'Leather',
        material: n.item.material || n.item.leather || '',
        color: n.item.color || '',
        hw: n.item.hw || '',
        region: n.item.region || 'AU',
        price: n.item.price,
        currency: n.item.currency,
        ago: n.ago,
        status: n.item.status || 'live',
        match: true,
        rarity: n.priority ? 'rare' : 'common',
      };
      setSelectedItem(item);
    }
  };
  const handleMarkAllRead = () => {
    setNotifications(current => current.map(n => ({ ...n, read: true })));
    fetch('/api/notifications/mark-all-read', { method: 'POST' }).catch(() => {});
  };
  const handleResendNotif = (n) => {
    if (!user?.isAdmin || !n?.id) return;
    fetch(`/api/notifications/${encodeURIComponent(n.id)}/resend-telegram`, { method: 'POST' })
      .then(res => res.json())
      .then(json => {
        if (json.ok) {
          showToast(`Telegram sent (${json.sent || 1}/${json.targets || 1})`);
        } else if (json.reason === 'not_configured') {
          showToast('No connected Telegram account found for this listing');
        } else {
          showToast(json.reason || json.error || 'Telegram resend failed');
        }
      })
      .catch(() => showToast('Telegram resend failed'));
  };

  const unreadCount = notifications.filter(n => !n.read).length;
  const userInitials = (() => {
    const source = (user?.name || user?.email || 'Saddle').trim();
    const parts = source.includes('@') ? [source[0]] : source.split(/\s+/).filter(Boolean);
    return parts.slice(0, 2).map(part => part[0]).join('').toUpperCase() || 'OB';
  })();
  const handleSignOut = () => {
    fetch('/api/auth/logout', { method: 'POST' }).catch(() => {});
    setUser(null);
    setAlerts([]);
    setNotifications([]);
    setAccountMenuOpen(false);
    setRoute('feed');
  };

  // ----------- Layout -----------
  return (
    <div
      data-screen-label={`OBT · ${route}`}
      style={{
        minHeight: '100vh',
        minHeight: '100dvh',
        background: 'var(--bg)',
        display: 'flex',
        flexDirection: isMobile ? 'column' : 'row',
      }}
    >
      {/* SIDEBAR (desktop) */}
      {!isMobile && (
        <aside style={{
          width: 240,
          flexShrink: 0,
          background: 'var(--bg-elev)',
          borderRight: '1px solid var(--line)',
          padding: '24px 18px',
          position: 'sticky',
          top: 0,
          height: '100vh',
          display: 'flex',
          flexDirection: 'column',
          gap: 24,
        }}>
          <Logo />
          <Nav route={route} setRoute={(r) => { setRoute(r); setEditingAlertId(null); }} alerts={alerts} user={user} />
          <div style={{ flex: 1 }} />
          {/* Region quick toggle */}
          <div>
            <div style={{
              fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase',
              letterSpacing: '0.12em', fontFamily: 'var(--font-mono)', marginBottom: 10,
            }}>Watching</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {window.DW_DATA.REGIONS.map(r => {
                const on = activeRegions.includes(r.code);
                const disabled = !ENABLED_REGIONS.includes(r.code);
                return (
                  <button
                    key={r.code}
                    onClick={() => {
                      if (disabled) return;
                      setActiveRegions(on
                        ? activeRegions.filter(c => c !== r.code)
                        : [...activeRegions, r.code]);
                    }}
                    style={{
                      display: 'inline-flex', alignItems: 'center', gap: 4,
                      padding: '4px 10px',
                      fontSize: 12, fontWeight: 500,
                      background: on ? 'var(--bg)' : 'transparent',
                      color: on ? 'var(--ink)' : 'var(--ink-3)',
                      border: `1px solid ${on ? 'var(--line-2)' : 'transparent'}`,
                      borderRadius: 999,
                      cursor: disabled ? 'not-allowed' : 'pointer',
                      opacity: disabled ? 0.35 : (on ? 1 : 0.5),
                    }}
                    title={disabled ? `${r.name} (disabled for now)` : (r.hint || r.name)}
                  >
                    <RegionFlags code={r.code} size={13} />
                    <span>{r.displayCode || r.code}</span>
                  </button>
                );
              })}
            </div>
          </div>
          {/* Account */}
          <div style={{ position: 'relative' }}>
          <button type="button" onClick={() => setAccountMenuOpen(open => !open)} style={{
            width: '100%',
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '10px 12px',
            background: 'var(--bg)',
            border: '1px solid var(--line)',
            borderRadius: 10,
            cursor: 'pointer',
            textAlign: 'left',
          }}>
            <div style={{
              width: 30, height: 30, borderRadius: '50%',
              background: 'var(--orange)',
              color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 12, fontWeight: 600, letterSpacing: '0.04em',
            }}>{userInitials}</div>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{
                display: 'flex',
                alignItems: 'center',
                gap: 6,
                fontSize: 13,
                fontWeight: 500,
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
              }}>
                <span>{user.isAdmin ? 'Admin account' : 'Standard plan'}</span>
                {user.isAdmin && (
                  <span style={{
                    fontSize: 9.5,
                    fontFamily: 'var(--font-mono)',
                    textTransform: 'uppercase',
                    color: 'var(--green)',
                    background: '#E6F2EC',
                    border: '1px solid #CDE6D8',
                    borderRadius: 999,
                    padding: '2px 6px',
                    flexShrink: 0,
                  }}>Admin</span>
                )}
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                {user.email}
              </div>
            </div>
          </button>
          {accountMenuOpen && (
            <div style={{
              position: 'absolute',
              left: 0,
              right: 0,
              bottom: 'calc(100% + 8px)',
              background: 'var(--bg-elev)',
              border: '1px solid var(--line)',
              borderRadius: 10,
              boxShadow: '0 12px 28px rgba(22, 18, 14, 0.12)',
              padding: 6,
              zIndex: 40,
            }}>
              <button type="button" onClick={() => { setRoute('settings'); setAccountMenuOpen(false); }} style={accountMenuItemStyle}>
                Account settings
              </button>
              {user.isAdmin && (
                <button type="button" onClick={() => { setRoute('admin'); setAccountMenuOpen(false); }} style={accountMenuItemStyle}>
                  Admin dashboard
                </button>
              )}
              <button type="button" onClick={handleSignOut} style={{ ...accountMenuItemStyle, color: 'var(--red)' }}>
                Sign out
              </button>
            </div>
          )}
          </div>
        </aside>
      )}

      {/* MOBILE HEADER */}
      {isMobile && (
        <header style={{
          position: 'sticky', top: 0, zIndex: 30,
          background: 'var(--bg-elev)',
          borderBottom: '1px solid var(--line)',
          padding: '12px 18px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <Logo size={16} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
            <div style={{ position: 'relative' }}>
              <button
                type="button"
                onClick={() => setAccountMenuOpen(open => !open)}
                style={{
                  width: 34,
                  height: 34,
                  borderRadius: '50%',
                  border: '1px solid var(--orange)',
                  background: 'var(--orange)',
                  color: '#fff',
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: 11.5,
                  fontWeight: 600,
                  letterSpacing: '0.04em',
                  cursor: 'pointer',
                }}
                title="Account"
              >
                {userInitials}
              </button>
              {accountMenuOpen && (
                <div style={{
                  position: 'absolute',
                  right: 0,
                  top: 'calc(100% + 8px)',
                  minWidth: 180,
                  background: 'var(--bg-elev)',
                  border: '1px solid var(--line)',
                  borderRadius: 10,
                  boxShadow: '0 12px 28px rgba(22, 18, 14, 0.12)',
                  padding: 6,
                  zIndex: 40,
                }}>
                  <button type="button" onClick={() => { setRoute('settings'); setAccountMenuOpen(false); }} style={accountMenuItemStyle}>
                    Account settings
                  </button>
                  {user.isAdmin && (
                    <button type="button" onClick={() => { setRoute('admin'); setAccountMenuOpen(false); }} style={accountMenuItemStyle}>
                      Admin dashboard
                    </button>
                  )}
                  <button type="button" onClick={handleSignOut} style={{ ...accountMenuItemStyle, color: 'var(--red)' }}>
                    Sign out
                  </button>
                </div>
              )}
            </div>
            <span style={{
              fontSize: 11, color: 'var(--green)',
              display: 'inline-flex', alignItems: 'center', gap: 5,
              fontFamily: 'var(--font-mono)',
              padding: '4px 9px',
              background: '#E6F2EC',
              borderRadius: 999,
              whiteSpace: 'nowrap',
            }}>
              <span style={{
                width: 6, height: 6, borderRadius: '50%',
                background: 'var(--green)',
                animation: 'pulse 1.6s ease-in-out infinite',
              }} />
              LIVE
            </span>
            <BellButton unreadCount={unreadCount} onClick={openInbox} getRef={(el) => bellAnchorRef.current = el} />
          </div>
        </header>
      )}

      {/* DESKTOP TOP-RIGHT BELL */}
      {!isMobile && (
        <div style={{
          position: 'fixed',
          top: 18, right: 24,
          zIndex: 25,
        }}>
          <BellButton unreadCount={unreadCount} onClick={openInbox} getRef={(el) => bellAnchorRef.current = el} />
        </div>
      )}

      {/* MAIN CONTENT */}
      <main style={{
        flex: 1,
        minWidth: 0,
        padding: isMobile ? '20px 18px 100px' : 'clamp(28px, 4vw, 48px) clamp(28px, 5vw, 56px)',
        maxWidth: 1100,
        margin: '0 auto',
        width: '100%',
      }}>
        {route === 'feed' && (
          <FeedScreen
            user={user}
            alerts={alerts}
            activeRegions={activeRegions}
            onGoToAdd={() => { setEditingAlertId(null); setPrefillFromItem(null); setRoute('add'); }}
            onGoToSettings={() => setRoute('settings')}
            onGoToAdmin={() => setRoute('admin')}
            onGoToMatches={() => setRoute('matches')}
            onSelectItem={setSelectedItem}
          />
        )}
        {route === 'alerts' && (
          <AlertsScreen
            user={user}
            alerts={alerts}
            onToggle={handleToggle}
            onEdit={handleEdit}
            onDelete={handleDelete}
            onGoToAdd={() => { setEditingAlertId(null); setPrefillFromItem(null); setRoute('add'); }}
          />
        )}
        {route === 'matches' && (
          <MatchReviewScreen
            alerts={alerts}
            onSelectItem={setSelectedItem}
          />
        )}
        {route === 'add' && (
          <AddAlertScreen
            editingAlert={editingAlert}
            prefill={prefillFromItem}
            onCancel={() => { setEditingAlertId(null); setPrefillFromItem(null); setRoute(editingAlert ? 'alerts' : 'feed'); }}
            onSave={handleSave}
          />
        )}
        {route === 'settings' && (
          <SettingsScreen
            user={user}
            activeRegions={activeRegions}
            setActiveRegions={setActiveRegions}
            enabledRegions={ENABLED_REGIONS}
            notif={notif}
            setNotif={setNotif}
            onSignOut={handleSignOut}
          />
        )}
        {route === 'admin' && user.isAdmin && (
          <AdminDashboardScreen />
        )}
      </main>

      {/* MOBILE BOTTOM NAV */}
      {isMobile && (
        <MobileNav
          route={route}
          setRoute={(r) => { setRoute(r); setEditingAlertId(null); }}
          user={user}
        />
      )}

      {/* STOCK DETAIL PANEL */}
      {selectedItem && (
        <StockDetail
          item={selectedItem}
          onClose={() => setSelectedItem(null)}
          onCreateAlertFromItem={handleCreateAlertFromItem}
        />
      )}

      {/* INBOX */}
      {inboxOpen && (
        <NotificationInbox
          notifications={notifications}
          isAdmin={Boolean(user?.isAdmin)}
          onClose={() => setInboxOpen(false)}
          onMarkAllRead={handleMarkAllRead}
          onSelectNotif={handleSelectNotif}
          onResendNotif={handleResendNotif}
          anchor={bellAnchorRef.current ? bellAnchorRef.current.getBoundingClientRect() : null}
        />
      )}

      {/* ONBOARDING */}
      {showOnboarding && (
        <Onboarding
          onComplete={finishOnboarding}
          onSkip={() => setShowOnboarding(false)}
        />
      )}

      {/* TOAST */}
      {toast && (
        <div style={{
          position: 'fixed',
          bottom: isMobile ? 84 : 24,
          left: '50%',
          transform: 'translateX(-50%)',
          background: 'var(--ink)',
          color: 'var(--bg)',
          padding: '10px 18px',
          borderRadius: 999,
          fontSize: 13,
          fontWeight: 500,
          boxShadow: '0 8px 24px rgba(0,0,0,0.2)',
          zIndex: 50,
          animation: 'slideUp 0.2s ease',
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <Icon name="check" size={14} />
          {toast}
        </div>
      )}

      {/* TWEAKS PANEL */}
      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks">
          <window.TweakSection title="Brand">
            <window.TweakColor
              label="Accent"
              value={tweaks.accentColor}
              onChange={(v) => setTweak('accentColor', v)}
              options={['#C8541F', '#9E3712', '#C2410C', '#0F766E', '#1F2937']}
            />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

// ----------- Desktop sidebar nav -----------
const accountMenuItemStyle = {
  width: '100%',
  display: 'flex',
  alignItems: 'center',
  padding: '9px 10px',
  background: 'transparent',
  border: 0,
  borderRadius: 8,
  color: 'var(--ink-2)',
  fontSize: 13,
  fontWeight: 500,
  cursor: 'pointer',
  textAlign: 'left',
};

const Nav = ({ route, setRoute, alerts, user }) => {
  const ownActiveAlerts = alerts.filter(a => a.active && (!user?.isAdmin || a.userId === user.id)).length;
  const items = [
    { id: 'feed', label: 'Live feed', icon: 'feed' },
    { id: 'alerts', label: user?.isAdmin ? 'Alerts' : 'My alerts', icon: 'bell', badge: ownActiveAlerts },
    { id: 'matches', label: 'Matches', icon: 'search' },
    { id: 'settings', label: 'Settings', icon: 'settings' },
  ];
  return (
    <nav style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      {items.map(it => {
        const active = route === it.id;
        return (
          <button
            key={it.id}
            onClick={() => setRoute(it.id)}
            style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '10px 12px',
              background: active ? 'var(--bg)' : 'transparent',
              border: '1px solid ' + (active ? 'var(--line-2)' : 'transparent'),
              borderRadius: 8,
              color: active ? 'var(--ink)' : 'var(--ink-2)',
              fontSize: 14,
              fontWeight: active ? 500 : 400,
              cursor: 'pointer',
              textAlign: 'left',
              transition: 'background 0.12s ease',
              width: '100%',
            }}
            onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--bg)'; }}
            onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
          >
            <Icon name={it.icon} size={17} />
            <span style={{ flex: 1 }}>{it.label}</span>
            {it.badge ? (
              <span style={{
                fontSize: 11, fontWeight: 600,
                background: active ? 'var(--orange)' : 'var(--line-2)',
                color: active ? '#fff' : 'var(--ink-2)',
                padding: '1px 7px',
                borderRadius: 999,
                fontFamily: 'var(--font-mono)',
              }}>{it.badge}</span>
            ) : null}
          </button>
        );
      })}
    </nav>
  );
};

// ----------- Mobile bottom nav -----------
const MobileNav = ({ route, setRoute, user }) => {
  const items = [
    { id: 'feed', label: 'Feed', icon: 'feed' },
    { id: 'alerts', label: 'Alerts', icon: 'bell' },
    { id: 'matches', label: 'Matches', icon: 'search' },
    { id: 'settings', label: 'Settings', icon: 'settings' },
  ];
  return (
    <nav style={{
      position: 'fixed', left: 0, right: 0, bottom: 0,
      background: 'var(--bg-elev)',
      borderTop: '1px solid var(--line)',
      display: 'grid',
      gridTemplateColumns: `repeat(${items.length}, 1fr)`,
      paddingBottom: 'env(safe-area-inset-bottom)',
      zIndex: 40,
    }}>
      {items.map(it => {
        const active = route === it.id;
        if (it.accent) {
          return (
            <button
              key={it.id}
              onClick={() => setRoute(it.id)}
              style={{
                display: 'flex', flexDirection: 'column', alignItems: 'center',
                justifyContent: 'center', gap: 4,
                padding: '8px 0 10px',
                background: 'transparent',
                border: 'none',
                cursor: 'pointer',
              }}
            >
              <div style={{
                width: 42, height: 42, borderRadius: '50%',
                background: 'var(--orange)',
                color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: '0 4px 12px rgba(229, 91, 31, 0.35)',
                marginTop: -16,
              }}>
                <Icon name={it.icon} size={20} stroke={2} />
              </div>
              <span style={{ fontSize: 10.5, color: 'var(--ink-3)', fontWeight: 500 }}>{it.label}</span>
            </button>
          );
        }
        return (
          <button
            key={it.id}
            onClick={() => setRoute(it.id)}
            style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center',
              justifyContent: 'center', gap: 4,
              padding: '12px 0 12px',
              background: 'transparent',
              border: 'none',
              color: active ? 'var(--orange)' : 'var(--ink-3)',
              cursor: 'pointer',
              transition: 'color 0.12s ease',
            }}
          >
            <Icon name={it.icon} size={20} stroke={active ? 2 : 1.7} />
            <span style={{ fontSize: 10.5, fontWeight: active ? 600 : 500 }}>{it.label}</span>
          </button>
        );
      })}
    </nav>
  );
};

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