// Auth gate modal — real OTP path for patients, name-only for doctors.

let _gateState = { open: false, intendedRoute: null, mode: 'choose' };
const GATE_EVENT = 'molara:gate-change';

function openGate(intendedRoute, mode = 'choose') {
  _gateState = { open: true, intendedRoute, mode };
  window.dispatchEvent(new CustomEvent(GATE_EVENT, { detail: _gateState }));
}
function closeGate() {
  _gateState = { open: false, intendedRoute: null, mode: 'choose' };
  window.dispatchEvent(new CustomEvent(GATE_EVENT, { detail: _gateState }));
}
function setGateMode(mode) {
  _gateState = { ..._gateState, mode };
  window.dispatchEvent(new CustomEvent(GATE_EVENT, { detail: _gateState }));
}

function requireAuth(route) {
  const auth = (() => {
    try { return JSON.parse(localStorage.getItem('molara.auth.v1') || 'null'); }
    catch (_) { return null; }
  })();
  if (auth && auth.role !== 'doctor') {
    window.navigate && window.navigate(route);
  } else {
    openGate(route, 'choose');
  }
}

window.requireAuth = requireAuth;
window.openGate = openGate;
window.closeGate = closeGate;

function AuthGate() {
  const [state, setState] = React.useState(_gateState);
  React.useEffect(() => {
    const fn = (e) => setState(e.detail);
    window.addEventListener(GATE_EVENT, fn);
    const esc = (e) => e.key === 'Escape' && closeGate();
    document.addEventListener('keydown', esc);
    return () => { window.removeEventListener(GATE_EVENT, fn); document.removeEventListener('keydown', esc); };
  }, []);
  React.useEffect(() => {
    if (state.open) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [state.open]);
  if (!state.open) return null;

  const finishAuth = () => {
    const dest = state.intendedRoute || '/dashboard';
    closeGate();
    window.navigate && window.navigate(dest);
  };

  const intendedPath = (state.intendedRoute || '').split('?')[0];
  const intendedLabel = ROUTE_LABEL[intendedPath] || 'continue';

  return (
    <div onClick={closeGate} style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'oklch(20% 0.04 240 / 0.5)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      display: 'grid', placeItems: 'center', padding: 20,
      animation: 'gate-fade 180ms ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 460, background: '#fff', borderRadius: 18,
        boxShadow: '0 30px 80px rgba(14,20,40,.28), 0 4px 12px rgba(14,20,40,.08)',
        overflow: 'hidden', fontFamily: 'var(--sans)',
        animation: 'gate-pop 220ms cubic-bezier(.2,.9,.3,1.2)',
        position: 'relative',
      }}>
        <button onClick={closeGate} aria-label="Close" style={{
          position: 'absolute', top: 16, right: 16, zIndex: 2,
          width: 32, height: 32, borderRadius: '50%',
          background: 'rgba(255,255,255,0.9)', border: '1px solid var(--line)',
          cursor: 'pointer', color: 'var(--ink-2)',
          display: 'grid', placeItems: 'center',
        }}>
          <I.close size={14}/>
        </button>

        {state.mode === 'choose' && <ChooseStep intendedLabel={intendedLabel} setMode={setGateMode}/>}
        {state.mode === 'signin' && <ModalOtp intendedLabel={intendedLabel} onDone={finishAuth} onBack={() => setGateMode('choose')}/>}
        {state.mode === 'signup' && <ModalOtp intendedLabel={intendedLabel} onDone={finishAuth} onBack={() => setGateMode('choose')} signup/>}
      </div>
    </div>
  );
}

const ROUTE_LABEL = {
  '/book': 'book your visit', '/instant': 'start a consult',
  '/dashboard': 'open your dashboard', '/appointments': 'view your appointments',
  '/records': 'open your records', '/payments': 'view payments',
  '/profile': 'open your profile', '/visit': 'join your visit',
  '/visit/summary': 'see your visit summary', '/confirmed': 'finish booking',
};

function ChooseStep({ intendedLabel, setMode }) {
  return (
    <div style={{ position: 'relative', padding: '40px 36px 32px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 22 }}>
        <div style={{ width: 32, height: 32, borderRadius: 9, background: 'var(--blue)', color: '#fff', display: 'grid', placeItems: 'center' }}>
          <I.pulse size={16}/>
        </div>
        <div style={{ fontFamily: 'var(--display)', fontSize: 19, letterSpacing: '-0.02em' }}>molara</div>
      </div>
      <h2 style={{ fontFamily: 'var(--display)', fontSize: 26, lineHeight: 1.15, letterSpacing: '-0.025em', margin: '0 0 8px', textWrap: 'balance' }}>
        Sign in to {intendedLabel}.
      </h2>
      <p style={{ fontSize: 14, color: 'var(--ink-3)', margin: '0 0 22px', lineHeight: 1.55 }}>
        We'll send you a 6-digit code by email or mobile. No password to remember.
      </p>
      <div style={{ display: 'grid', gap: 10, marginBottom: 12 }}>
        <button onClick={() => setMode('signin')} className="ml-btn ml-btn--primary"
          style={{ justifyContent: 'space-between', padding: '14px 18px', fontSize: 14 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <I.user size={15}/> Sign in with email or mobile
          </span>
          <I.arrowR size={14}/>
        </button>
      </div>
      <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 14, display: 'flex', alignItems: 'center', gap: 6 }}>
        <I.shield size={12}/> One-time code · expires in 10 minutes
      </div>
    </div>
  );
}

function ModalOtp({ onDone, onBack, intendedLabel, signup }) {
  const [step, setStep] = React.useState('email');
  const [loginMethod, setLoginMethod] = React.useState('email');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [name, setName] = React.useState('');
  const [code, setCode] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [info, setInfo] = React.useState('');
  const [devCode, setDevCode] = React.useState('');

  const sendCode = async () => {
    setErr(''); setInfo(''); setBusy(true);
    try {
      const contact = loginMethod === 'phone' ? phone.trim() : email.trim();
      const r = loginMethod === 'phone'
        ? await window.molaraAuth.requestPatientPhoneOtp(phone.trim())
        : await window.molaraAuth.requestPatientOtp(email.trim());
      if (r?.devCode) setDevCode(r.devCode);
      setInfo(r?.sent ? `Code sent to ${contact}.` : (r?.warning || 'Server is in dev mode — check console.'));
      setStep('code');
    } catch (e) { setErr(e.message || 'Could not send code.'); }
    finally { setBusy(false); }
  };
  const verify = async () => {
    setErr(''); setBusy(true);
    try {
      const r = await window.molaraAuth.verifyPatientOtp({ email: loginMethod === 'email' ? email.trim() : '', phone: loginMethod === 'phone' ? phone.trim() : '', code: code.trim(), name: name.trim(), method: loginMethod });
      if (r?.user) onDone();
    } catch (e) { setErr(e.message || 'Could not verify.'); }
    finally { setBusy(false); }
  };

  return (
    <div style={{ position: 'relative', padding: '36px 36px 32px' }}>
      <button onClick={onBack} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', fontSize: 12, padding: 0, marginBottom: 18, fontFamily: 'inherit' }}>
        <I.chevronL size={12}/> Back
      </button>

      {step === 'email' && (
        <>
          <h2 style={{ fontFamily: 'var(--display)', fontSize: 24, lineHeight: 1.15, letterSpacing: '-0.025em', margin: '0 0 8px' }}>
            Sign in with email or mobile
          </h2>
          <p style={{ fontSize: 13, color: 'var(--ink-3)', margin: '0 0 20px' }}>
            We'll send a 6-digit code. No password needed.
          </p>
          <div className="ml-tonestrip" style={{ marginBottom: 14 }}>
            <button className={loginMethod === 'email' ? 'active' : ''} onClick={() => { setLoginMethod('email'); setErr(''); }}>Email</button>
            <button className={loginMethod === 'phone' ? 'active' : ''} onClick={() => { setLoginMethod('phone'); setErr(''); }}>Mobile OTP</button>
          </div>
          <div style={{ marginBottom: 12 }}>
            <label className="ml-label" style={{ marginBottom: 6, display: 'block' }}>{loginMethod === 'phone' ? 'Mobile number' : 'Email'}</label>
            {loginMethod === 'phone' ? (
              <input className="ml-input" type="tel" placeholder="98765 43210" value={phone}
                onChange={(e) => setPhone(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && phone && sendCode()} autoFocus/>
            ) : (
              <input className="ml-input" type="email" placeholder="you@gmail.com" value={email}
                onChange={(e) => setEmail(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && email && sendCode()} autoFocus/>
            )}
          </div>
          <div style={{ marginBottom: 14 }}>
            <label className="ml-label" style={{ marginBottom: 6, display: 'block' }}>Name <span style={{ color: 'var(--ink-4)', fontWeight: 400 }}>(first time only)</span></label>
            <input className="ml-input" placeholder="Your name" value={name} onChange={(e) => setName(e.target.value)}/>
          </div>
          {err && <div style={errStyle}>{err}</div>}
          <button onClick={sendCode} disabled={busy || !(loginMethod === 'phone' ? phone : email)} className="ml-btn ml-btn--primary"
            style={{ width: '100%', justifyContent: 'center', padding: '13px', opacity: (busy || !(loginMethod === 'phone' ? phone : email)) ? 0.6 : 1 }}>
            {busy ? 'Sending…' : (loginMethod === 'phone' ? 'Text me a code' : 'Email me a code')} <I.arrowR size={14}/>
          </button>
        </>
      )}

      {step === 'code' && (
        <>
          <h2 style={{ fontFamily: 'var(--display)', fontSize: 22, lineHeight: 1.15, letterSpacing: '-0.025em', margin: '0 0 8px' }}>
            Enter the 6-digit code
          </h2>
          <p style={{ fontSize: 13, color: 'var(--ink-3)', margin: '0 0 14px' }}>Sent to {loginMethod === 'phone' ? phone : email}.</p>
          {info && <div style={infoStyle}>{info}</div>}
          {devCode && <div style={{ ...infoStyle, fontFamily: 'var(--mono)' }}>Dev code: <b>{devCode}</b></div>}
          <input className="ml-input" maxLength={6} placeholder="123456" value={code}
            onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
            onKeyDown={(e) => e.key === 'Enter' && code.length === 6 && verify()}
            style={{ fontFamily: 'var(--mono)', fontSize: 22, textAlign: 'center', letterSpacing: 8, marginBottom: 14 }} autoFocus/>
          {err && <div style={errStyle}>{err}</div>}
          <button onClick={verify} disabled={busy || code.length < 6} className="ml-btn ml-btn--primary"
            style={{ width: '100%', justifyContent: 'center', padding: '13px', opacity: (busy || code.length < 6) ? 0.6 : 1 }}>
            {busy ? 'Verifying…' : 'Verify & continue'} <I.arrowR size={14}/>
          </button>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 14, textAlign: 'center' }}>
            Didn't get it? <a onClick={sendCode} style={{ color: 'var(--blue-deep)', cursor: 'pointer', fontWeight: 500 }}>Resend</a>
          </div>
        </>
      )}
    </div>
  );
}

const errStyle = { background: 'oklch(96% 0.04 25)', border: '1px solid oklch(82% 0.12 25)', color: 'oklch(40% 0.15 25)', padding: '10px 14px', borderRadius: 8, fontSize: 13, marginBottom: 12 };
const infoStyle = { background: 'var(--paper-2)', border: '1px solid var(--line)', color: 'var(--ink-2)', padding: '10px 14px', borderRadius: 8, fontSize: 12.5, marginBottom: 12 };

window.AuthGate = AuthGate;
