/* AIWine — sign in / join, inside the app.
   Uses the WEBSITE's account layer (assets/account.js), so this is the same
   login, the same Supabase session and the same member record the website and
   the CRM see. No second account system. */
function AuthSheet({ open, onClose, onDone, intent }) {
  const [mode, setMode] = React.useState(intent === 'join' ? 'join' : 'signin');
  const [f, setF] = React.useState({ firstName: '', email: '', password: '' });
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [sent, setSent] = React.useState('');

  React.useEffect(() => { if (open) { setMode(intent === 'join' ? 'join' : 'signin'); setF({ firstName: '', email: '', password: '' }); setErr(''); setSent(''); setBusy(false); } }, [open, intent]);

  const set = k => e => setF(x => ({ ...x, [k]: e.target.value }));
  const A = () => window.AIAccount;

  async function submit() {
    setErr(''); setBusy(true);
    try {
      if (!A()) throw new Error('The sign-in service didn’t load. Check your connection and reload.');
      if (mode === 'join') {
        await A().register({ firstName: f.firstName, email: f.email, password: f.password, marketing: false });
        // With "Confirm email" on, register() succeeds but there is no session yet.
        if (!A().isLoggedIn()) { setSent('Almost there — confirm your email from your inbox, then sign in.'); setBusy(false); return; }
      } else {
        await A().login({ email: f.email, password: f.password });
      }
      setBusy(false);
      onDone();
    } catch (e) {
      setErr((e && e.message) || 'Something went wrong. Please try again.');
      setBusy(false);
    }
  }

  async function reset() {
    setErr('');
    if (!f.email) { setErr('Enter your email first and I’ll send a reset link.'); return; }
    try { await A().resetPassword(f.email); setSent('Reset link sent. Check your inbox — the link opens on the website.'); }
    catch (e) { setErr((e && e.message) || 'Couldn’t send that reset link.'); }
  }

  const label = { ...S.mono, fontSize: 9, color: 'var(--muted)', marginBottom: 6 };
  const input = { width: '100%', boxSizing: 'border-box', border: '1px solid var(--line)', borderRadius: 12, padding: '14px 15px', ...S.sans, fontSize: 15, background: 'var(--card)', color: 'var(--ink)', outline: 'none' };

  return (
    <Sheet open={open} onClose={onClose} height="88%">
      <div className="aw-scroll" style={{ position: 'absolute', inset: 0, overflowY: 'auto', padding: '34px 22px 30px' }}>
        <Eyebrow>{mode === 'join' ? 'Join AIWine' : 'Welcome back'}</Eyebrow>
        <div style={{ ...S.serif, fontSize: 32, lineHeight: 1.06, marginTop: 10, color: 'var(--ink)' }}>
          {mode === 'join' ? 'One account for the app and the website.' : 'Sign in.'}
        </div>
        <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 12 }}>
          {mode === 'join'
            ? 'Your cellar, your taste profile and your cart follow you — phone, laptop, and back again. Free; no card needed.'
            : 'The same email and password you use at aiwine.co.nz.'}
        </div>

        {sent ? (
          <div style={{ marginTop: 24, borderRadius: 16, border: '1px solid var(--green)', background: 'var(--bg-alt)', padding: 18 }}>
            <div style={{ ...S.serif, fontSize: 21, color: 'var(--ink)' }}>{sent}</div>
            <div style={{ marginTop: 16 }}><Btn kind="ghost" onClick={() => { setSent(''); setMode('signin'); }}>Back to sign in</Btn></div>
          </div>
        ) : (
          <div style={{ marginTop: 24 }}>
            {mode === 'join' && (
              <div style={{ marginBottom: 14 }}>
                <div style={label}>First name</div>
                <input value={f.firstName} onChange={set('firstName')} autoComplete="given-name" style={input} />
              </div>
            )}
            <div style={{ marginBottom: 14 }}>
              <div style={label}>Email</div>
              <input value={f.email} onChange={set('email')} type="email" inputMode="email" autoCapitalize="off" autoComplete="email" style={input} />
            </div>
            <div style={{ marginBottom: 6 }}>
              <div style={label}>Password</div>
              <input value={f.password} onChange={set('password')} type="password" autoComplete={mode === 'join' ? 'new-password' : 'current-password'}
                onKeyDown={e => e.key === 'Enter' && submit()} style={input} />
            </div>
            {mode === 'signin' && (
              <button onClick={reset} style={{ ...S.sans, fontSize: 12.5, color: 'var(--claret)', background: 'none', border: 'none', padding: 0, marginTop: 8, cursor: 'pointer' }}>Forgotten your password?</button>
            )}

            {err && <div style={{ marginTop: 16, borderRadius: 12, border: '1px solid var(--claret)', padding: '13px 15px', ...S.sans, fontSize: 13, lineHeight: 1.5, color: 'var(--claret)' }}>{err}</div>}

            <div style={{ marginTop: 22 }}>
              <Btn full onClick={submit} style={{ opacity: busy ? .6 : 1 }}>{busy ? 'One moment…' : mode === 'join' ? 'Create my account' : 'Sign in'}</Btn>
            </div>
            <button onClick={() => { setErr(''); setMode(mode === 'join' ? 'signin' : 'join'); }}
              style={{ ...S.sans, fontSize: 13, color: 'var(--ink-soft)', background: 'none', border: 'none', width: '100%', marginTop: 16, cursor: 'pointer' }}>
              {mode === 'join' ? 'I already have an account — sign in' : 'New to AIWine? Create an account'}
            </button>
            <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', textAlign: 'center', marginTop: 18, lineHeight: 1.5 }}>
              You must be 18 or over to buy wine in New Zealand.
            </div>
          </div>
        )}
      </div>
    </Sheet>
  );
}

/* The account block on the You tab. */
function AccountCard({ onAuth, onSignOut }) {
  const signed = AIW.signedIn(), email = AIW.email();
  if (!signed) {
    return (
      <div style={{ borderRadius: 20, border: '1px solid var(--line)', background: 'var(--card)', padding: 22 }}>
        <Eyebrow>Your account</Eyebrow>
        <div style={{ ...S.serif, fontSize: 25, lineHeight: 1.12, marginTop: 10, color: 'var(--ink)' }}>Sign in to keep all of this.</div>
        <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 10 }}>
          Right now your cellar and taste profile live on this phone only. Sign in and they follow you to any device — and your cart is the same basket as the website.
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 18, flexWrap: 'wrap' }}>
          <Btn small onClick={() => onAuth('join')}>Create an account</Btn>
          <Btn small kind="ghost" onClick={() => onAuth('signin')}>Sign in</Btn>
        </div>
      </div>
    );
  }
  return (
    <div style={{ borderRadius: 20, border: '1px solid var(--line)', background: 'var(--card)', padding: 22 }}>
      <Eyebrow>Your account</Eyebrow>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 12 }}>
        <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--green-bright)', flex: 'none' }} />
        <div style={{ ...S.serif, fontSize: 21, color: 'var(--ink)', wordBreak: 'break-all' }}>{email}</div>
      </div>
      <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 8, lineHeight: 1.5 }}>
        Signed in · your cellar, taste profile and cart are synced across your devices.
      </div>
      <button onClick={onSignOut} style={{ ...S.sans, fontSize: 12.5, fontWeight: 600, color: 'var(--claret)', background: 'none', border: 'none', padding: 0, marginTop: 14, cursor: 'pointer' }}>Sign out</button>
    </div>
  );
}

Object.assign(window, { AuthSheet, AccountCard });
