/* =========================================================
   Tappt dashboard — root: auth, onboarding, dashboard
   ========================================================= */
const {
  CARDS, LINK_TYPES, typeMeta, AVATAR_COLORS, Store, genAnalytics,
  I, AppleGlyph, GoogleGlyph, BioPreview,
} = window;
const { useState, useEffect, useRef } = React;

function useToast() {
  const [msg, setMsg] = useState(null);
  const show = (m) => { setMsg(m); setTimeout(() => setMsg(null), 2200); };
  const node = (
    <div className={'toast' + (msg ? ' show' : '')}>
      <span className="dot" />{msg}
    </div>
  );
  return [show, node];
}

/* ---------------------------------------------------------
   AUTH
   --------------------------------------------------------- */
function Auth({ onAuthed }) {
  const [mode, setMode] = useState('signup');
  const [email, setEmail] = useState('');
  const [pw, setPw] = useState('');
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);

  const submit = (e) => {
    e.preventDefault();
    setErr('');
    if (!email.includes('@')) { setErr('Enter a valid email.'); return; }
    if (pw.length < 6) { setErr('Password must be at least 6 characters.'); return; }
    setBusy(true);
    // STUB: replace with supabase.auth.signUp / signInWithPassword
    setTimeout(() => {
      setBusy(false);
      const existing = Store.getUser();
      if (mode === 'login') {
        if (existing && existing.email === email) { Store.setSession(true); onAuthed(existing, false); }
        else if (existing) { Store.setSession(true); onAuthed(existing, false); }
        else onAuthed({ email, links: [], onboarded: false }, true);
      } else {
        const fresh = { email, links: [], onboarded: false };
        Store.saveUser(fresh); Store.setSession(true);
        onAuthed(fresh, true);
      }
    }, 700);
  };

  const cardImgs = ['joker', 'lovergirl', 'black'].map((id) => CARDS.find((c) => c.id === id));

  return (
    <div className="auth">
      <div className="auth-brand">
        <div className="auth-brand-bg" />
        <img className="auth-logo" src="assets/logo-white.png" alt="Tappt" />
        <div className="auth-brand-mid">
          <h1>Your world.<br/><span className="it">One profile.</span></h1>
          <p>One tap shares everything you make — links, socials, your latest drop. This is the home for your Tappt card.</p>
          <div className="auth-cards">
            {cardImgs.map((c, i) => (
              <div className="ac" style={{ '--r': `${(i - 1) * 7}deg` }} key={c.id}><img src={c.img} alt="" /></div>
            ))}
          </div>
        </div>
        <div className="auth-foot">TAPPT INC · 2026</div>
      </div>

      <div className="auth-form-wrap">
        <form className="auth-form fade-up" onSubmit={submit}>
          <h2>{mode === 'signup' ? 'Create your account' : 'Welcome back'}</h2>
          <div className="sub">{mode === 'signup' ? 'Claim your handle and bring your card to life.' : 'Sign in to manage your profile.'}</div>

          <div className="social-btns">
            <button type="button" className="social-btn" onClick={() => { setBusy(true); setTimeout(() => { const u = Store.getUser() || { email: 'you@icloud.com', links: [], onboarded: false }; Store.saveUser(u); Store.setSession(true); onAuthed(u, !u.onboarded); }, 600); }}>
              <AppleGlyph /> Continue with Apple
            </button>
            <button type="button" className="social-btn" onClick={() => { setBusy(true); setTimeout(() => { const u = Store.getUser() || { email: 'you@gmail.com', links: [], onboarded: false }; Store.saveUser(u); Store.setSession(true); onAuthed(u, !u.onboarded); }, 600); }}>
              <GoogleGlyph /> Continue with Google
            </button>
          </div>
          <div className="divider">or with email</div>

          <div className="field">
            <label>Email</label>
            <input className="input" type="email" placeholder="you@email.com" value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>
          <div className="field">
            <label>Password</label>
            <input className="input" type="password" placeholder="••••••••" value={pw} onChange={(e) => setPw(e.target.value)} />
          </div>
          {err && <div className="err">{err}</div>}

          <button className="btn btn-primary btn-block" type="submit" disabled={busy}>
            {busy ? <span className="spin">{I.spark({ width: 18, height: 18 })}</span> : (mode === 'signup' ? 'Create account' : 'Sign in')}
            {!busy && I.arrow({ width: 17, height: 17 })}
          </button>

          <div className="auth-switch">
            {mode === 'signup' ? 'Already have a card? ' : "New to Tappt? "}
            <button type="button" onClick={() => { setMode(mode === 'signup' ? 'login' : 'signup'); setErr(''); }}>
              {mode === 'signup' ? 'Sign in' : 'Create an account'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

window.Auth = Auth;
window.useToast = useToast;
