// admin-terms.jsx — Admin panel for the Terms & Conditions agreement system.
//
// Three views in one component:
//   1. List of every T&C version (most recent first) with "X / Y teachers
//      agreed". Each row has Edit (drafts only) and a click-to-drill-down.
//   2. Create / Edit modal — title input + markdown body textarea + live
//      preview. Save-as-draft vs Publish. Once published, the row is
//      immutable (v62 trigger enforces this).
//   3. Drill-down — for a published version, list which teachers agreed
//      and which didn't.
//
// Data flows via window.ADMIN_DATA.* helpers (see data-terms.js). RLS in
// the database does the real gatekeeping.
//
// Public: window.AdminTerms.

const AT_NAVY   = 'oklch(22% 0.06 265)';
const AT_GOLD   = 'oklch(72% 0.17 80)';
const AT_BORDER = 'oklch(91% 0.01 265)';
const AT_MUTED  = 'oklch(56% 0.04 265)';
const AT_INK    = 'oklch(18% 0.03 265)';

const ATCard = ({ children, style }) => (
  <div style={{ background:'#fff', borderRadius:14, border:`1px solid ${AT_BORDER}`, padding:'22px 26px', marginBottom:18, boxShadow:'0 2px 10px oklch(18% 0.06 265 / 0.05)', ...style }}>
    {children}
  </div>
);

const ATModalEditor = ({ initial, isPublished, onClose, onSaveDraft, onPublish, busy, err }) => {
  // For published versions the modal shows the snapshot but ALL inputs
  // are read-only. The v62 trigger blocks edits anyway, but the UI
  // shouldn't tempt the admin into trying.
  const [title, setTitle] = React.useState(initial?.title || '');
  const [body,  setBody]  = React.useState(initial?.body  || '');
  const readOnly = isPublished;

  const fld = { width:'100%', padding:'10px 12px', borderRadius:8, border:`1.5px solid ${AT_BORDER}`, fontSize:13, fontFamily:"'Plus Jakarta Sans', sans-serif", color:AT_INK, background:readOnly?'oklch(98% 0.005 265)':'#fff', outline:'none', boxSizing:'border-box' };
  const lbl = { display:'block', fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:AT_MUTED, marginBottom:5 };
  const previewBox = { padding:'14px 16px', borderRadius:8, border:`1.5px solid ${AT_BORDER}`, background:'oklch(98% 0.005 265)', fontSize:13, color:AT_INK, minHeight:240, overflow:'auto', boxSizing:'border-box' };

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(10,12,24,0.45)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:9000, padding:'20px' }}>
      <div onClick={e => e.stopPropagation()} style={{ width:880, maxWidth:'100%', maxHeight:'90vh', background:'#fff', borderRadius:14, overflow:'hidden', display:'flex', flexDirection:'column', fontFamily:"'Plus Jakarta Sans', sans-serif", boxShadow:'0 20px 60px rgba(0,0,0,0.3)' }}>
        <div style={{ padding:'18px 24px', borderBottom:`1px solid ${AT_BORDER}`, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <div>
            <div style={{ fontSize:11, fontWeight:700, color:AT_GOLD, textTransform:'uppercase', letterSpacing:'0.1em', marginBottom:3 }}>
              {isPublished ? 'Published terms version' : (initial?.id ? 'Edit draft' : 'New terms version')}
            </div>
            <div style={{ fontSize:18, fontWeight:700, color:AT_INK }}>{title || (readOnly ? '—' : 'Untitled')}</div>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ background:'none', border:'none', fontSize:22, color:AT_MUTED, cursor:'pointer' }}>×</button>
        </div>

        <div style={{ flex:1, overflow:'auto', padding:'22px 24px' }}>
          {isPublished && (
            <div style={{ marginBottom:16, padding:'10px 14px', background:'oklch(96% 0.05 80)', border:`1px solid ${AT_GOLD}`, borderRadius:10, fontSize:12, color:'oklch(36% 0.13 80)' }}>
              This version was published on {new Date(initial.published_at).toLocaleString()} and is now immutable. Create a new version to make changes.
            </div>
          )}

          <div style={{ marginBottom:14 }}>
            <label style={lbl}>Title</label>
            <input type="text" value={title} onChange={e => setTitle(e.target.value)} disabled={readOnly}
              placeholder="e.g., Mastery Teacher Terms, October 2026"
              style={fld} />
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            <div>
              <label style={lbl}>Body (markdown)</label>
              <textarea value={body} onChange={e => setBody(e.target.value)} disabled={readOnly} rows={14}
                placeholder={`# Section heading\n\nA paragraph.\n\n- A bullet\n- Another bullet\n\n**bold** and *italic*`}
                style={{ ...fld, minHeight:260, resize:'vertical', lineHeight:1.55, fontFamily:'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize:12.5 }} />
              <div style={{ marginTop:6, fontSize:11, color:AT_MUTED }}>
                Markdown supported: # / ## / ### headings, **bold**, *italic*, lists, `code`. No HTML, no links.
              </div>
            </div>
            <div>
              <label style={lbl}>Live preview</label>
              <div style={previewBox} dangerouslySetInnerHTML={{ __html: window.renderTermsMarkdown(body || '') }} />
            </div>
          </div>

          {err && <div style={{ marginTop:14, padding:'9px 12px', background:'oklch(95% 0.06 25)', color:'oklch(40% 0.15 25)', borderRadius:8, fontSize:13 }}>{err}</div>}
        </div>

        {!readOnly && (
          <div style={{ padding:'14px 24px', borderTop:`1px solid ${AT_BORDER}`, display:'flex', gap:10, justifyContent:'flex-end' }}>
            <button onClick={onClose} disabled={busy}
              style={{ background:'oklch(96% 0.01 265)', border:'none', borderRadius:9, padding:'10px 18px', fontWeight:600, fontSize:13, color:AT_MUTED, cursor:'pointer' }}>
              Cancel
            </button>
            <button onClick={() => onSaveDraft({ title, body })} disabled={busy || !title.trim() || !body.trim()}
              style={{ background:'#fff', color:AT_NAVY, border:`1.5px solid ${AT_BORDER}`, borderRadius:9, padding:'10px 18px', fontWeight:600, fontSize:13, cursor: busy ? 'wait' : 'pointer', opacity: (!title.trim() || !body.trim()) ? 0.55 : 1 }}>
              {busy ? 'Saving…' : (initial?.id ? 'Save draft' : 'Save as draft')}
            </button>
            <button onClick={() => {
                if (!confirm('Publish this version? Every teacher whose latest agreement predates now will see the banner until they accept. Once published the body is frozen.')) return;
                onPublish({ title, body });
              }}
              disabled={busy || !title.trim() || !body.trim()}
              style={{ background:AT_NAVY, color:'#fff', border:'none', borderRadius:9, padding:'10px 22px', fontWeight:700, fontSize:13, cursor: busy ? 'wait' : 'pointer', opacity: (!title.trim() || !body.trim()) ? 0.55 : 1 }}>
              {busy ? 'Publishing…' : 'Publish now'}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

const ATDrillDown = ({ version, summary, onClose }) => {
  const teachers = Array.from(summary.teachersByUserId.values())
    .sort((a, b) => (a.full_name || '').localeCompare(b.full_name || ''));
  const agreed = summary.agreementsByVersionId.get(version.id) || new Map();

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(10,12,24,0.45)', display:'flex', justifyContent:'flex-end', zIndex:9000 }}>
      <div onClick={e => e.stopPropagation()} style={{ width:520, maxWidth:'100%', height:'100%', background:'oklch(98% 0.008 60)', overflowY:'auto', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        <div style={{ position:'sticky', top:0, background:'#fff', borderBottom:`1px solid ${AT_BORDER}`, padding:'16px 24px', display:'flex', justifyContent:'space-between', alignItems:'center', zIndex:5 }}>
          <div>
            <div style={{ fontSize:11, fontWeight:700, color:AT_GOLD, textTransform:'uppercase', letterSpacing:'0.1em', marginBottom:3 }}>Agreements</div>
            <div style={{ fontSize:18, fontWeight:700, color:AT_INK }}>{version.title}</div>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ background:'none', border:'none', fontSize:22, color:AT_MUTED, cursor:'pointer' }}>×</button>
        </div>
        <div style={{ padding:'18px 24px' }}>
          <div style={{ fontSize:13, color:AT_MUTED, marginBottom:14 }}>
            {agreed.size} of {teachers.length} teacher{teachers.length === 1 ? '' : 's'} agreed.
          </div>
          <div style={{ background:'#fff', borderRadius:10, border:`1px solid ${AT_BORDER}`, overflow:'hidden' }}>
            {teachers.length === 0 ? (
              <div style={{ padding:'18px', textAlign:'center', color:AT_MUTED, fontSize:13 }}>No teachers in this org yet.</div>
            ) : teachers.map((t, i) => {
              const when = agreed.get(t.user_id);
              return (
                <div key={t.user_id} style={{ display:'flex', alignItems:'center', gap:12, padding:'11px 14px', borderTop: i === 0 ? 'none' : `1px solid ${AT_BORDER}` }}>
                  <span style={{ width:8, height:8, borderRadius:'50%', background: when ? 'oklch(60% 0.18 150)' : 'oklch(72% 0.02 265)', flexShrink:0 }} />
                  <span style={{ flex:1, fontSize:13, color:AT_INK }}>{t.full_name || '—'}</span>
                  <span style={{ fontSize:11, color:AT_MUTED }}>
                    {when ? new Date(when).toLocaleDateString() : 'not yet'}
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};

const AdminTerms = () => {
  const [versions, setVersions] = React.useState(null);
  const [summary,  setSummary]  = React.useState(null);  // { totalTeachers, teachersByUserId, agreementsByVersionId }
  const [editing,  setEditing]  = React.useState(null);  // { id, title, body, published_at } | { _new: true } | null
  const [viewing,  setViewing]  = React.useState(null);  // a version row
  const [busy,     setBusy]     = React.useState(false);
  const [err,      setErr]      = React.useState('');

  const reload = React.useCallback(async () => {
    setErr('');
    try {
      const [v, s] = await Promise.all([
        window.ADMIN_DATA.loadTermsVersions(),
        window.ADMIN_DATA.loadTermsAgreementsSummary(),
      ]);
      setVersions(v);
      setSummary(s);
    } catch (e) {
      setErr(e.message || 'Could not load Terms.');
    }
  }, []);

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

  const onSaveDraft = async ({ title, body }) => {
    setBusy(true); setErr('');
    try {
      if (editing._new) {
        await window.ADMIN_DATA.createTermsDraft({ title, body });
      } else {
        await window.ADMIN_DATA.updateTermsDraft(editing.id, { title, body });
      }
      setEditing(null);
      await reload();
    } catch (e) { setErr(e.message || 'Could not save.'); }
    finally { setBusy(false); }
  };

  const onPublish = async ({ title, body }) => {
    setBusy(true); setErr('');
    try {
      let row;
      if (editing._new) {
        row = await window.ADMIN_DATA.createTermsDraft({ title, body });
      } else {
        row = await window.ADMIN_DATA.updateTermsDraft(editing.id, { title, body });
      }
      await window.ADMIN_DATA.publishTermsVersion(row.id);
      setEditing(null);
      await reload();
    } catch (e) { setErr(e.message || 'Could not publish.'); }
    finally { setBusy(false); }
  };

  const onDeleteDraft = async (v) => {
    if (!confirm('Delete this draft? This cannot be undone.')) return;
    setBusy(true); setErr('');
    try {
      await window.ADMIN_DATA.deleteTermsDraft(v.id);
      await reload();
    } catch (e) { setErr(e.message || 'Could not delete.'); }
    finally { setBusy(false); }
  };

  if (!versions || !summary) {
    return <div style={{ padding:'24px', color:AT_MUTED, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Loading…</div>;
  }

  return (
    <div style={{ maxWidth:920, margin:'0 auto', paddingBottom:90, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
      <ATCard>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:6 }}>
          <div>
            <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:22, fontWeight:600, color:AT_INK }}>Terms &amp; Conditions</div>
            <div style={{ fontSize:13, color:AT_MUTED, marginTop:3 }}>
              Publish a new version to ask every teacher to re-agree. Drafts stay private.
            </div>
          </div>
          <button onClick={() => setEditing({ _new: true })}
            style={{ background:AT_NAVY, color:'#fff', border:'none', borderRadius:10, padding:'10px 18px', fontWeight:700, fontSize:13, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
            + New version
          </button>
        </div>
      </ATCard>

      {err && <div style={{ padding:'12px 14px', background:'oklch(95% 0.06 25)', color:'oklch(40% 0.15 25)', borderRadius:8, fontSize:13, marginBottom:14 }}>{err}</div>}

      <ATCard>
        {versions.length === 0 ? (
          <div style={{ padding:'30px 0', textAlign:'center', color:AT_MUTED, fontSize:14 }}>
            No T&amp;C versions yet. Click <strong>+ New version</strong> to create your first.
          </div>
        ) : (
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {versions.map(v => {
              const isPublished = !!v.published_at;
              const agreed = summary.agreementsByVersionId.get(v.id);
              const agreedCount = agreed ? agreed.size : 0;
              return (
                <div key={v.id} style={{
                  display:'flex', alignItems:'center', gap:14,
                  padding:'12px 16px', background:'oklch(98% 0.005 265)', border:`1px solid ${AT_BORDER}`, borderRadius:10,
                }}>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <span style={{ fontSize:14, fontWeight:700, color:AT_INK }}>{v.title}</span>
                      {isPublished ? (
                        <span style={{ fontSize:10, fontWeight:700, padding:'3px 8px', borderRadius:999, background:'oklch(94% 0.07 150)', color:'oklch(30% 0.13 150)', textTransform:'uppercase', letterSpacing:'0.05em' }}>
                          Published
                        </span>
                      ) : (
                        <span style={{ fontSize:10, fontWeight:700, padding:'3px 8px', borderRadius:999, background:'oklch(95% 0.005 265)', color:AT_MUTED, textTransform:'uppercase', letterSpacing:'0.05em' }}>
                          Draft
                        </span>
                      )}
                    </div>
                    <div style={{ fontSize:11, color:AT_MUTED, marginTop:3 }}>
                      {isPublished ? (
                        <>Published {new Date(v.published_at).toLocaleString()} · {agreedCount} / {summary.totalTeachers} teacher{summary.totalTeachers === 1 ? '' : 's'} agreed</>
                      ) : (
                        <>Created {new Date(v.created_at).toLocaleString()}</>
                      )}
                    </div>
                  </div>
                  {isPublished ? (
                    <>
                      <button onClick={() => setViewing(v)} disabled={busy}
                        style={{ background:'#fff', border:`1px solid ${AT_BORDER}`, borderRadius:8, padding:'7px 12px', fontSize:12, fontWeight:600, color:AT_NAVY, cursor:'pointer' }}>
                        Who agreed?
                      </button>
                      <button onClick={() => setEditing(v)} disabled={busy}
                        style={{ background:'#fff', border:`1px solid ${AT_BORDER}`, borderRadius:8, padding:'7px 12px', fontSize:12, fontWeight:600, color:AT_MUTED, cursor:'pointer' }}>
                        View
                      </button>
                    </>
                  ) : (
                    <>
                      <button onClick={() => setEditing(v)} disabled={busy}
                        style={{ background:'#fff', border:`1px solid ${AT_BORDER}`, borderRadius:8, padding:'7px 12px', fontSize:12, fontWeight:600, color:AT_NAVY, cursor:'pointer' }}>
                        Edit
                      </button>
                      <button onClick={() => onDeleteDraft(v)} disabled={busy} title="Delete draft"
                        style={{ background:'oklch(96% 0.04 25)', color:'oklch(40% 0.18 25)', border:'1px solid oklch(88% 0.05 25)', borderRadius:8, padding:'7px 10px', fontSize:12, fontWeight:600, cursor:'pointer' }}>
                        Delete
                      </button>
                    </>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </ATCard>

      {editing && (
        <ATModalEditor
          initial={editing._new ? null : editing}
          isPublished={!!editing.published_at}
          onClose={() => { setEditing(null); setErr(''); }}
          onSaveDraft={onSaveDraft}
          onPublish={onPublish}
          busy={busy}
          err={err}
        />
      )}

      {viewing && (
        <ATDrillDown version={viewing} summary={summary} onClose={() => setViewing(null)} />
      )}
    </div>
  );
};

window.AdminTerms = AdminTerms;
