// App — deferred auth: anonymous users can play, auth required for stats/trophies/profile

// ── GA4 helper ──────────────────────────────
function trackPage(path, title) {
  if (typeof gtag === 'function') {
    gtag('config', 'G-8FL8N8HK3C', {
      page_path: path,
      page_title: title,
    });
  }
}
window.trackPage = trackPage;

function trackEvent(eventName, params) {
  if (typeof gtag === 'function') {
    gtag('event', eventName, params || {});
  }
}
window.trackEvent = trackEvent;

function App() {
  const T = window.T;
  const [session, setSession] = React.useState(null);
  const [authChecked, setAuthChecked] = React.useState(false);
  const [tab, setTab] = React.useState(() => localStorage.getItem('futball-tab') || 'home');
  const [draftOpen, setDraftOpen] = React.useState(false);
  const [xiOpen, setXiOpen] = React.useState(false);

  React.useEffect(() => { localStorage.setItem('futball-tab', tab); }, [tab]);

  // Fire GA4 page view on tab change
  React.useEffect(() => {
    const titles = { home:'Home', stats:'Stats', play:'Play', achievements:'Trophies', profile:'Profile' };
    trackPage('/' + tab, titles[tab] || tab);
  }, [tab]);

  // Subscribe to auth changes
  React.useEffect(() => {
    let mounted = true;
    window.sb.auth.getSession().then(({ data: { session } }) => {
      if (!mounted) return;
      setSession(session);
      setAuthChecked(true);
    });
    const { data: listener } = window.sb.auth.onAuthStateChange((_event, session) => {
      if (!mounted) return;
      setSession(session);
      setAuthChecked(true);
    });
    return () => {
      mounted = false;
      listener.subscription.unsubscribe();
    };
  }, []);

  const openDraft = () => { setDraftOpen(true); trackPage('/play/draft', 'Draft Mode'); };
  const closeDraft = () => setDraftOpen(false);
  const openXi = () => { setXiOpen(true); trackPage('/play/xi', 'Name the XI'); };
  const closeXi = () => setXiOpen(false);

  const isSignedIn = !!session;

  // Still checking auth — show loading
  if (!authChecked) {
    return (
      <Phone>
        <div style={{
          flex: 1, display:'flex', alignItems:'center', justifyContent:'center',
          color: T.textSec, fontSize: 13,
        }}>Loading…</div>
      </Phone>
    );
  }

  // Auth-gated tabs show inline auth prompt
  const gatedTabs = ['stats', 'achievements', 'profile'];
  const needsAuth = gatedTabs.includes(tab) && !isSignedIn;

  const Screen = needsAuth
    ? () => <InlineAuthPrompt tab={tab} />
    : tab === 'home'         ? (props) => <HomeScreen {...props} onOpenDraft={openDraft} onOpenXi={openXi}/>
    : tab === 'stats'        ? StatsScreen
    : tab === 'play'         ? (props) => <PlayScreen {...props} onOpenDraft={openDraft} onOpenXi={openXi}/>
    : tab === 'achievements' ? AchievementsScreen
    : tab === 'profile'      ? ProfileScreen
    : HomeScreen;

  return (
    <Phone>
      {draftOpen ? (
        <DraftFlow onExit={closeDraft} />
      ) : xiOpen ? (
        <XiFlow onExit={closeXi} />
      ) : (
        <>
          <Screen />
          <BottomNav active={tab} onChange={setTab} />
        </>
      )}
    </Phone>
  );
}

// ── Inline auth prompt for gated tabs ────────────────────────────
function InlineAuthPrompt({ tab }) {
  const T = window.T;
  const config = {
    stats: {
      icon: '📊',
      title: 'Track Your Game',
      desc: 'Get a one-time code to track your accuracy, see trends, and compete on the leaderboard.',
    },
    achievements: {
      icon: '🏆',
      title: 'Trophy Cabinet',
      desc: 'Get a one-time code to start earning trophies for your favorite teams and nations.',
    },
    profile: {
      icon: '👤',
      title: 'Your Profile',
      desc: 'Get a one-time code to save your progress and set your display name.',
    },
  }[tab] || { icon: '🔐', title: 'Sign In', desc: 'Get a one-time code to access this feature.' };

  return (
    <Content>
      <div style={{
        display:'flex', flexDirection:'column', alignItems:'center',
        justifyContent:'center', textAlign:'center',
        padding:'40px 20px', flex:1, minHeight:'60vh',
      }}>
        <div style={{fontSize:56, marginBottom:20, opacity:0.9}}>{config.icon}</div>
        <div style={{
          fontFamily:'Bakbak One, sans-serif', fontSize:24,
          letterSpacing:'0.04em', color:T.text, marginBottom:10,
        }}>{config.title}</div>
        <div style={{
          fontSize:14, color:T.textSec, lineHeight:1.6, marginBottom:32,
          maxWidth:280,
        }}>{config.desc}</div>
        <InlineAuthForm/>
      </div>
    </Content>
  );
}

// ── Inline auth form (OTP flow) ──────────────────────────────────
function InlineAuthForm() {
  const T = window.T;
  const [email, setEmail] = React.useState('');
  const [step, setStep] = React.useState('email');
  const [code, setCode] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');

  const sendCode = async () => {
    if (!email.trim()) return;
    setSending(true);
    setError('');
    try {
      await window.signInWithEmail(email.trim());
      setStep('code');
    } catch (e) {
      setError(e.message || 'Failed to send code');
    } finally {
      setSending(false);
    }
  };

  const verify = async () => {
    if (code.length < 8) return;
    setSending(true);
    setError('');
    try {
      const { error: err } = await window.sb.auth.verifyOtp({
        email: email.trim(),
        token: code,
        type: 'email',
      });
      if (err) throw err;
      // Track conversion event
      if (typeof window.trackEvent === 'function') {
        window.trackEvent('sign_in_completed', { method: 'email_otp' });
      }
    } catch (e) {
      setError(e.message || 'Invalid code');
    } finally {
      setSending(false);
    }
  };

  if (step === 'email') {
    return (
      <div style={{width:'100%', maxWidth:300}}>
        <input
          type="email"
          value={email}
          onChange={e => setEmail(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && sendCode()}
          placeholder="Your email"
          style={{
            width:'100%', padding:'14px 16px', borderRadius:12,
            background:T.card, border:`1px solid ${T.border}`,
            color:T.text, fontFamily:'DM Sans', fontSize:16,
            outline:'none', marginBottom:12,
          }}
        />
        <button onClick={sendCode} disabled={sending || !email.trim()} style={{
          width:'100%', padding:'14px', borderRadius:12,
          background: email.trim() ? 'linear-gradient(180deg, #F5C842, #C99A10)' : T.card,
          color: email.trim() ? '#1A1200' : T.textMute,
          border: email.trim() ? 'none' : `1px solid ${T.border}`,
          fontFamily:'Bakbak One, sans-serif', fontSize:15,
          letterSpacing:'0.06em', cursor: email.trim() ? 'pointer' : 'default',
        }}>{sending ? 'Sending…' : 'Get Code'}</button>
        {error && <div style={{color:T.red, fontSize:12, marginTop:10}}>{error}</div>}
        <div style={{fontSize:11, color:T.textMute, marginTop:14, lineHeight:1.5}}>
          We'll send an 8-digit code to your email. No password needed.
        </div>
      </div>
    );
  }

  return (
    <div style={{width:'100%', maxWidth:300}}>
      <div style={{fontSize:13, color:T.textSec, marginBottom:14}}>
        Code sent to <span style={{color:T.text, fontWeight:600}}>{email}</span>
      </div>
      <input
        type="text"
        inputMode="numeric"
        value={code}
        onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 8))}
        onKeyDown={e => e.key === 'Enter' && verify()}
        placeholder="8-digit code"
        autoComplete="one-time-code"
        style={{
          width:'100%', padding:'14px 16px', borderRadius:12,
          background:T.card, border:`1px solid ${T.border}`,
          color:T.text, fontFamily:'DM Sans', fontSize:22, fontWeight:700,
          letterSpacing:'0.18em', textAlign:'center',
          outline:'none', marginBottom:12,
        }}
      />
      <button onClick={verify} disabled={sending || code.length < 8} style={{
        width:'100%', padding:'14px', borderRadius:12,
        background: code.length >= 8 ? 'linear-gradient(180deg, #F5C842, #C99A10)' : T.card,
        color: code.length >= 8 ? '#1A1200' : T.textMute,
        border: code.length >= 8 ? 'none' : `1px solid ${T.border}`,
        fontFamily:'Bakbak One, sans-serif', fontSize:15,
        letterSpacing:'0.06em', cursor: code.length >= 8 ? 'pointer' : 'default',
      }}>{sending ? 'Verifying…' : 'Verify'}</button>
      {error && <div style={{color:T.red, fontSize:12, marginTop:10}}>{error}</div>}
      <button onClick={() => { setStep('email'); setCode(''); setError(''); }}
        style={{background:'transparent', border:'none', color:T.textSec, fontSize:12, marginTop:12, cursor:'pointer', textDecoration:'underline'}}>
        Use a different email
      </button>
    </div>
  );
}

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