// terms-banner.jsx — teacher-side T&C agreement banner + modal.
//
// Sits at the top of the teacher schedule (rendered by
// InstructorScheduleBanners). Shows a yellow banner whenever the latest
// published terms_versions row's published_at is newer than this user's
// most recent terms_agreements.agreed_at. Click the CTA to open a modal
// that renders the version body (markdown) and offers an "I agree"
// button — clicking it INSERTs into terms_agreements, dismisses the
// banner.
//
// Public:
//   window.useTeacherTermsBanner() — React hook returning
//     { pending: <terms_versions row or null>, agree: () => Promise }
//   <window.TeacherTermsBanner version=... onAgree=... />
//
// We split the hook from the banner so InstructorScheduleBanners can
// decide whether to render the banner without duplicating queries.

(function () {
  function useTeacherTermsBanner() {
    const auth = window.useAuth ? window.useAuth() : { user: null };
    const userId = auth?.user?.id || null;
    const [pending, setPending] = React.useState(null);     // terms_versions row OR null
    const [loaded, setLoaded] = React.useState(false);

    const reload = React.useCallback(async () => {
      if (!userId) { setPending(null); setLoaded(true); return; }
      try {
        // Latest published version (RLS lets the teacher SELECT only rows
        // where published_at is not null — see v62 policy tv_read_published).
        const { data: latest, error: e1 } = await window.supa
          .from('terms_versions')
          .select('id, title, body, published_at')
          .not('published_at', 'is', null)
          .order('published_at', { ascending: false })
          .limit(1)
          .maybeSingle();
        if (e1) { console.warn('[terms] latest version load:', e1.message); setPending(null); setLoaded(true); return; }
        if (!latest) { setPending(null); setLoaded(true); return; }

        // Has the current user already agreed to this version?
        const { data: ag, error: e2 } = await window.supa
          .from('terms_agreements')
          .select('id, agreed_at')
          .eq('user_id', userId)
          .eq('version_id', latest.id)
          .maybeSingle();
        if (e2) { console.warn('[terms] agreement load:', e2.message); setPending(latest); setLoaded(true); return; }

        // Pending if there's no agreement OR the version was republished
        // (impossible today since published rows are immutable, but the
        // banner-visibility rule is "published_at > latest agreed_at for
        // this version", which collapses to "no agreement").
        setPending(ag ? null : latest);
        setLoaded(true);
      } catch (e) {
        console.warn('[terms] reload error:', e.message);
        setPending(null);
        setLoaded(true);
      }
    }, [userId]);

    React.useEffect(() => { reload(); }, [reload]);

    const agree = React.useCallback(async () => {
      if (!userId || !pending) return;
      const { error } = await window.supa
        .from('terms_agreements')
        .insert({ user_id: userId, version_id: pending.id });
      if (error) {
        // 23505 = duplicate (already agreed in another tab) — just refresh.
        if (error.code !== '23505') throw new Error(error.message);
      }
      await reload();
    }, [userId, pending, reload]);

    return { pending, loaded, agree, reload };
  }

  // ── Banner only (rendered inline in the schedule) ───────────────────
  // Yellow/amber strip with a CTA that opens the modal.
  const TeacherTermsBanner = ({ pending, onOpen }) => {
    if (!pending) return null;
    return (
      <div style={{
        background:'oklch(96% 0.07 80)',
        borderBottom:'1px solid oklch(86% 0.08 80)',
        color:'oklch(34% 0.14 75)',
        padding:'12px 24px', display:'flex', alignItems:'center', gap:14, flexWrap:'wrap',
        fontFamily:"'Plus Jakarta Sans', sans-serif",
      }}>
        <span style={{ fontSize:18 }} role="img" aria-label="warning">⚠️</span>
        <div style={{ flex:1, minWidth:200 }}>
          <div style={{ fontSize:13, fontWeight:700 }}>
            Please agree to the updated terms and services to avoid discontinuation.
          </div>
          <div style={{ fontSize:12, opacity:0.85, marginTop:2 }}>
            {pending.title}
          </div>
        </div>
        <button onClick={onOpen}
          style={{
            background:'#fff', color:'oklch(34% 0.14 75)', border:'1px solid oklch(80% 0.1 75)',
            borderRadius:8, padding:'8px 16px', fontSize:13, fontWeight:700, cursor:'pointer',
            fontFamily:"'Plus Jakarta Sans', sans-serif", whiteSpace:'nowrap',
          }}>
          Read &amp; Agree
        </button>
      </div>
    );
  };

  // ── Full-screen modal that renders the body + I-agree button ────────
  const TeacherTermsModal = ({ pending, onAgree, onClose }) => {
    const [busy, setBusy] = React.useState(false);
    const [err,  setErr]  = React.useState('');
    if (!pending) return null;

    const submit = async () => {
      setBusy(true); setErr('');
      try {
        await onAgree();
        onClose && onClose();
      } catch (e) {
        setErr(e.message || 'Could not record your agreement.');
      } finally { setBusy(false); }
    };

    return (
      <div onClick={onClose} style={{
        position:'fixed', inset:0, background:'rgba(10,12,24,0.55)',
        display:'flex', alignItems:'center', justifyContent:'center',
        zIndex:9000, padding:'20px', fontFamily:"'Plus Jakarta Sans', sans-serif",
      }}>
        <div onClick={e => e.stopPropagation()} style={{
          width:680, maxWidth:'100%', maxHeight:'90vh',
          background:'#fff', borderRadius:14, overflow:'hidden',
          display:'flex', flexDirection:'column', boxShadow:'0 20px 60px rgba(0,0,0,0.3)',
        }}>
          <div style={{ padding:'18px 24px', borderBottom:'1px solid oklch(91% 0.01 265)' }}>
            <div style={{ fontSize:11, fontWeight:700, color:'oklch(72% 0.17 80)', textTransform:'uppercase', letterSpacing:'0.1em', marginBottom:4 }}>
              Updated terms
            </div>
            <div style={{ fontSize:20, fontWeight:700, color:'oklch(18% 0.03 265)' }}>{pending.title}</div>
          </div>
          <div
            style={{ flex:1, overflowY:'auto', padding:'22px 28px', fontSize:14, color:'oklch(22% 0.06 265)', lineHeight:1.65 }}
            dangerouslySetInnerHTML={{ __html: window.renderTermsMarkdown(pending.body || '') }}
          />
          {err && <div style={{ margin:'0 24px 12px', padding:'9px 12px', background:'oklch(95% 0.06 25)', color:'oklch(40% 0.15 25)', borderRadius:8, fontSize:13 }}>{err}</div>}
          <div style={{ padding:'14px 24px', borderTop:'1px solid oklch(91% 0.01 265)', display:'flex', justifyContent:'flex-end', gap:10 }}>
            <button onClick={onClose} disabled={busy}
              style={{ background:'oklch(96% 0.01 265)', border:'none', borderRadius:9, padding:'10px 18px', fontWeight:600, fontSize:13, color:'oklch(56% 0.04 265)', cursor: busy ? 'wait' : 'pointer' }}>
              Not now
            </button>
            <button onClick={submit} disabled={busy}
              style={{ background:'oklch(22% 0.06 265)', color:'#fff', border:'none', borderRadius:9, padding:'10px 22px', fontWeight:700, fontSize:13, cursor: busy ? 'wait' : 'pointer', opacity: busy ? 0.7 : 1 }}>
              {busy ? 'Saving…' : 'I agree'}
            </button>
          </div>
        </div>
      </div>
    );
  };

  window.useTeacherTermsBanner = useTeacherTermsBanner;
  window.TeacherTermsBanner = TeacherTermsBanner;
  window.TeacherTermsModal  = TeacherTermsModal;
})();
