// Molara — Sign in / Create account (real OTP + doctor-by-name)

function signInRouteParams(route) {
  const q = (route || window.location.hash.replace(/^#/, '') || '').split('?')[1] || '';
  return new URLSearchParams(q);
}

function SignIn({ tone = 'warm', role = 'patient', route = '' }) {
  const [mode, setMode] = React.useState('signin'); // 'signin' | 'otp'
  const [loginMethod, setLoginMethod] = React.useState('email'); // 'email' | 'phone'
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [name, setName] = React.useState('');
  const [doctorName, setDoctorName] = React.useState('');
  const [otp, setOtp] = React.useState(['', '', '', '', '', '']);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [info, setInfo] = React.useState('');
  const [devCode, setDevCode] = React.useState('');

  const setOtpAt = (i, v) => {
    const n = [...otp];
    n[i] = v.slice(-1);
    setOtp(n);
    if (v && i < 5) {
      const next = document.querySelectorAll('[data-otp-input]')[i + 1];
      next && next.focus();
    }
  };

  const warm = tone === 'warm';
  const isDoctor = role === 'doctor';
  const nextRoute = signInRouteParams(route).get('next');
  const contactValue = loginMethod === 'phone' ? phone.trim() : email.trim();
  const contactLabel = loginMethod === 'phone' ? 'mobile number' : 'email';

  const sendCode = async () => {
    setErr(''); setInfo(''); setBusy(true);
    try {
      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 ${contactValue}.`
        : (r?.warning || 'Server is in dev mode — see console for code.'));
      setMode('otp');
    } catch (e) {
      setErr(e.message || 'Could not send code.');
    } finally { setBusy(false); }
  };

  const verifyCode = async () => {
    setErr(''); setBusy(true);
    try {
      const code = otp.join('');
      const r = await window.molaraAuth.verifyPatientOtp({ email: loginMethod === 'email' ? email.trim() : '', phone: loginMethod === 'phone' ? phone.trim() : '', code, name: name.trim(), method: loginMethod });
      if (r?.user) window.navigate && window.navigate(nextRoute || '/dashboard');
    } catch (e) {
      setErr(e.message || 'Could not verify code.');
    } finally { setBusy(false); }
  };

  const doctorSignIn = async () => {
    setErr(''); setBusy(true);
    try {
      const r = await window.molaraAuth.doctorSignIn(doctorName.trim());
      if (r?.user) window.navigate && window.navigate('/doctor-dashboard');
    } catch (e) {
      setErr(e.message || 'Sign in failed.');
    } finally { setBusy(false); }
  };

  return (
    <div className="ml-root" style={{ height: '100%', display: 'grid', gridTemplateColumns: '1fr 1fr', background: '#fff' }}>
      <div style={{ padding: '40px 56px', display: 'flex', flexDirection: 'column', overflowY: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 56 }}>
          <Logo size={20} />
          <div style={{ marginLeft: 'auto', fontSize: 13, color: 'var(--ink-3)' }}>
            {isDoctor
              ? <>Patient? <a onClick={() => window.navigate('/signin')} style={{ color: 'var(--blue-deep)', fontWeight: 500, cursor: 'pointer' }}>Patient sign in</a></>
              : <>Are you a dentist? <a onClick={() => window.navigate('/doctor-signin')} style={{ color: 'var(--blue-deep)', fontWeight: 500, cursor: 'pointer' }}>Dentist sign in</a></>}
          </div>
        </div>

        <div style={{ maxWidth: 440, width: '100%', margin: 'auto 0' }}>
          {!isDoctor && mode === 'signin' && (
            <>
              <div className="ml-label" style={{ marginBottom: 14 }}>PATIENT SIGN IN</div>
              <h1 style={{ fontSize: 44, lineHeight: 1.05, letterSpacing: '-0.03em', marginBottom: 14 }}>
                {warm ? <>Sign in with email or mobile.</> : <>Sign in.</>}
              </h1>
              <p style={{ fontSize: 15, color: 'var(--ink-3)', marginBottom: 28 }}>
                We'll send you a 6-digit code. No password to remember.
              </p>

              <div className="ml-tonestrip" style={{ marginBottom: 18 }}>
                <button className={loginMethod === 'email' ? 'active' : ''} onClick={() => { setLoginMethod('email'); setErr(''); setInfo(''); }}>
                  Email
                </button>
                <button className={loginMethod === 'phone' ? 'active' : ''} onClick={() => { setLoginMethod('phone'); setErr(''); setInfo(''); }}>
                  Mobile OTP
                </button>
              </div>

              <div style={{ marginBottom: 14 }}>
                <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()}/>
                ) : (
                  <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()}/>
                )}
              </div>

              <div style={{ marginBottom: 14 }}>
                <label className="ml-label" style={{ marginBottom: 6, display: 'block' }}>Your name <span style={{ color: 'var(--ink-4)', fontWeight: 400 }}>(first time only)</span></label>
                <input className="ml-input" placeholder="Sara Lin" value={name} onChange={(e) => setName(e.target.value)}/>
              </div>

              {err && <div style={errStyle}>{err}</div>}

              <button onClick={sendCode} disabled={busy || !contactValue}
                className="ml-btn ml-btn--primary"
                style={{ width: '100%', justifyContent: 'center', padding: '14px', marginTop: 10, opacity: (busy || !contactValue) ? 0.6 : 1 }}>
                {busy ? 'Sending…' : (loginMethod === 'phone' ? 'Text me a code' : 'Email me a code')} <I.arrowR size={14}/>
              </button>

              <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 18, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <I.shield size={12}/> One-time code · expires in 10 minutes
              </div>
            </>
          )}

          {!isDoctor && mode === 'otp' && (
            <>
              <a onClick={() => { setMode('signin'); setErr(''); setInfo(''); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--ink-3)', cursor: 'pointer', marginBottom: 24 }}>
                <I.chevronL size={13}/> Back
              </a>
              <div className="ml-label" style={{ marginBottom: 14 }}>VERIFY</div>
              <h1 style={{ fontSize: 40, lineHeight: 1.05, letterSpacing: '-0.03em', marginBottom: 14 }}>
                {warm ? <>Check your {contactLabel}.</> : <>Enter verification code.</>}
              </h1>
              <p style={{ fontSize: 15, color: 'var(--ink-3)', marginBottom: 24 }}>
                We sent a 6-digit code to <b style={{ color: 'var(--ink)' }}>{contactValue}</b>. It's good for 10 minutes.
              </p>
              {info && <div style={infoStyle}>{info}</div>}
              {devCode && <div style={{ ...infoStyle, fontFamily: 'var(--mono)' }}>Dev code: <b>{devCode}</b></div>}

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 10, marginBottom: 18, maxWidth: 360 }}>
                {otp.map((v, i) => (
                  <input key={i} value={v} data-otp-input
                    onChange={(e) => setOtpAt(i, e.target.value)}
                    onKeyDown={(e) => e.key === 'Backspace' && !v && i > 0 && document.querySelectorAll('[data-otp-input]')[i-1].focus()}
                    maxLength={1}
                    style={{ width: '100%', aspectRatio: '1/1.2', textAlign: 'center', fontFamily: 'var(--mono)', fontSize: 22, border: '1.5px solid ' + (v ? 'var(--blue)' : 'var(--line)'), borderRadius: 10, background: '#fff', outline: 'none', color: 'var(--ink)' }}/>
                ))}
              </div>

              {err && <div style={errStyle}>{err}</div>}

              <button onClick={verifyCode} disabled={busy || otp.join('').length < 6}
                className="ml-btn ml-btn--primary" style={{ width: '100%', justifyContent: 'center', padding: '14px', maxWidth: 360, opacity: (busy || otp.join('').length < 6) ? 0.6 : 1 }}>
                {busy ? 'Verifying…' : 'Verify & continue'} <I.arrowR size={14}/>
              </button>

              <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 16 }}>
                Didn't get it? <a onClick={sendCode} style={{ color: 'var(--blue-deep)', cursor: 'pointer', fontWeight: 500 }}>Resend</a>
              </div>
            </>
          )}

          {isDoctor && (
            <>
              <div className="ml-label" style={{ marginBottom: 14 }}>DENTIST PORTAL</div>
              <h1 style={{ fontSize: 40, lineHeight: 1.05, letterSpacing: '-0.03em', marginBottom: 14 }}>
                Sign in with your email or name.
              </h1>
              <p style={{ fontSize: 15, color: 'var(--ink-3)', marginBottom: 28 }}>
                Enter your approved email or your full name exactly as it appears to patients.
              </p>

              <div style={{ marginBottom: 14 }}>
                <label className="ml-label" style={{ marginBottom: 6, display: 'block' }}>Email or full name</label>
                <input className="ml-input" placeholder="810shivani@gmail.com" value={doctorName}
                  onChange={(e) => setDoctorName(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && doctorName && doctorSignIn()}/>
              </div>

              <div style={{ background: 'var(--paper-2)', padding: 12, borderRadius: 8, fontSize: 12, color: 'var(--ink-3)', marginBottom: 16, lineHeight: 1.55 }}>
                <b style={{ color: 'var(--ink-2)' }}>Available names:</b><br/>
                Dr. Shivani Kumari · Dr. Sakshi Sable · Dr. Shirin Chavan · Dr. Sanjana Murthy · Dr. Neha Khandelwal
              </div>

              {err && <div style={errStyle}>{err}</div>}

              <button onClick={doctorSignIn} disabled={busy || !doctorName}
                className="ml-btn ml-btn--primary" style={{ width: '100%', justifyContent: 'center', padding: '14px', opacity: (busy || !doctorName) ? 0.6 : 1 }}>
                {busy ? 'Signing in…' : 'Sign in as dentist'} <I.arrowR size={14}/>
              </button>
            </>
          )}
        </div>

        <div style={{ marginTop: 56, fontSize: 11, color: 'var(--ink-4)', display: 'flex', gap: 14 }}>
          <span>© Molara 2026</span>
          <a style={{ color: 'var(--ink-4)' }}>Privacy</a>
          <a style={{ color: 'var(--ink-4)' }}>Terms</a>
          <a style={{ color: 'var(--ink-4)' }}>Help</a>
        </div>
      </div>

      <aside style={{ background: 'var(--ink)', color: '#fff', padding: 56, position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        <div style={{ position: 'absolute', inset: '-20% -20% auto auto', width: 600, height: 600, borderRadius: '50%', background: 'radial-gradient(circle, oklch(55% 0.18 240 / 0.55), transparent 60%)', filter: 'blur(40px)', pointerEvents: 'none' }}/>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <div className="ml-label" style={{ color: 'oklch(75% 0.05 240)', marginBottom: 20 }}>{isDoctor ? 'TODAY · DENTIST PORTAL' : 'DENTAL CARE · AT A DISTANCE'}</div>
          <h2 style={{ fontSize: 44, color: '#fff', lineHeight: 1.02, letterSpacing: '-0.02em', marginBottom: 36 }}>
            {isDoctor ? <>Your consult queue is <span style={{ fontStyle: 'italic', color: 'oklch(82% 0.1 240)' }}>ready.</span></> : <>Sign in to <span style={{ fontStyle: 'italic', color: 'oklch(82% 0.1 240)' }}>book and chat.</span></>}
          </h2>
          <div style={{ background: 'rgba(255,255,255,.05)', border: '1px solid rgba(255,255,255,.1)', padding: 20, borderRadius: 14, marginBottom: 14 }}>
            <div style={{ fontSize: 13, color: 'oklch(80% 0.02 240)', lineHeight: 1.6 }}>
              {isDoctor
                ? 'When you sign in, patients see you marked online. Bookings, chats, and video calls route directly to you.'
                : 'Real OTP sent to your email or mobile number. Bookings and uploads are stored on the server, so your dentist can see them on their device.'}
            </div>
          </div>
        </div>
      </aside>
    </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: 14,
};
const infoStyle = {
  background: 'var(--paper-2)',
  border: '1px solid var(--line)',
  color: 'var(--ink-2)',
  padding: '10px 14px',
  borderRadius: 8,
  fontSize: 13,
  marginBottom: 14,
};

Object.assign(window, { SignIn });

// ----- Doctor dashboard -----
function DoctorDashboard({ tone = 'warm' }) {
  const { user } = useAuth();
  const consults = useConsults();
  const [selectedId, setSelectedId] = React.useState(null);
  React.useEffect(() => {
    if (!selectedId && consults[0]) setSelectedId(consults[0].id);
  }, [consults, selectedId]);
  const active = consults.find(c => c.id === selectedId) || consults[0] || null;
  const docName = user?.name || 'Dentist';
  const docInitials = user?.initials || 'DR';

  return (
    <div className="ml-root" style={{ height: '100%', overflow: 'auto', background: 'var(--paper-2)' }}>
      <header style={{ height: 68, padding: '0 40px', display: 'flex', alignItems: 'center', gap: 18, background: '#fff', borderBottom: '1px solid var(--line)' }}>
        <Logo size={20}/>
        <span className="ml-pill ml-pill--mint"><span className="ml-live"/> Available — patients see you online</span>
        <button onClick={() => { window.signOutUser && window.signOutUser(); window.navigate('/'); }} className="ml-btn ml-btn--ghost" style={{ marginLeft: 'auto', fontSize: 12 }}>
          Sign out
        </button>
        <div className="ml-avatar" style={{ width: 36, height: 36, borderRadius: 999, fontSize: 13 }}>{docInitials}</div>
      </header>

      <main style={{ padding: '28px 40px 44px', maxWidth: 1240 }}>
        <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', marginBottom: 22 }}>
          <div>
            <div className="ml-label" style={{ marginBottom: 8 }}>DENTIST DASHBOARD</div>
            <h1 style={{ fontSize: 38, marginBottom: 6 }}>Good afternoon, {docName}.</h1>
            <p className="ml-muted" style={{ fontSize: 14, margin: 0 }}>Only consultations booked with you appear here.</p>
          </div>
          <button onClick={() => active && window.navigate && window.navigate(`/visit?consult=${active.id}&role=doctor`)}
            className="ml-btn ml-btn--primary" disabled={!active} style={{ opacity: active ? 1 : 0.55 }}>
            <I.video size={14}/> Start next consult
          </button>
        </div>

        {consults.length === 0 ? (
          <div className="ml-card" style={{ padding: 56, textAlign: 'center' }}>
            <div style={{ width: 56, height: 56, borderRadius: 16, background: 'var(--blue-soft)', color: 'var(--blue-deep)', display: 'grid', placeItems: 'center', margin: '0 auto 16px' }}>
              <I.calendar size={24}/>
            </div>
            <h2 style={{ fontSize: 28, marginBottom: 8 }}>No patient consultations yet.</h2>
            <p className="ml-muted" style={{ maxWidth: 460, margin: '0 auto', fontSize: 14, lineHeight: 1.55 }}>
              When a patient books with you, their consultation will appear here with reason, pain level, and uploaded photos.
            </p>
          </div>
        ) : (
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1.25fr 0.85fr', gap: 18 }}>
          <section style={{ display: 'grid', gap: 12, alignContent: 'start' }}>
            {consults.map((c) => {
              const specialty = SPECIALTIES.find(s => s.k === DOC_BY_ID(c.docId).k);
              const Icon = I[specialty?.icon] || I.tooth;
              const on = c.id === active.id;
              return (
                <button key={c.id} onClick={() => setSelectedId(c.id)} className="ml-card" style={{
                  padding: 16, display: 'grid', gridTemplateColumns: '42px 1fr auto', gap: 12, alignItems: 'center',
                  border: '1px solid ' + (on ? 'var(--blue)' : 'var(--line)'), background: on ? 'var(--blue-tint)' : '#fff',
                  textAlign: 'left', cursor: 'pointer',
                }}>
                  <div style={{ width: 42, height: 42, borderRadius: 10, background: '#fff', display: 'grid', placeItems: 'center', color: 'var(--blue-deep)' }}>
                    <Icon size={18}/>
                  </div>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 500 }}>{c.reason}</div>
                    <div className="ml-muted" style={{ fontSize: 12 }}>{c.id} · {c.patientName}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontFamily: 'var(--mono)', fontSize: 12 }}>{c.time}</div>
                    <span className="ml-pill ml-pill--ghost" style={{ marginTop: 5 }}>Confirmed</span>
                  </div>
                </button>
              );
            })}
          </section>

          <section className="ml-card" style={{ padding: 24 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
              <div className="ml-avatar" style={{ width: 58, height: 58, borderRadius: 14, fontSize: 18 }}>{active.patientInitials}</div>
              <div>
                <h2 style={{ fontSize: 24, marginBottom: 4 }}>{active.reason}</h2>
                <div className="ml-muted" style={{ fontSize: 13 }}>{active.id} · {active.date} · {active.time} · {active.mode} consult</div>
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, marginBottom: 20 }}>
              {[
                ['Pain level', `${active.severity} / 10`],
                ['Care type', active.careType],
                ['Patient', active.patientName],
              ].map(([k, v]) => (
                <div key={k} style={{ padding: 14, background: 'var(--paper-2)', borderRadius: 8 }}>
                  <div className="ml-label" style={{ marginBottom: 5 }}>{k}</div>
                  <div style={{ fontSize: 15, fontWeight: 500 }}>{v}</div>
                </div>
              ))}
            </div>

            <div className="ml-label" style={{ marginBottom: 8 }}>Patient note</div>
            <p style={{ color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.6, marginTop: 0 }}>
              {active.note || 'No extra note added by the patient.'}
            </p>

            <button onClick={() => window.navigate(`/visit?consult=${active.id}&role=doctor`)}
              className="ml-btn ml-btn--primary" style={{ marginTop: 12 }}>
              <I.video size={14}/> Join video visit
            </button>
          </section>

          <aside style={{ display: 'grid', gap: 14, alignContent: 'start' }}>
            <div className="ml-card" style={{ padding: 18 }}>
              <div className="ml-label" style={{ marginBottom: 12 }}>Today</div>
              <div style={{ fontFamily: 'var(--display)', fontSize: 34 }}>{consults.length}</div>
              <div className="ml-muted" style={{ fontSize: 12 }}>patient consult{consults.length === 1 ? '' : 's'} booked</div>
            </div>
            <div className="ml-card" style={{ padding: 18 }}>
              <div className="ml-label" style={{ marginBottom: 12 }}>Records uploaded</div>
              <DoctorRecords/>
            </div>
          </aside>
        </div>
        )}
      </main>
    </div>
  );
}

function DoctorRecords() {
  const records = useRecords();
  if (!records.length) return <div className="ml-muted" style={{ fontSize: 12 }}>None yet.</div>;
  return (
    <div style={{ display: 'grid', gap: 8 }}>
      {records.slice(0, 4).map((r) => (
        <a key={r.id} href={r.url || '#'} target="_blank" rel="noreferrer" style={{ display: 'flex', gap: 10, alignItems: 'center', padding: 8, borderRadius: 8, background: 'var(--paper-2)', textDecoration: 'none', color: 'var(--ink)' }}>
          <div style={{ width: 32, height: 32, borderRadius: 6, background: '#fff', display: 'grid', placeItems: 'center', color: 'var(--blue-deep)' }}>
            <I.file size={14}/>
          </div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.name}</div>
            <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{r.patientName || 'Patient'}</div>
          </div>
        </a>
      ))}
    </div>
  );
}

window.DoctorDashboard = DoctorDashboard;

// Brand glyphs (kept for other components that reference them)
function GoogleG({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true">
      <circle cx="12" cy="12" r="10" fill="none" stroke="var(--ink-3)" strokeWidth="1.5"/>
      <text x="12" y="16" textAnchor="middle" fontFamily="var(--display)" fontSize="13" fontWeight="600" fill="var(--ink)">G</text>
    </svg>
  );
}
function AppleGlyph({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true">
      <path d="M15.5 4.5c-.9.9-2 1.5-3.1 1.4-.1-1.1.4-2.2 1.2-3 .9-.9 2.1-1.5 3.1-1.5.1 1.1-.3 2.2-1.2 3.1zM20 17.5c-.4 1-1 1.9-1.7 2.7-.9 1.1-2.2 2.4-3.8 2.4-1.4 0-1.8-.9-3.8-.9s-2.4.9-3.8.9c-1.6 0-2.9-1.3-3.8-2.4-2.4-3-2.7-6.5-1.2-8.4 1-1.3 2.6-2.1 4.2-2.1 1.5 0 2.4.9 3.7.9s2-.9 3.8-.9c1.3 0 2.7.7 3.7 1.9-3.2 1.8-2.7 6.2.7 7.9z" fill="var(--ink)"/>
    </svg>
  );
}
window.GoogleG = GoogleG;
window.AppleGlyph = AppleGlyph;
