// petal-auth.jsx — splash + passwordless email-OTP sign-in + auth gate.
const { useState: useA, useEffect: useAE, useRef: useAR } = React;

function Splash() {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      background: 'linear-gradient(180deg,#FBF4EF 0%,#F7ECE6 100%)', gap: 16 }}>
      <div style={{ animation: 'petalspin 2.4s linear infinite' }}><Bloom size={46} /></div>
      <div style={{ fontFamily: SERIF, fontSize: 22, color: PAL.deep }}>{CFG.APP_NAME || 'Petal'}</div>
    </div>
  );
}

const authInput = {
  border: `1.5px solid ${PAL.border}`, background: '#fff', borderRadius: 14, padding: '14px 16px',
  fontSize: 15.5, fontFamily: FONT, color: PAL.ink, outline: 'none', width: '100%',
};
const authBtn = {
  border: 'none', background: PAL.blush, color: '#fff', borderRadius: 16, padding: '15px',
  fontSize: 16.5, fontWeight: 700, fontFamily: FONT, cursor: 'pointer',
  boxShadow: '0 8px 20px rgba(217,140,140,0.40)', width: '100%',
};
const ghostLink = {
  background: 'transparent', border: 'none', color: PAL.deep, fontFamily: FONT, fontSize: 14,
  fontWeight: 600, cursor: 'pointer', padding: '4px 2px', textDecoration: 'underline', textUnderlineOffset: 3,
};
const OTP_CODE_LENGTH = Math.max(1, Math.min(12, Number(CFG.OTP_CODE_LENGTH) || 8));

function Login({ onSignedIn }) {
  const [step, setStep] = useA('email'); // email | code
  const [email, setEmail] = useA('');
  const [code, setCode] = useA('');
  const [busy, setBusy] = useA(false);
  const [err, setErr] = useA('');
  const live = PetalAPI.LIVE;
  const codeRef = useAR(null);

  const validEmail = /\S+@\S+\.\S+/.test(email.trim());

  async function sendCode(e) {
    if (e) e.preventDefault();
    setErr('');
    if (!validEmail) { setErr('Please enter a valid email.'); return; }
    setBusy(true);
    try {
      await PetalAPI.auth.sendOtp(email.trim());
      setStep('code');
      setTimeout(() => codeRef.current && codeRef.current.focus(), 60);
    } catch (e2) {
      setErr('We couldn\u2019t send a code to that email. Make sure it\u2019s your invited address.');
    }
    setBusy(false);
  }

  async function verify(e) {
    if (e) e.preventDefault();
    setErr('');
    if (!live && code.trim().length < OTP_CODE_LENGTH) { setErr(`Enter any ${OTP_CODE_LENGTH} digits to continue (demo).`); return; }
    if (live && code.trim().length < OTP_CODE_LENGTH) { setErr(`Enter the ${OTP_CODE_LENGTH}-digit code from your email.`); return; }
    setBusy(true);
    try {
      const u = await PetalAPI.auth.verifyOtp(email.trim(), code.trim());
      onSignedIn(u);
    } catch (e2) {
      setErr('That code didn\u2019t match. Check your email or send a new one.');
      setBusy(false);
    }
  }

  const demoEnter = (role) => onSignedIn(PetalAPI.auth.demoSignIn(role));

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'center',
      background: 'linear-gradient(180deg,#FBF4EF 0%,#F4E6DF 100%)', padding: '0 26px' }}>
      <div style={{ textAlign: 'center', marginBottom: 26 }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}><Bloom size={42} /></div>
        {step === 'email' ? (
          <React.Fragment>
            <div style={{ fontFamily: SERIF, fontSize: 34, color: PAL.ink, lineHeight: 1.05 }}>Welcome back</div>
            <div style={{ fontSize: 14.5, color: PAL.mut, marginTop: 8, lineHeight: 1.45 }}>
              Your private little check-in space.<br />Only {PEOPLE.patient} &amp; {PEOPLE.doctor} can come in.
            </div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div style={{ fontFamily: SERIF, fontSize: 32, color: PAL.ink, lineHeight: 1.08 }}>Check your email</div>
            <div style={{ fontSize: 14.5, color: PAL.mut, marginTop: 8, lineHeight: 1.45 }}>
              We sent your {OTP_CODE_LENGTH}-digit code to<br /><span style={{ color: PAL.ink, fontWeight: 600 }}>{email}</span>
            </div>
          </React.Fragment>
        )}
      </div>

      {step === 'email' ? (
        <form onSubmit={sendCode} style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@email.com"
            autoComplete="email" autoFocus style={authInput} />
          {err && <div style={{ fontSize: 13, color: PAL.deep, textAlign: 'center' }}>{err}</div>}
          <button type="submit" disabled={busy} style={{ ...authBtn, opacity: busy ? 0.6 : 1, marginTop: 4 }}>
            {busy ? 'Sending…' : 'Email me a code'}
          </button>
        </form>
      ) : (
        <form onSubmit={verify} style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
          <input ref={codeRef} value={code} onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, OTP_CODE_LENGTH))}
            inputMode="numeric" placeholder={'•'.repeat(OTP_CODE_LENGTH)} maxLength={OTP_CODE_LENGTH}
            style={{ ...authInput, textAlign: 'center', fontSize: 26, letterSpacing: 12, fontWeight: 700, padding: '14px 16px' }} />
          {err && <div style={{ fontSize: 13, color: PAL.deep, textAlign: 'center' }}>{err}</div>}
          <button type="submit" disabled={busy} style={{ ...authBtn, opacity: busy ? 0.6 : 1, marginTop: 4 }}>
            {busy ? 'Verifying…' : 'Verify & sign in'}
          </button>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 16, marginTop: 4 }}>
            <button type="button" onClick={() => { setStep('email'); setCode(''); setErr(''); }} style={{ ...ghostLink, fontSize: 13, textDecoration: 'none' }}>‹ Different email</button>
            {live && <button type="button" onClick={sendCode} style={{ ...ghostLink, fontSize: 13, textDecoration: 'none' }}>Resend code</button>}
          </div>
        </form>
      )}

      {!live && (
        <div style={{ marginTop: 24, textAlign: 'center' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: '#fff', border: `1px solid ${PAL.border}`,
            borderRadius: 999, padding: '6px 13px', fontSize: 12, color: PAL.mut, marginBottom: 14 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: PAL.amber }} />
            Preview mode — {step === 'code' ? `type any ${OTP_CODE_LENGTH} digits` : 'no backend connected yet'}
          </div>
          {step === 'email' && (
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
              <button onClick={() => demoEnter('patient')} style={ghostLink}>Peek as {PEOPLE.patient}</button>
              <span style={{ color: PAL.border }}>·</span>
              <button onClick={() => demoEnter('doctor')} style={ghostLink}>Peek as {PEOPLE.doctor}</button>
            </div>
          )}
          <div style={{ fontSize: 11.5, color: PAL.mut, marginTop: 16, lineHeight: 1.5, opacity: 0.85 }}>
            Add your Supabase keys in <code style={{ background: '#fff', padding: '1px 5px', borderRadius: 5 }}>petal-config.js</code> for real OTP sign-in. See DEPLOY.md.
          </div>
        </div>
      )}
    </div>
  );
}

function AuthGate({ children }) {
  const [status, setStatus] = useA('loading');
  const [user, setUser] = useA(null);

  useAE(() => {
    (async () => {
      await PetalAPI.init();
      const u = await PetalAPI.auth.current();
      if (u) { setUser(u); setStatus('in'); } else { setStatus('out'); }
    })();
  }, []);

  const onSignedIn = (u) => { setUser(u); setStatus('in'); };
  const signOut = async () => { await PetalAPI.auth.signOut(); setUser(null); setStatus('out'); };

  if (status === 'loading') return <Splash />;
  if (status === 'out') return <Login onSignedIn={onSignedIn} />;
  return children(user, signOut);
}

Object.assign(window, { AuthGate });
