/* SigninModal.jsx — sign-in modal (Parent | Teacher entry)
   Two equally-weighted role cards: Parents only (violet accent) and
   Teachers only (teal accent). Each card offers Kakao + Google sign-in
   and surfaces the "owner approval required" pill so the closed-gate
   model is communicated up front. Lives outside the App composition
   so it can call useT() against the LangContext that App provides. */

const SigninModal = ({ open, onClose, parentHref, teacherHref, role = 'both' }) => {
  const showParent  = role === 'parent'  || role === 'both';
  const showTeacher = role === 'teacher' || role === 'both';

  /* Build absolute callback URLs once — Supabase requires the exact origin+path
     match against the URLs registered in Authentication → URL Configuration.
     `new URL(rel, base).href` resolves "../sriki-parent/index.html" against the
     current page so it works equally for localhost and any deployed origin. */
  const parentCallback  = new URL(parentHref,  window.location.href).href;
  const teacherCallback = new URL(teacherHref, window.location.href).href;

  const startOAuth = (provider, redirectTo) => {
    if (window.SRIKI_AUTH) {
      void window.SRIKI_AUTH.signInWithOAuth(provider, redirectTo);
    } else {
      /* Hard fallback: supabase-js failed to load → at least take the user
         to the subapp page so the flow visibly continues. */
      window.location.href = redirectTo;
    }
  };
  const t = window.useT();
  const { lang } = React.useContext(window.LangContext);

  /* Close on Escape — modal is dismissible like any standard dialog */
  React.useEffect(() => {
    if (!open) return;
    const onKey = e => { if (e.key === 'Escape') onClose?.(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(11, 23, 39, 0.55)',
      backdropFilter: 'blur(6px)',
      WebkitBackdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 16,
      animation: 'srikiModalFade 200ms ease',
    }}>
      <div onClick={e => e.stopPropagation()} className="sriki-signin-modal" role="dialog" aria-modal="true" style={{
        width: 460, maxWidth: '100%', background: '#fff', borderRadius: 16,
        padding: 28,
        maxHeight: 'calc(100dvh - 32px)', overflowY: 'auto',
        boxShadow:
          '0 4px 12px rgba(15,23,42,0.06),' +
          '0 40px 80px -20px rgba(15,23,42,0.30)',
        animation: 'srikiModalRise 240ms cubic-bezier(0.2,0.6,0.25,1)',
      }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
          <div style={{
            fontFamily: 'var(--font-sans)', fontFeatureSettings: '"ss01"',
            fontSize: 24, fontWeight: 700, letterSpacing: '-0.3px',
            color: '#0B1727',
          }}>{t('signin.modal.title')}</div>
          <button onClick={onClose} aria-label={lang === 'ko' ? '닫기' : 'Close'} style={{
            width: 32, height: 32, borderRadius: 8,
            border: 0, background: '#F8FAFC', cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: '#475569',
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
              stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"/>
              <line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
        </div>
        <div style={{
          fontSize: 13.5, fontWeight: 400,
          color: '#475569', marginTop: 4, lineHeight: 1.60,
        }}>
          {role === 'both' ? t('signin.modal.desc') : t('signin.modal.desc.single')}
        </div>

        {/* Parent card */}
        {showParent && <window.SigninRoleCard
          accent="#6D28D9"
          accentSoft="rgba(109,40,217,0.10)"
          bg="linear-gradient(135deg, #FFFFFF 0%, #FAF5FF 100%)"
          title={t('signin.parent.title')}
          desc={t('signin.parent.desc')}
          badge={t('signin.badge.approval')}
          note={t('signin.note.parent')}
          ctaKakao={t('signin.cta.kakao')}
          ctaGoogle={t('signin.cta.google')}
          onKakao={() => startOAuth('kakao',  parentCallback)}
          onGoogle={() => startOAuth('google', parentCallback)}
          icon={(
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none"
              stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
              <circle cx="9" cy="7" r="4"/>
              <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
              <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
            </svg>
          )}
          topMargin={20}
        />}

        {/* Teacher card */}
        {showTeacher && <window.SigninRoleCard
          accent="#0F766E"
          accentSoft="rgba(15,118,110,0.10)"
          bg="linear-gradient(135deg, #FFFFFF 0%, #F0FDFA 100%)"
          title={t('signin.teacher.title')}
          desc={t('signin.teacher.desc')}
          badge={t('signin.badge.approval')}
          note={t('signin.note.teacher')}
          ctaKakao={t('signin.cta.kakao')}
          ctaGoogle={t('signin.cta.google')}
          onKakao={() => startOAuth('kakao',  teacherCallback)}
          onGoogle={() => startOAuth('google', teacherCallback)}
          icon={(
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none"
              stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M2 7l10-4 10 4-10 4z"/>
              <path d="M5 9v6c0 1 3 3 7 3s7-2 7-3V9"/>
            </svg>
          )}
          topMargin={showParent ? 12 : 20}
        />}

        {/* Footer — first-time visitors get pointed to the free assessment */}
        <div style={{
          marginTop: 18, paddingTop: 14, borderTop: '1px solid #EEF2F7',
          fontSize: 13, fontWeight: 500,
          color: '#475569', textAlign: 'center',
        }}>
          {t('signin.firsttime')}
          <a href="#assessment" onClick={onClose} style={{ color: '#6D28D9', fontWeight: 700 }}>
            {t('signin.firsttime.link')}
          </a>
        </div>
      </div>
    </div>
  );
};

window.SigninModal = SigninModal;
