// Roast Battle v2 — leaner router, 7 screens, no gamification.

function V2Jumper({ current, go }) {
  const screens = [
    ['splash',   'Splash'],
    ['onboard',  'Onboard'],
    ['friends',  'Add Friends'],
    ['home',     'Home'],
    ['write',    'Write a Roast'],
    ['reveal',   'Reveal'],
    ['profile',  'Profile'],
  ];
  const i = screens.findIndex(s => s[0] === current);
  return (
    <div style={{
      position: 'fixed', left: 16, bottom: 16,
      display: 'flex', alignItems: 'center', gap: 8,
      background: '#0E0E0E', color: '#fff',
      borderRadius: 999, padding: '8px 12px',
      fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
      boxShadow: '0 8px 24px rgba(0,0,0,0.3)',
      zIndex: 100,
    }}>
      <button onClick={() => go(screens[Math.max(0, i - 1)][0])} style={v2btn}>◀</button>
      <select value={current} onChange={e => go(e.target.value)} style={{
        background: 'transparent', color: '#fff', border: 'none', outline: 'none',
        fontFamily: 'JetBrains Mono', fontSize: 12, minWidth: 140,
      }}>
        {screens.map(s => <option key={s[0]} value={s[0]} style={{ background: '#111' }}>{s[1]}</option>)}
      </select>
      <button onClick={() => go(screens[Math.min(screens.length - 1, i + 1)][0])} style={v2btn}>▶</button>
      <span style={{ opacity: 0.5, marginLeft: 4 }}>{i + 1}/{screens.length}</span>
    </div>
  );
}
const v2btn = {
  appearance: 'none', cursor: 'pointer',
  background: 'rgba(255,255,255,0.1)', color: '#fff',
  border: 'none', borderRadius: 6,
  width: 24, height: 24, padding: 0,
  fontFamily: 'inherit', fontSize: 11,
};

const V2_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": ["#FF2D87", "#B6FF3C", "#FFD400", "#FFF1DE"]
}/*EDITMODE-END*/;

const V2_THEME_BY_HERO = {
  '#FF2D87': 'hot',
  '#B6FF3C': 'toxic',
  '#00E8FF': 'cyber',
  '#FF4632': 'cream',
};

// Track viewport-is-mobile on window so the shared useIsMobile() in
// components.jsx can read it. One listener, one source of truth, broadcast
// to subscribed components via a custom event.
const RB_MOBILE_QUERY = '(max-width: 500px)';
if (typeof window !== 'undefined' && window.__rbMobileWired !== true) {
  const mq = window.matchMedia(RB_MOBILE_QUERY);
  window.__isMobile = mq.matches;
  const broadcast = () => {
    window.__isMobile = mq.matches;
    window.dispatchEvent(new Event('rb-mobile-change'));
  };
  // Some older Safari versions only support addListener; cover both.
  if (mq.addEventListener) mq.addEventListener('change', broadcast);
  else mq.addListener(broadcast);
  window.__rbMobileWired = true;
}

// Dev affordances (V2Jumper, TweaksPanel) only render when devMode is on.
// Two ways to flip it:
//   - ?dev=1 in the URL (one-shot — also writes the flag to localStorage)
//   - ?dev=0 in the URL (clears it)
//   - localStorage.rb_dev === '1' (sticky across refreshes once turned on)
// Mobile hides these regardless — they're desktop-only design tools.
function isDevMode() {
  if (typeof window === 'undefined') return false;
  try {
    const u = new URL(window.location.href);
    const qp = u.searchParams.get('dev');
    if (qp === '1') { try { localStorage.setItem('rb_dev', '1'); } catch (e) {} return true; }
    if (qp === '0') { try { localStorage.removeItem('rb_dev'); } catch (e) {} return false; }
    return localStorage.getItem('rb_dev') === '1';
  } catch (e) { return false; }
}

function App() {
  const [tweaks, setTweak] = useTweaks(V2_TWEAK_DEFAULTS);
  const themeKey = (typeof tweaks.theme === 'string' && window.THEMES[tweaks.theme])
    ? tweaks.theme
    : (Array.isArray(tweaks.theme) ? (V2_THEME_BY_HERO[tweaks.theme[0]] || 'hot') : 'hot');
  const t = window.THEMES[themeKey];

  const isMobile = useIsMobile();
  const devMode = React.useMemo(isDevMode, []);
  const identity = useIdentity();
  const profile = useProfile();

  const [screen, setScreen] = React.useState('splash');
  const [ctx, setCtx] = React.useState({ opp: null });
  const [onboard, setOnboard] = React.useState({ handle: '', avatar: '🐀' });

  // Share-link handler (P1.18). If the URL has ?add=<handle>, stash it in
  // sessionStorage. The Friends screen reads it on mount, prefills the
  // search box, and runs the lookup. We clean the URL right away so a
  // refresh doesn't re-trigger.
  React.useEffect(() => {
    try {
      const u = new URL(window.location.href);
      const add = u.searchParams.get('add');
      if (add) {
        const cleaned = String(add).replace(/^@+/, '').toLowerCase();
        sessionStorage.setItem('rb_pending_add', cleaned);
        u.searchParams.delete('add');
        history.replaceState({}, '', u.pathname + (u.search || '') + u.hash);
      }
    } catch (e) {}
  }, []);

  // Auto-route to Friends if a pending add is sitting in sessionStorage
  // and the user is onboarded. (Onboard's NEXT routes there anyway; this
  // handles the returning-user case where we'd land on Home by default.)
  React.useEffect(() => {
    if (!profile.ready || !profile.row) return;
    try {
      if (sessionStorage.getItem('rb_pending_add') && screen === 'home') {
        setScreen('friends');
      }
    } catch (e) {}
  }, [profile.ready, profile.row, screen]);

  // Auto-route returning users past Splash. New users see Splash → click → Onboard.
  // If the user has a profile row and they're currently on Splash, go straight Home.
  React.useEffect(() => {
    if (profile.ready && profile.row && screen === 'splash') {
      setScreen('home');
    }
  }, [profile.ready, profile.row, screen]);

  const go = (s, newCtx) => {
    if (newCtx) setCtx(prev => ({ ...prev, ...newCtx }));
    setScreen(s);
    setTimeout(() => {
      const el = document.querySelector('[data-screen-scroll]');
      if (el) el.scrollTop = 0;
    }, 0);
  };

  const setTab = (id) => {
    if (id === 'home')    go('home');
    if (id === 'friends') go('friends');
    if (id === 'profile') go('profile');
  };

  const renderScreen = () => {
    const props = { t, go, ctx, setTab, state: onboard, setState: setOnboard };
    switch (screen) {
      case 'splash':   return <V2Splash {...props} />;
      case 'onboard':  return <V2Onboard {...props} />;
      case 'friends':  return <V2Friends {...props} />;
      case 'home':     return <V2Home {...props} />;
      case 'write':    return <V2Write {...props} />;
      case 'reveal':   return <V2Reveal {...props} />;
      case 'profile':  return <V2Profile {...props} />;
      default: return null;
    }
  };

  const isDark = t.dark;
  const pageBg = isDark ? '#0A0A0A' : '#E8E0CE';

  // Boot gate — block render until the anonymous Supabase session is ready.
  // identity.error means anonymous auth is disabled in the Supabase dashboard
  // or there's a project/network problem; surface it clearly instead of
  // showing a misleading loading state forever. See docs/identity.md.
  if (!identity.ready || identity.error) {
    const pad = isMobile ? '24px' : '32px';
    const wrap = {
      width: '100%', minHeight: '100dvh',
      background: t.bg, color: t.ink,
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      padding: pad, gap: 14, textAlign: 'center',
      fontFamily: 'Space Grotesk, system-ui',
    };
    if (identity.error) {
      return (
        <div style={wrap}>
          <div style={{ fontFamily: 'Bungee, system-ui', fontSize: 22, color: t.pop }}>can't sign in</div>
          <div style={{ fontSize: 14, color: t.sub, maxWidth: 320, lineHeight: 1.4 }}>
            anonymous auth probably isn't enabled in the supabase dashboard yet — turn it on under <em>authentication → providers</em> and reload.
          </div>
          <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.sub, opacity: 0.7, marginTop: 6 }}>{identity.error}</div>
        </div>
      );
    }
    return (
      <div style={wrap}>
        <div style={{ fontFamily: 'Bungee, system-ui', fontSize: 22, color: t.ink, opacity: 0.4 }}>loading…</div>
      </div>
    );
  }

  // Mobile: fullscreen, screen content directly under the body. The fake
  // iOS device frame is desktop-only — on a real phone the user IS the
  // device, no need to draw one around them.
  //
  // Important: the inner wrapper must use `height: '100dvh'`, not minHeight.
  // The Screen component inside uses `height: 100%` (so the absolutely-
  // positioned TabBar can pin to its bottom), and that percentage doesn't
  // resolve against min-height — it'd collapse to auto and float the TabBar
  // at the top of the viewport.
  if (isMobile) {
    return (
      <div style={{
        width: '100%', minHeight: '100dvh',
        background: t.bg, color: t.ink,
        overflow: 'hidden',
      }}>
        <div data-screen-scroll data-screen-label={screen}
             style={{ width: '100%', height: '100dvh', position: 'relative' }}>
          {renderScreen()}
        </div>
        {/* Dev affordances stay off on mobile regardless of ?dev=1.
            The jumper and tweaks panel are desktop-only design tools. */}
      </div>
    );
  }

  // Desktop: framed iPhone mockup centered on a tinted page background.
  return (
    <div style={{
      minHeight: '100vh', width: '100%',
      background: pageBg,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24, boxSizing: 'border-box',
      backgroundImage: `radial-gradient(circle at 20% 30%, ${t.pop}22, transparent 40%), radial-gradient(circle at 80% 70%, ${t.accent}22, transparent 40%)`,
    }}>
      <div data-screen-label={screen}>
        <IOSDevice width={402} height={874} dark={isDark}>
          <div data-screen-scroll style={{ width: '100%', height: '100%' }}>
            {renderScreen()}
          </div>
        </IOSDevice>
      </div>

      {devMode && <V2Jumper current={screen} go={go} />}

      {devMode && (
        <TweaksPanel title="Tweaks">
          <TweakSection title="theme">
            <TweakColor
              label="palette"
              value={tweaks.theme}
              onChange={v => setTweak('theme', v)}
              options={[
                ['#FF2D87', '#B6FF3C', '#FFD400', '#FFF1DE'],
                ['#B6FF3C', '#FF2D87', '#FFE600', '#0D1100'],
                ['#00E8FF', '#FF2DEA', '#FFE600', '#06002A'],
                ['#FF4632', '#15203F', '#FFB400', '#F2EBDA'],
              ]}
            />
          </TweakSection>
        </TweaksPanel>
      )}
    </div>
  );
}

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