// admin-silent-mode.jsx
//
// Joe's directive 2026-05-24: a one-click "Silent Mode" toggle in the
// admin top bar that flips a global flag in public.admin_settings.
//
// REDEFINED 2026-06-01 (v134): Silent Mode now gates exactly ONE email — the
// weekly "update your availability" nudge to teachers
// (public.send_teacher_availability_reminders, which self-checks the flag).
// Everything else — lesson reminders, booking/application/verification emails,
// the missing-email admin alert — is UNAFFECTED by Silent Mode. (The central
// gate that used to live in public.send_booking_email was removed in v134.)
//
// Exposes two window components:
//   window.AdminSilentModeToggle — the button. Mount in the top bar.
//   window.AdminSilentModeBanner — always-visible red bar across all tabs
//                                   when silent mode is on. Mount above
//                                   the tab-content area.
//
// Both components read public.admin_settings via the admin-only SELECT
// policy added in v83. Writes go through the SECURITY DEFINER RPC
// public.admin_set_silent_mode(p_enabled boolean).

const SilentModeData = {
  // Single source of truth so the toggle + banner don't double-fetch.
  // Listeners are notified whenever any toggle/refresh fires.
  // A single shared 15s poll is started on the first subscribe and cleared
  // on the last unsubscribe so the table isn't polled once per mounted
  // component.
  state: { loaded: false, enabled: false, setAt: null, setBy: '' },
  listeners: new Set(),
  _pollTimer: null,
  subscribe(fn) {
    this.listeners.add(fn);
    if (!this._pollTimer) {
      this._pollTimer = setInterval(() => { this.refresh(); }, 15000);
    }
    return () => {
      this.listeners.delete(fn);
      if (this.listeners.size === 0 && this._pollTimer) {
        clearInterval(this._pollTimer);
        this._pollTimer = null;
      }
    };
  },
  notify() {
    for (const fn of Array.from(this.listeners)) {
      try { fn(this.state); } catch (e) { /* listener errors must not break each other */ }
    }
  },
  async refresh() {
    try {
      const { data, error } = await window.supa
        .from('admin_settings')
        .select('silent_mode, silent_mode_set_at, silent_mode_set_by')
        .eq('id', 1)
        .maybeSingle();
      if (error) throw error;
      this.state = {
        loaded: true,
        enabled: !!data?.silent_mode,
        setAt:   data?.silent_mode_set_at || null,
        setBy:   data?.silent_mode_set_by || '',
      };
      this.notify();
    } catch (e) {
      // Non-admin sessions get RLS-blocked here; that's fine — they
      // won't render this component. Just stop loading and keep
      // enabled=false so the banner stays hidden.
      this.state = { ...this.state, loaded: true };
      this.notify();
    }
  },
  async setEnabled(next) {
    const { error } = await window.supa.rpc('admin_set_silent_mode', { p_enabled: !!next });
    if (error) throw error;
    await this.refresh();
  },
};

// Expose for any other admin surface that wants to read or react.
window.SilentModeData = SilentModeData;

const useSilentModeState = () => {
  const [state, setState] = React.useState(SilentModeData.state);
  React.useEffect(() => {
    const unsub = SilentModeData.subscribe(setState);
    if (!SilentModeData.state.loaded) SilentModeData.refresh();
    return unsub;
  }, []);
  return state;
};

const AdminSilentModeToggle = () => {
  const { enabled, setAt, setBy } = useSilentModeState();
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const onClick = async () => {
    if (busy) return;
    setErr('');
    const next = !enabled;
    if (next) {
      const ok = window.confirm(
        'Turn ON Silent Mode?\n\n' +
        'While ON, the weekly "update your availability" nudge to teachers ' +
        'is paused.\n\n' +
        'Nothing else is affected — lesson reminders, booking emails, and ' +
        'application emails all keep sending normally.\n\n' +
        'You can turn it off any time from this same button.'
      );
      if (!ok) return;
    }
    setBusy(true);
    try {
      await SilentModeData.setEnabled(next);
    } catch (e) {
      setErr(e?.message || String(e));
    } finally {
      setBusy(false);
    }
  };

  const title = enabled
    ? `Silent Mode is ON${setAt ? ' since ' + new Date(setAt).toLocaleString() : ''}${setBy ? ' (by ' + setBy + ')' : ''}.\nClick to turn OFF.`
    : 'Click to turn ON Silent Mode (pauses only the weekly availability nudge to teachers — every other email keeps sending).';

  return (
    <button
      onClick={onClick}
      disabled={busy}
      title={title}
      aria-pressed={enabled}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        background: enabled ? 'oklch(48% 0.20 25)' : 'oklch(96% 0.01 265)',
        color: enabled ? '#fff' : 'oklch(42% 0.04 265)',
        border: '1px solid ' + (enabled ? 'oklch(42% 0.20 25)' : 'oklch(88% 0.02 265)'),
        borderRadius: 9,
        padding: '8px 14px',
        fontSize: 12, fontWeight: 600,
        cursor: busy ? 'wait' : 'pointer',
        fontFamily: "'Plus Jakarta Sans', sans-serif",
        whiteSpace: 'nowrap', flexShrink: 0,
        opacity: busy ? 0.65 : 1,
        transition: 'background 0.14s, color 0.14s, border 0.14s',
      }}
    >
      <span style={{
        display: 'inline-block', width: 8, height: 8, borderRadius: '50%',
        background: enabled ? '#fff' : 'oklch(60% 0.18 145)',
        boxShadow: enabled ? '0 0 0 2px rgba(255,255,255,0.35)' : 'none',
        flexShrink: 0,
      }} />
      Silent Mode{enabled ? ' · ON' : ''}
      {err && <span style={{ marginLeft: 6, color: enabled ? '#fff' : 'oklch(45% 0.18 25)', fontWeight: 500 }}>· {err.slice(0, 80)}</span>}
    </button>
  );
};

const AdminSilentModeBanner = () => {
  const { enabled, setAt, setBy } = useSilentModeState();
  if (!enabled) return null;
  return (
    <div
      role="status"
      style={{
        background: 'oklch(48% 0.20 25)',
        color: '#fff',
        padding: '9px 18px',
        fontSize: 12.5, fontWeight: 600,
        fontFamily: "'Plus Jakarta Sans', sans-serif",
        borderBottom: '1px solid oklch(40% 0.20 25)',
        display: 'flex', alignItems: 'center', gap: 10,
        flexShrink: 0, flexWrap: 'wrap',
      }}
    >
      <span style={{
        display: 'inline-block', width: 9, height: 9, borderRadius: '50%',
        background: '#fff', boxShadow: '0 0 0 2px rgba(255,255,255,0.35)', flexShrink: 0,
      }} />
      <span>
        Silent Mode is ON — the weekly "update your availability" nudge to
        teachers is paused. Everything else (lesson reminders, booking and
        application emails) is unaffected.
      </span>
      {setAt && (
        <span style={{ marginLeft: 'auto', fontWeight: 400, opacity: 0.85 }}>
          since {new Date(setAt).toLocaleString()}{setBy ? ' by ' + setBy : ''}
        </span>
      )}
    </div>
  );
};

Object.assign(window, { AdminSilentModeToggle, AdminSilentModeBanner });
