/* Roundhouse — Account & Sync screen.
   Magic-link auth via Supabase. Reached from Settings → Account. */

function AccountSync({ go }) {
  const [email,   setEmail]   = React.useState('');
  const [status,  setStatus]  = React.useState('idle'); // idle | sending | sent | error | signedin
  const [user,    setUser]    = React.useState(null);
  const [syncing, setSyncing] = React.useState(false);
  const [syncMsg, setSyncMsg] = React.useState('');

  React.useEffect(() => {
    window.rhSync.getUser().then(function(u) {
      if (u) { setStatus('signedin'); setUser(u); }
    });
  }, []);

  const handleSend = async () => {
    if (!email.trim()) return;
    setStatus('sending');
    const { error } = await window.rhSync.signInWithEmail(email.trim());
    setStatus(error ? 'error' : 'sent');
  };

  const handleSignOut = async () => {
    await window.rhSync.signOut();
    setStatus('idle');
    setUser(null);
  };

  const handleManualSync = async () => {
    setSyncing(true);
    setSyncMsg('');
    try {
      await window.rhSync.pullAndMerge();
      await window.rhSync.pushAll();
      if (window.__rhCache) window.__rhCache = {};
      if (window.__rhRefresh) window.__rhRefresh();
      setSyncMsg('Up to date');
    } catch(e) {
      console.warn('manual sync:', e);
      setSyncMsg('Sync failed — check connection');
    }
    setSyncing(false);
  };

  // ── Signed in ────────────────────────────────────────────────────────
  if (status === 'signedin') return (
    <div style={{minHeight:'100%', background:'var(--bg-base)'}}>
      <TopBar title="Account & Sync" left={<BackRow go={go} dest="settings"/>}/>
      <div style={{padding:'24px 20px', display:'flex', flexDirection:'column', gap:20}}>

        <div style={{background:'var(--bg-elevated-1)', border:'1px solid var(--border-default)', borderRadius:2, padding:16}}>
          <div style={{fontFamily:'var(--font-display)', fontSize:12, color:'var(--rh-brass)', letterSpacing:'0.12em', textTransform:'uppercase', marginBottom:6}}>Signed in</div>
          <div style={{fontFamily:'var(--font-ui)', fontSize:14, color:'var(--fg-1)'}}>{user?.email}</div>
          <div style={{fontFamily:'var(--font-ui)', fontSize:11, color:'var(--fg-4)', marginTop:6, lineHeight:1.5}}>
            Your guns, ammo, and sessions sync automatically across devices.
          </div>
        </div>

        <button
          className="btn btn-ghost"
          style={{padding:'12px 0', letterSpacing:'0.1em', fontSize:11, opacity: syncing ? 0.5 : 1, display:'flex', alignItems:'center', justifyContent:'center', gap:8}}
          onClick={handleManualSync}
          disabled={syncing}
        >
          {syncing ? 'Syncing…' : 'Sync now'}
          {syncMsg && !syncing && <span style={{color:'var(--rh-brass)', fontSize:10, letterSpacing:'0.08em'}}>{syncMsg}</span>}
        </button>

        <div style={{height:1, background:'var(--border-hairline)'}}/>

        <button
          className="btn btn-ghost"
          style={{padding:'12px 0', letterSpacing:'0.1em', fontSize:11, color:'var(--rh-dusty-red)'}}
          onClick={handleSignOut}
        >
          Sign out
        </button>
      </div>
    </div>
  );

  // ── Magic link sent ───────────────────────────────────────────────────
  if (status === 'sent') return (
    <div style={{minHeight:'100%', background:'var(--bg-base)'}}>
      <TopBar title="Account & Sync" left={<BackRow go={go} dest="settings"/>}/>
      <div style={{padding:'40px 20px', display:'flex', flexDirection:'column', gap:16, alignItems:'center', textAlign:'center'}}>
        <div style={{fontFamily:'var(--font-display)', fontSize:28, color:'var(--fg-1)', letterSpacing:'0.04em', lineHeight:1.1}}>Check your email</div>
        <div style={{fontFamily:'var(--font-ui)', fontSize:13, color:'var(--fg-3)', lineHeight:1.6, maxWidth:280}}>
          We sent a sign-in link to<br/>
          <span style={{color:'var(--fg-1)', fontWeight:600}}>{email}</span>
        </div>
        <div style={{fontFamily:'var(--font-ui)', fontSize:11, color:'var(--fg-4)', lineHeight:1.6, maxWidth:260}}>
          Tap the link in the email to sign in. Your data will sync automatically when you return to the app.
        </div>
        <button className="btn btn-ghost" style={{marginTop:12, fontSize:11}} onClick={() => setStatus('idle')}>
          Use a different email
        </button>
      </div>
    </div>
  );

  // ── Sign in form ──────────────────────────────────────────────────────
  return (
    <div style={{minHeight:'100%', background:'var(--bg-base)'}}>
      <TopBar title="Account & Sync" left={<BackRow go={go} dest="settings"/>}/>
      <div style={{padding:'24px 20px', display:'flex', flexDirection:'column', gap:20}}>

        <div>
          <div style={{fontFamily:'var(--font-display)', fontSize:26, color:'var(--fg-1)', letterSpacing:'0.04em', lineHeight:1.2, marginBottom:8}}>Back up your record</div>
          <div style={{fontFamily:'var(--font-ui)', fontSize:13, color:'var(--fg-3)', lineHeight:1.6}}>
            Sign in to sync your guns, ammo, and sessions across devices. Your data lives on this device — sign in to add a cloud backup.
          </div>
        </div>

        <div style={{display:'flex', flexDirection:'column', gap:6}}>
          <div style={{fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--fg-4)'}}>Email</div>
          <input
            type="email"
            value={email}
            autoCapitalize="none"
            autoCorrect="off"
            onChange={function(e) { setEmail(e.target.value); }}
            onKeyDown={function(e) { if (e.key === 'Enter') handleSend(); }}
            placeholder="you@example.com"
            style={{
              background:'var(--bg-elevated-1)',
              border:'1px solid var(--border-default)',
              borderRadius:2,
              padding:'12px 14px',
              color:'var(--fg-1)',
              fontFamily:'var(--font-ui)',
              fontSize:15,
              outline:'none',
              width:'100%',
              boxSizing:'border-box',
            }}
          />
        </div>

        {status === 'error' && (
          <div style={{fontFamily:'var(--font-ui)', fontSize:12, color:'var(--rh-dusty-red)'}}>
            Something went wrong. Check your email and try again.
          </div>
        )}

        <button
          className="btn btn-primary"
          style={{padding:'14px 0', letterSpacing:'0.1em', fontSize:12, opacity: (status === 'sending' || !email.trim()) ? 0.5 : 1}}
          onClick={handleSend}
          disabled={status === 'sending' || !email.trim()}
        >
          {status === 'sending' ? 'Sending…' : 'Send sign-in link'}
        </button>

        <div style={{fontFamily:'var(--font-ui)', fontSize:11, color:'var(--fg-4)', textAlign:'center', lineHeight:1.5}}>
          No password needed. We email you a one-tap sign-in link.
        </div>
      </div>
    </div>
  );
}

window.AccountSync = AccountSync;
