/* =========================================================
   Tappt — Auth + signup flow (welcome · login · account type ·
   details · verify · permissions). Mobile, LinkMe-grade, Tappt brand.
   Replaces window.Auth from app-main.jsx (loaded after it).
   ========================================================= */
const { useState: aUse, useRef: aRef, useEffect: aEffect } = React;
const A_Store = window.Store;
const A_CARDS = window.CARDS || [];

function aLogo() {
  return (
    <span className="auth-wordmark">
      <img className="aw-dark" src="assets/logo-white.png" alt="Tappt" />
      <img className="aw-light" src="assets/logo-black.png" alt="Tappt" />
    </span>
  );
}

/* password strength 0–4 */
function pwScore(p) {
  let s = 0;
  if (p.length >= 8) s++;
  if (/[a-z]/.test(p) && /[A-Z]/.test(p)) s++;
  if (/[0-9]/.test(p)) s++;
  if (/[^A-Za-z0-9]/.test(p)) s++;
  if (p.length >= 12 && s >= 3) s = 4;
  return Math.min(s, 4);
}
const PW_LABEL = ['', 'Weak', 'Fair', 'Good', 'Strong'];

const TAKEN_HANDLES = ['joker', 'admin', 'tappt', 'max', 'official', 'support', 'help'];

function AuthFlow({ onAuthed, themeMode, setThemeMode }) {
  const [view, setView] = aUse('welcome');   // welcome · login · type · details · verify · perms
  const AuthThemeToggle = () => (setThemeMode && window.ThemeToggle
    ? <span className="auth2-theme">{window.ThemeToggle({ theme: document.documentElement.dataset.theme, onToggle: () => setThemeMode(document.documentElement.dataset.theme === 'light' ? 'dark' : 'light') })}</span>
    : null);
  const [acct, setAcct] = aUse('creator');
  const [email, setEmail] = aUse('');
  const [name, setName] = aUse('');
  const [bday, setBday] = aUse('');
  const [handle, setHandle] = aUse('');
  const [pw, setPw] = aUse('');
  const [showPw, setShowPw] = aUse(false);
  const [code, setCode] = aUse(['', '', '', '', '', '']);
  const [resend, setResend] = aUse(56);
  const [perms, setPerms] = aUse({ location: true, notifications: true, contacts: false });
  // login
  const [liId, setLiId] = aUse('');
  const [liPw, setLiPw] = aUse('');
  const [err, setErr] = aUse('');
  const [adminGate, setAdminGate] = aUse(false);
  const [adminPin, setAdminPin] = aUse('');
  const codeRefs = aRef([]);

  aEffect(() => {
    if (view !== 'verify') return;
    setResend(56);
    const t = setInterval(() => setResend((r) => (r <= 1 ? (clearInterval(t), 0) : r - 1)), 1000);
    return () => clearInterval(t);
  }, [view]);

  const handleClean = handle.toLowerCase().replace(/[^a-z0-9_.]/g, '');
  const handleOk = handleClean.length >= 3 && !TAKEN_HANDLES.includes(handleClean);
  const handleBad = handleClean.length > 0 && (handleClean.length < 3 || TAKEN_HANDLES.includes(handleClean));
  const score = pwScore(pw);
  const detailsValid = email.includes('@') && name.trim() && bday && handleOk && score >= 2;

  const [busy, setBusy] = aUse(false);
  const socialAuth = async (provider) => {
    if (window.TapptDB && window.TapptDB.available()) {
      setErr('');
      try {
        const r = await window.TapptDB.signInOAuth(provider);
        if (r && r.error) throw r.error;
      } catch (e) {
        setErr((provider === 'google' ? 'Google' : 'Apple') + " sign-in isn't switched on yet — use email & password instead.");
      }
      return;
    }
    const u = A_Store.getUser() || { email: provider === 'apple' ? 'you@icloud.com' : 'you@gmail.com', links: [], onboarded: false };
    A_Store.saveUser(u); A_Store.setSession(true);
    onAuthed(u, !u.onboarded);
  };

  const doLogin = async () => {
    setErr('');
    if (!liId.trim()) { setErr('Enter your email or username.'); return; }
    if (liPw.length < 6) { setErr('Password must be at least 6 characters.'); return; }
    if (window.TapptDB && window.TapptDB.available() && liId.includes('@')) {
      setBusy(true);
      try {
        var data = await window.TapptDB.signIn(liId.trim(), liPw);
        var prof = await window.TapptDB.loadProfile(data.user.id);
        A_Store.setSession(true);
        onAuthed(prof || { email: liId, links: [], onboarded: false }, !prof || !prof.handle);
      } catch (e) {
        var m = (e && e.message) || 'Could not sign in.';
        if (/confirm/i.test(m)) {
          m = "Your email isn't confirmed yet — we've re-sent the link, tap it then sign in.";
          try { window.TapptDB.resendConfirm(liId.trim()); } catch (e2) {}
        } else if (/invalid/i.test(m)) {
          m = "Email or password doesn't match. New here? Sign up first.";
        }
        setErr(m);
      }
      setBusy(false);
      return;
    }
    if (window.TapptDB && window.TapptDB.available() && !liId.includes('@') && liId.trim().toLowerCase() !== 'demo') {
      setErr('Sign in with the email you signed up with.');
      return;
    }
    const existing = A_Store.getUser();
    A_Store.setSession(true);
    onAuthed(existing || { email: liId, links: [], onboarded: false }, !existing || !existing.onboarded);
  };

  const finishSignup = async () => {
    const u = { email: email, name: name.trim(), handle: handleClean, birthday: bday, accountType: acct, links: [], onboarded: false, perms: perms };
    if (window.TapptDB && window.TapptDB.available() && email.includes('@') && pw.length >= 6) {
      setBusy(true);
      try {
        await window.TapptDB.signUp(email.trim(), pw, { handle: handleClean, name: name.trim() });
        try {
          await window.TapptDB.signIn(email.trim(), pw);
          // confirmation OFF — session is live, go straight into onboarding
          A_Store.setSession(true);
          setBusy(false);
          onAuthed(u, true);
        } catch (e2) {
          // confirmation ON — Supabase emailed a code; collect it on the verify step
          setBusy(false);
          setView('verify');
        }
      } catch (e) { setErr(e.message || 'Could not create account.'); setBusy(false); return; }
      return;
    }
    A_Store.saveUser(u); A_Store.setSession(true);
    onAuthed(u, true);
  };

  const verifyEmail = async () => {
    const token = code.join('');
    setBusy(true);
    try {
      if (window.TapptDB && window.TapptDB.verifyOtp) await window.TapptDB.verifyOtp(email.trim(), token);
      A_Store.setSession(true);
      setBusy(false);
      onAuthed({ email: email, name: name.trim(), handle: handleClean, birthday: bday, accountType: acct, links: [], onboarded: false, perms: perms }, true);
    } catch (e) { setErr((e && e.message) || "That code didn't work — try again."); setBusy(false); }
  };

  const demoLogin = () => {
    // Prefer the user's OWN saved profile so edits survive a re-login; only fall
    // back to the pristine seed the very first time (no saved profile yet).
    const saved = A_Store.getUser();
    const demo = (saved && saved.handle === 'maxxharland') ? saved
      : (window.DEMO_USER || { email: 'max@tappt.io', name: 'Max Harland', handle: 'maxxharland', onboarded: true, pro: true });
    A_Store.saveUser(demo);
    A_Store.setSession(true);
    onAuthed(demo, false);
  };

  const setDigit = (i, v) => {
    v = v.replace(/\D/g, '').slice(-1);
    const next = code.slice(); next[i] = v; setCode(next);
    if (v && i < 5 && codeRefs.current[i + 1]) codeRefs.current[i + 1].focus();
  };
  const codeFull = code.every((c) => c !== '');

  /* ---------- WELCOME ---------- */
  if (view === 'welcome') {
    return (
      <div className="auth2 welcome">
        <AuthThemeToggle />
        <button className="auth2-admin" onClick={() => { setAdminPin(''); setAdminGate(true); }} aria-label="Admin">●</button>
        {adminGate && (
          <div className="auth2-admin-bg" onClick={(ev) => { if (ev.target === ev.currentTarget) setAdminGate(false); }}>
            <div className="auth2-admin-card">
              <div className="auth2-admin-t">Admin access</div>
              <input className="auth2-admin-in" type="tel" inputMode="numeric" autoFocus maxLength={4} placeholder="••••" value={adminPin}
                onChange={(ev) => { const v = ev.target.value.replace(/\D/g, '').slice(0, 4); setAdminPin(v); if (v === '2001') { setAdminGate(false); demoLogin(); } }} />
              <div className="auth2-admin-s">{adminPin.length === 4 && adminPin !== '2001' ? 'Wrong code' : 'Enter your code'}</div>
            </div>
          </div>
        )}
        <div className="auth2-hero">
          {aLogo()}
          <p className="auth2-tag">The home for your taps. One profile for everything you make, share and sell.</p>
        </div>
        <div className="auth2-actions">
          <button className="auth2-btn" onClick={() => { setView('type'); }}>
            <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M12 12a5 5 0 1 0 0-10 5 5 0 0 0 0 10zm0 2c-4.4 0-8 2.7-8 6v2h16v-2c0-3.3-3.6-6-8-6z"/></svg>
            Use phone or email
          </button>
          <button className="auth2-btn" onClick={() => socialAuth('google')}><GoogleGlyph /> Continue with Google</button>
          <button className="auth2-btn" onClick={() => socialAuth('apple')}><AppleGlyph /> Continue with Apple</button>
          {err && <div className="auth2-err">{err}</div>}
          <p className="auth2-legal">By continuing you agree to Tappt's <a href="#">Privacy Policy</a> and <a href="#">Terms of Service</a>. <span style={{ opacity: 0.35 }}>b50</span></p>
        </div>
        <div className="auth2-bottom">
          <span>Have an account already?</span>
          <button className="auth2-ghost" onClick={() => { setView('login'); setErr(''); }}>Log in</button>
        </div>
      </div>
    );
  }

  /* ---------- LOGIN ---------- */
  if (view === 'login') {
    return (
      <div className="auth2 login">
        <button className="auth2-back" onClick={() => setView('welcome')} aria-label="Back">‹</button>
        <AuthThemeToggle />
        <div className="auth2-loginhead">
          <div className="auth2-welcomeback">Welcome back</div>
          {aLogo()}
          <p className="auth2-tag">Sign in to manage your profile and taps.</p>
        </div>
        <div className="auth2-fields">
          <input className="auth2-input" placeholder="Email, username or phone" value={liId} onChange={(e) => setLiId(e.target.value)} />
          <div className="auth2-pwwrap">
            <input className="auth2-input" type={showPw ? 'text' : 'password'} placeholder="Password" value={liPw} onChange={(e) => setLiPw(e.target.value)} />
            <button className="auth2-eye" onClick={() => setShowPw(!showPw)} aria-label="Toggle password">{showPw ? '🙈' : (window.I && window.I.eye ? window.I.eye({ width: 20, height: 20 }) : '👁')}</button>
          </div>
          <button className="auth2-forgot" onClick={() => setErr('Password reset — wired with backend.')}>Forgot password?</button>
          {err && <div className="auth2-err">{err}</div>}
          <button className="auth2-btn" onClick={() => socialAuth('google')}><GoogleGlyph /> Continue with Google</button>
          <button className="auth2-btn" onClick={() => socialAuth('apple')}><AppleGlyph /> Continue with Apple</button>
        </div>
        <div className="auth2-foot-cta">
          <button className="auth2-primary" onClick={doLogin}>Continue</button>
          <div className="auth2-bottom"><span>Don't have an account?</span><button className="auth2-ghost" onClick={() => { setView('welcome'); setErr(''); }}>Sign up</button></div>
        </div>
      </div>
    );
  }

  /* signup progress dots */
  const signupSteps = ['type', 'details', 'verify', 'perms'];
  const stepIdx = signupSteps.indexOf(view);
  const Progress = () => (
    <div className="auth2-prog">{[0, 1, 2].map((i) => <span key={i} className={i <= Math.min(stepIdx, 2) ? 'on' : ''} />)}</div>
  );

  /* ---------- ACCOUNT TYPE ---------- */
  if (view === 'type') {
    return (
      <div className="auth2 step">
        <button className="auth2-back" onClick={() => setView('welcome')} aria-label="Back">‹</button>
        <AuthThemeToggle />
        <Progress />
        <h2 className="auth2-h">How will you<br/>use Tappt?</h2>
        <div className="acct-list">
          {[['creator', 'Creator', 'For creators, artists and public figures growing an audience and personal brand.', 'M12 2a5 5 0 0 1 5 5 5 5 0 0 1-10 0 5 5 0 0 1 5-5zm0 12c4.42 0 8 2.24 8 5v3H4v-3c0-2.76 3.58-5 8-5z'],
            ['business', 'Business', 'For entrepreneurs, brands, teams and services that want a smarter way to connect with customers.', 'M4 21V8l8-5 8 5v13h-6v-6h-4v6H4z'],
            ['personal', 'Personal', 'For sharing your links, socials and contact with friends and people you meet.', 'M16 11a4 4 0 1 0-4-4 4 4 0 0 0 4 4zM8 13a3 3 0 1 0-3-3 3 3 0 0 0 3 3zm0 2c-2.67 0-6 1.34-6 4v2h7v-2c0-1.1.36-2.07.97-2.85A9.6 9.6 0 0 0 8 15zm8 0c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z']].map(([id, t, s, d]) => (
            <button key={id} className={'acct-card' + (acct === id ? ' sel' : '')} onClick={() => setAcct(id)}>
              <span className="acct-ic"><svg viewBox="0 0 24 24" width="26" height="26" fill="currentColor"><path d={d}/></svg></span>
              <span className="acct-meta"><b>{t}</b><span>{s}</span></span>
            </button>
          ))}
        </div>
        <div className="auth2-foot-cta">
          <button className="auth2-primary" onClick={() => setView('details')}>Continue</button>
          <div className="auth2-bottom"><span>Have an account already?</span><button className="auth2-ghost" onClick={() => setView('login')}>Log in</button></div>
        </div>
      </div>
    );
  }

  /* ---------- DETAILS ---------- */
  if (view === 'details') {
    return (
      <div className="auth2 step">
        <button className="auth2-back" onClick={() => setView('type')} aria-label="Back">‹</button>
        <AuthThemeToggle />
        <Progress />
        <h2 className="auth2-h">Tell us a bit<br/>about yourself</h2>
        <div className="auth2-fields">
          <input className="auth2-input" type="email" placeholder="Email or phone number" value={email} onChange={(e) => setEmail(e.target.value)} />
          <input className="auth2-input" placeholder="Full name" value={name} onChange={(e) => setName(e.target.value)} />
          <label className="auth2-date">
            <span>Birthday</span>
            <input type="date" value={bday} onChange={(e) => setBday(e.target.value)} />
          </label>
          <div>
            <input className={'auth2-input' + (handleOk ? ' ok' : handleBad ? ' bad' : '')} placeholder="Username" value={handle} onChange={(e) => setHandle(e.target.value)} />
            {handleOk && <div className="auth2-hint ok">Available</div>}
            {handleBad && <div className="auth2-hint bad">{handleClean.length < 3 ? 'Too short' : 'Taken — try another'}</div>}
          </div>
          <div className="auth2-pwwrap">
            <input className="auth2-input" type={showPw ? 'text' : 'password'} placeholder="Password" value={pw} onChange={(e) => setPw(e.target.value)} />
            <button className="auth2-eye" onClick={() => setShowPw(!showPw)} aria-label="Toggle password">{showPw ? '🙈' : (window.I && window.I.eye ? window.I.eye({ width: 20, height: 20 }) : '👁')}</button>
          </div>
          {pw.length > 0 && (
            <div className="pw-meter">
              <div className="pw-meter-head"><span>Password strength</span><b className={'s' + score}>{PW_LABEL[score]}</b></div>
              <div className="pw-bar"><span className={'s' + score} style={{ width: (score / 4) * 100 + '%' }} /></div>
            </div>
          )}
        </div>
        <div className="auth2-foot-cta">
          <button className="auth2-primary" disabled={!detailsValid || busy} onClick={() => {
            // Real cloud signup goes straight through (no fake code screen).
            // Local/demo fallback still shows the mock verify step.
            if (window.TapptDB && window.TapptDB.available() && email.includes('@')) finishSignup();
            else setView('verify');
          }}>{busy ? 'Creating account…' : 'Continue'}</button>
          {err && <div className="auth2-err" style={{ marginTop: 10 }}>{err}</div>}
          <div className="auth2-bottom"><span>Have an account already?</span><button className="auth2-ghost" onClick={() => setView('login')}>Log in</button></div>
        </div>
      </div>
    );
  }

  /* ---------- VERIFY EMAIL ---------- */
  if (view === 'verify') {
    return (
      <div className="auth2 step verify">
        <button className="auth2-back" onClick={() => setView('details')} aria-label="Back">‹</button>
        <AuthThemeToggle />
        <div className="auth2-steptitle">Sign up</div>
        <h2 className="auth2-h">Verify your email</h2>
        <p className="auth2-tag">We've sent a 6-digit code to <b>{email || 'your email'}</b>. It can take a moment — check spam if you don't see it.</p>
        <div className="code-row">
          {code.map((c, i) => (
            <input key={i} ref={(el) => (codeRefs.current[i] = el)} className="code-cell" inputMode="numeric" maxLength={1} value={c}
              onChange={(e) => setDigit(i, e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Backspace' && !code[i] && i > 0) codeRefs.current[i - 1].focus(); }} />
          ))}
        </div>
        <div className="auth2-resend">{resend > 0 ? `Resend code in ${resend}s` : <button onClick={() => setResend(56)}>Resend code</button>}</div>
        <div className="auth2-foot-cta">
          <button className="auth2-primary" disabled={!codeFull || busy} onClick={verifyEmail}>{busy ? 'Verifying…' : 'Next'}</button>
          {err && <div className="auth2-err" style={{ marginTop: 10, textAlign: 'center' }}>{err}</div>}
        </div>
      </div>
    );
  }

  /* ---------- PERMISSIONS ---------- */
  const PERMS = [
    ['location', 'Location', 'Map where you tapped and meet people nearby. Powers your Connections map.', 'M12 2a7 7 0 0 0-7 7c0 5 7 13 7 13s7-8 7-13a7 7 0 0 0-7-7zm0 9.5A2.5 2.5 0 1 1 12 6.5a2.5 2.5 0 0 1 0 5z'],
    ['notifications', 'Notifications', 'Get notified when someone taps in, likes or comments on a Moment, or sends a message.', 'M12 22a2.5 2.5 0 0 0 2.45-2h-4.9A2.5 2.5 0 0 0 12 22zm7-6V11a7 7 0 0 0-5-6.7V4a2 2 0 1 0-4 0v.3A7 7 0 0 0 5 11v5l-2 2v1h18v-1l-2-2z'],
    ['contacts', 'Contacts', "Find friends already on Tappt and let them find you. Earn rewards for inviting friends.", 'M16 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zm-8 0a4 4 0 1 0 0-8 4 4 0 0 0 0 8zm0 2c-3 0-6 1.5-6 4.5V20h8v-2.5c0-1.1.4-2 1-2.8-1-.5-2-.7-3-.7zm8 0c-.6 0-1.2.05-1.8.15C15.3 14 16 15.4 16 17v3h8v-2.5c0-3-3-4.5-6-4.5z'],
  ];
  return (
    <div className="auth2 step perms">
      <AuthThemeToggle />
      <h2 className="auth2-h">Permissions</h2>
      <p className="auth2-tag">Tappt is a networking app. Allow a few permissions to get the best experience.</p>
      <div className="perm-list">
        {PERMS.map(([id, t, s, d]) => (
          <button key={id} className="perm-card" onClick={() => setPerms((p) => ({ ...p, [id]: !p[id] }))}>
            <span className="perm-ic"><svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d={d}/></svg></span>
            <span className="perm-meta"><b>{t}</b><span>{s}</span></span>
            <span className={'perm-check' + (perms[id] ? ' on' : '')}>{perms[id] ? (window.I && window.I.check ? window.I.check({ width: 15, height: 15 }) : '✓') : ''}</span>
          </button>
        ))}
      </div>
      <div className="auth2-foot-cta">
        <button className="auth2-primary" onClick={finishSignup}>Next</button>
      </div>
    </div>
  );
}

window.Auth = AuthFlow;
