// v-auth.jsx — vendor auth/session UX: sign-in, session restore, expired session, role gate

// ─── Field ───────────────────────────────────────────────────────────
const AUTH_FLD = { width:'100%', boxSizing:'border-box', background:'rgba(255,255,255,0.07)', border:'1px solid rgba(255,255,255,0.16)', borderRadius:12, padding:'13px 15px', fontFamily:'var(--font-body)', fontSize:14, color:'var(--dust-cream)', outline:'none' };

// ─── Sign-in screen (signed-out state) ───────────────────────────────
// states: idle → signingin → error (denied) | success → session
function AuthScreen({ onSignIn, expired=false, inviteId=null }) {
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [confirmPw, setConfirmPw] = React.useState('');
  const [mode, setMode] = React.useState(inviteId ? 'signup' : 'signin');
  const [state, setState] = React.useState('idle'); // idle | signingin | error
  const [err, setErr] = React.useState(null);
  const [captchaState, setCaptchaState] = React.useState('loading');
  const captchaContainerRef = React.useRef(null);
  const captchaTokenRef = React.useRef('');
  const captchaWidgetRef = React.useRef(null);
  const captchaApiRef = React.useRef(null);

  React.useEffect(() => {
    let disposed = false;
    let timer = null;
    const siteKey = window.LASSO_RUNTIME_CONFIG?.turnstileSiteKey;
    const fail = () => { if (!disposed) setCaptchaState('unavailable'); };
    const mount = () => {
      if (disposed || captchaWidgetRef.current !== null || !captchaContainerRef.current) return;
      if (!siteKey || !window.turnstile?.render) { fail(); return; }
      captchaApiRef.current = window.turnstile;
      captchaWidgetRef.current = captchaApiRef.current.render(captchaContainerRef.current, {
        sitekey: siteKey,
        callback(token) { captchaTokenRef.current = typeof token === 'string' ? token : ''; if (!disposed) setCaptchaState(captchaTokenRef.current ? 'verified' : 'unavailable'); },
        'expired-callback'() { captchaTokenRef.current = ''; if (!disposed) setCaptchaState('ready'); },
        'error-callback'() { captchaTokenRef.current = ''; fail(); },
      });
      if (!disposed) setCaptchaState('ready');
    };
    const startedAt = Date.now();
    timer = window.setInterval(() => {
      if (window.turnstile?.render) { window.clearInterval(timer); timer = null; mount(); }
      else if (Date.now() - startedAt >= 8000) { window.clearInterval(timer); timer = null; fail(); }
    }, 50);
    return () => {
      disposed = true;
      if (timer) window.clearInterval(timer);
      if (captchaWidgetRef.current !== null && window.turnstile?.remove) window.turnstile.remove(captchaWidgetRef.current);
    };
  }, []);

  const consumeCaptcha = () => {
    captchaTokenRef.current = '';
    const responseField = captchaContainerRef.current?.querySelector('input[name="cf-turnstile-response"]');
    if (responseField) responseField.value = '';
    if (captchaWidgetRef.current !== null && captchaApiRef.current?.reset) captchaApiRef.current.reset(captchaWidgetRef.current);
    setCaptchaState('ready');
  };

  const submit = async () => {
    if (state==='signingin') return;
    setErr(null); setState('signingin');
    if (!email.trim() || !pw.trim()) { setState('error'); setErr('Enter your email and password.'); return; }
    if (mode==='signup' && pw.length < 8) { setState('error'); setErr('Choose a password with at least 8 characters.'); return; }
    if (mode==='signup' && pw !== confirmPw) { setState('error'); setErr('Your passwords do not match.'); return; }
    try {
      const responseField = captchaContainerRef.current?.querySelector('input[name="cf-turnstile-response"]');
      const captchaToken = captchaTokenRef.current || responseField?.value || '';
      if (!captchaToken) throw new Error(captchaState==='unavailable' ? 'Security check is unavailable. Nothing has been submitted.' : 'Complete the security check before continuing. Nothing has been submitted.');
      if (mode==='signup') {
        const result = await signUpVendor({ email:email.trim(), password:pw, captchaToken, inviteId });
        if (result.confirmationRequired) { setState('confirmation'); return; }
        onSignIn(result.session);
      } else onSignIn(await signInVendor({ email:email.trim(), password:pw, captchaToken, inviteId }));
    }
    catch (error) { setState('error'); setErr(error instanceof Error ? error.message : 'No active vendor membership was found for this account.'); }
    finally { consumeCaptcha(); }
  };

  return (
    <div style={{ position:'absolute', inset:0, zIndex:200, display:'flex', alignItems:'center', justifyContent:'center', background:'linear-gradient(160deg, rgba(20,13,9,0.86), rgba(27,18,13,0.94))', backdropFilter:'blur(10px)', animation:'v-fade 240ms ease-out' }}>
      <div style={{ width:420, maxWidth:'calc(100vw - 48px)' }}>
        <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:26, justifyContent:'center' }}>
          <Bull size={40}/>
          <Wordmark size={22}/>
          <span style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:11, letterSpacing:'0.14em', textTransform:'uppercase', color:'#9F8979', border:'1px solid rgba(255,255,255,0.16)', borderRadius:6, padding:'3px 8px' }}>Vendor</span>
        </div>

        <div style={{ background:'rgba(255,251,245,0.05)', border:'1px solid rgba(255,255,255,0.12)', borderRadius:22, padding:'28px 28px 24px', boxShadow:'0 40px 90px -30px rgba(0,0,0,0.8)', animation:'v-pop 280ms var(--ease-out)' }}>
          {expired && (
            <div style={{ display:'flex', gap:10, alignItems:'flex-start', padding:'11px 13px', background:'rgba(224,153,42,0.12)', border:'1px solid rgba(224,153,42,0.35)', borderRadius:12, marginBottom:18 }}>
              <I.clock c="#E0992A" s={16}/>
              <span style={{ fontFamily:'var(--font-body)', fontSize:12.5, lineHeight:1.5, color:'#D8CCC0' }}>Your session expired. Sign back in to keep managing orders — nothing was lost.</span>
            </div>
          )}
          <h1 style={{ margin:'0 0 4px', fontFamily:'var(--font-display)', fontWeight:900, fontSize:22, color:'var(--dust-cream)', letterSpacing:'-0.01em' }}>{inviteId && mode==='signup' ? 'Join your kitchen' : 'Sign in to your kitchen'}</h1>
          <p style={{ margin:'0 0 20px', fontFamily:'var(--font-body)', fontSize:13, color:'#9F8979' }}>{inviteId && mode==='signup' ? 'Create your own password. Your invited role activates after you verify this email.' : 'Owner, manager and staff sign-ins each see what their role allows.'}</p>

          {state==='confirmation' ? (
            <div style={{ padding:'12px 13px', background:'rgba(46,139,78,0.14)', border:'1px solid rgba(91,143,110,0.4)', borderRadius:12, fontFamily:'var(--font-body)', fontSize:12.5, lineHeight:1.55, color:'#D8CCC0' }}>
              Check your email to verify this address. Then return through the same invite link and sign in to activate your kitchen role.
            </div>
          ) : <>

          <label style={{ display:'block', marginBottom:12 }}>
            <span style={{ display:'block', fontFamily:'var(--font-display)', fontWeight:700, fontSize:10.5, letterSpacing:'0.08em', textTransform:'uppercase', color:'#9F8979', marginBottom:7 }}>Work email</span>
            <input value={email} onChange={e=>setEmail(e.target.value)} onKeyDown={e=>e.key==='Enter'&&submit()} placeholder="you@fireanddough.co.uk" autoComplete="email" style={AUTH_FLD}/>
          </label>
          <label style={{ display:'block', marginBottom:6 }}>
            <span style={{ display:'block', fontFamily:'var(--font-display)', fontWeight:700, fontSize:10.5, letterSpacing:'0.08em', textTransform:'uppercase', color:'#9F8979', marginBottom:7 }}>Password</span>
            <input value={pw} onChange={e=>setPw(e.target.value)} onKeyDown={e=>e.key==='Enter'&&submit()} type="password" placeholder="••••••••" autoComplete="current-password" style={AUTH_FLD}/>
          </label>
          {mode==='signup' && <label style={{ display:'block', marginBottom:6 }}>
            <span style={{ display:'block', fontFamily:'var(--font-display)', fontWeight:700, fontSize:10.5, letterSpacing:'0.08em', textTransform:'uppercase', color:'#9F8979', marginBottom:7 }}>Confirm password</span>
            <input value={confirmPw} onChange={e=>setConfirmPw(e.target.value)} onKeyDown={e=>e.key==='Enter'&&submit()} type="password" placeholder="••••••••" autoComplete="new-password" style={AUTH_FLD}/>
          </label>}
          <div style={{ textAlign:'right', marginBottom:16 }}>
            <span style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:12, color:'var(--sun-orange)', cursor:'pointer' }}>Forgot password?</span>
          </div>

          <div ref={captchaContainerRef} data-vendor-auth-turnstile aria-label="Security check" style={{ minHeight:65, marginBottom:14 }}></div>
          {captchaState==='unavailable' && <p style={{ margin:'-6px 0 14px', fontFamily:'var(--font-body)', fontSize:12, lineHeight:1.45, color:'#E8C4B8' }}>Security check is unavailable. Nothing has been submitted.</p>}

          {state==='error' && err && (
            <div style={{ display:'flex', gap:9, alignItems:'flex-start', padding:'10px 13px', background:'rgba(193,59,31,0.14)', border:'1px solid rgba(193,59,31,0.4)', borderRadius:11, marginBottom:14, animation:'v-pop 200ms var(--ease-out)' }}>
              <I.alert c="#E07B5F" s={15}/>
              <span style={{ fontFamily:'var(--font-body)', fontSize:12.5, lineHeight:1.45, color:'#E8C4B8' }}>{err}</span>
            </div>
          )}

          <Btn kind="accent" full size="lg" onClick={submit} disabled={state==='signingin'}
            icon={state==='signingin' ? <span style={{ display:'inline-flex', animation:'v-spin 800ms linear infinite' }}><I.refresh c="#fff" s={16}/></span> : <I.arrow c="#fff" s={16}/>}>
            {state==='signingin' ? (mode==='signup' ? 'Creating account…' : 'Signing in…') : (mode==='signup' ? 'Create account' : 'Sign in')}
          </Btn>

          {inviteId && <button onClick={()=>{ setMode(m=>m==='signup'?'signin':'signup'); setErr(null); setState('idle'); }} style={{ display:'block', width:'100%', marginTop:12, padding:0, background:'none', border:'none', cursor:'pointer', fontFamily:'var(--font-display)', fontWeight:700, fontSize:12, color:'var(--sun-orange)' }}>
            {mode==='signup' ? 'Already have a Lasso account? Sign in' : 'New to Lasso? Create your account'}
          </button>}
          </>}

          <div style={{ marginTop:18, paddingTop:16, borderTop:'1px solid rgba(255,255,255,0.1)', fontFamily:'var(--font-body)', fontSize:11.5, lineHeight:1.45, color:'#9F8979' }}>Access is for active Lasso vendor owners, managers and staff. Your assigned role controls what you can open.</div>
        </div>

        <div style={{ marginTop:16, textAlign:'center', fontFamily:'var(--font-body)', fontSize:11.5, color:'#8A786B' }}>
          New restaurant? <a href="https://lasso.delivery/vendor-apply/" style={{ color:'var(--sun-orange)', fontFamily:'var(--font-display)', fontWeight:700 }}>Apply to join Lasso →</a>
        </div>
      </div>
    </div>
  );
}

// ─── Session restore splash ──────────────────────────────────────────
function SessionRestoring() {
  return (
    <div style={{ position:'absolute', inset:0, zIndex:200, display:'flex', flexDirection:'column', gap:16, alignItems:'center', justifyContent:'center', background:'var(--dark-chocolate)' }}>
      <Bull size={52}/>
      <div style={{ display:'flex', alignItems:'center', gap:9, fontFamily:'var(--font-display)', fontWeight:700, fontSize:13, color:'#9F8979' }}>
        <span style={{ display:'inline-flex', animation:'v-spin 800ms linear infinite' }}><I.refresh c="var(--brand-orange)" s={15}/></span>
        Restoring your session…
      </div>
    </div>
  );
}

// ─── Expired-session overlay (kept context, re-auth in place) ────────
function SessionExpiredOverlay({ onSignBackIn, onSignOut }) {
  const [busy, setBusy] = React.useState(false);
  const go = () => { setBusy(true); setTimeout(onSignBackIn, 800); };
  return (
    <div style={{ position:'fixed', inset:0, zIndex:940, background:'rgba(12,8,6,0.6)', backdropFilter:'blur(7px)', display:'flex', alignItems:'center', justifyContent:'center', animation:'v-fade 200ms ease-out' }}>
      <div style={{ width:400, maxWidth:'calc(100vw - 48px)', background:'var(--dark-chocolate)', color:'var(--dust-cream)', borderRadius:20, border:'1px solid rgba(255,255,255,0.14)', padding:'26px 26px 22px', boxShadow:'0 40px 90px -20px rgba(0,0,0,0.8)', animation:'v-pop 240ms var(--ease-out)' }}>
        <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:12 }}>
          <div style={{ width:42, height:42, borderRadius:12, background:'rgba(224,153,42,0.18)', display:'flex', alignItems:'center', justifyContent:'center' }}><I.clock c="#E0992A" s={20}/></div>
          <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:17 }}>Session expired</div>
        </div>
        <p style={{ margin:'0 0 18px', fontFamily:'var(--font-body)', fontSize:13, lineHeight:1.55, color:'#B6A595' }}>For security you've been signed out after inactivity. Sign back in to continue exactly where you left off — the kitchen queue is untouched.</p>
        <Btn kind="accent" full onClick={go} disabled={busy}
          icon={busy ? <span style={{ display:'inline-flex', animation:'v-spin 800ms linear infinite' }}><I.refresh c="#fff" s={15}/></span> : <I.lock c="#fff" s={15}/>}>
          {busy ? 'Signing back in…' : 'Sign back in'}
        </Btn>
        <button onClick={onSignOut} style={{ display:'block', width:'100%', marginTop:10, padding:'9px', background:'transparent', border:'none', cursor:'pointer', fontFamily:'var(--font-display)', fontWeight:700, fontSize:12.5, color:'#9F8979' }}>Switch account</button>
      </div>
    </div>
  );
}

// ─── Role-denied gate (mirrors RLS expectations) ─────────────────────
function RoleDenied({ page, session }) {
  const r = ROLES[session.role];
  return (
    <div style={{ maxWidth:620, margin:'60px auto 0' }}>
      <Card pad={0} style={{ overflow:'hidden' }}>
        <div style={{ padding:'32px 32px 26px', textAlign:'center' }}>
          <div style={{ width:56, height:56, borderRadius:16, background:'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 16px' }}>
            <I.lock c="var(--brand-orange)" s={25}/>
          </div>
          <h2 style={{ margin:'0 0 8px', fontFamily:'var(--font-display)', fontWeight:900, fontSize:20, color:'var(--fg-primary)' }}>Your role can't open this</h2>
          <p style={{ margin:'0 auto', maxWidth:420, fontFamily:'var(--font-body)', fontSize:13.5, lineHeight:1.55, color:'var(--warm-stone)' }}>
            You're signed in as <strong style={{ color:'var(--fg-primary)' }}>{r.name}</strong> ({r.label} — {r.access.toLowerCase()}). Ask your owner to upgrade your role if you need access here.
          </p>
        </div>
        <div style={{ padding:'13px 32px', borderTop:'1px solid var(--soft-line)', background:'var(--bg-app)', display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
          <I.shield c="var(--warm-stone)" s={14}/>
          <span style={{ fontFamily:'var(--font-body)', fontSize:11.5, color:'var(--warm-stone)' }}>Access is enforced server-side by row-level security — this screen mirrors it.</span>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { AuthScreen, SessionRestoring, SessionExpiredOverlay, RoleDenied });
