// admin-reminders-availability.jsx — "Weekly nudge" tab of the reminder editor.
//
// Admin control for the weekly teacher availability reminder: an on/off
// toggle, an editable schedule (day + hour + timezone), and an editable
// subject + body using the same rich editor / placeholder chips / live
// preview as the Student & Teacher reminder templates. Backed by the
// weekly_availability_reminder_settings singleton (supabase/v119) via
// window.ADMIN_DATA.availabilityReminder.
//
// Mounted by admin-reminders.jsx only while the "Weekly nudge" tab is active.

const AdminRemindersAvailability = () => {
  const AVAIL          = window.ADMIN_DATA.availabilityReminder;
  const PLACEHOLDERS   = window.AR_AVAIL_PLACEHOLDERS;
  const DEFAULT_TPL    = window.AR_AVAIL_DEFAULT_TEMPLATE;
  const DOW_OPTIONS    = window.AR_DOW_OPTIONS;
  const HOUR_OPTIONS   = window.AR_HOUR_OPTIONS;
  const TZ_OPTIONS     = window.AR_SEND_TZ_OPTIONS;
  const fillPreview    = window.arFillPlaceholders;

  const [settings, setSettings] = React.useState(null); // null = loading
  const [silent, setSilent]     = React.useState(false);
  const [busy, setBusy]         = React.useState(false);
  const [err, setErr]           = React.useState('');
  const [saveOk, setSaveOk]     = React.useState('');
  const [testBusy, setTestBusy] = React.useState(false);
  const [testMsg, setTestMsg]   = React.useState('');
  const [dirty, setDirty]       = React.useState(false);

  const subjectRef = React.useRef(null);
  const bodyRef    = React.useRef(null);
  const lastFocused = React.useRef('body'); // 'subject' | 'body'

  React.useEffect(() => {
    let alive = true;
    (async () => {
      try {
        const [s, sm] = await Promise.all([
          AVAIL.get(),
          window.supa.from('admin_settings').select('silent_mode').eq('id', 1).single(),
        ]);
        if (!alive) return;
        setSettings(s);
        setSilent(!!(sm.data && sm.data.silent_mode));
      } catch (e) {
        if (alive) { setErr(e.message || 'Failed to load'); setSettings({}); }
      }
    })();
    return () => { alive = false; };
  }, []);

  React.useEffect(() => { window.arInstallPillStyles && window.arInstallPillStyles(); }, []);

  const patch = (p) => { setSettings(s => ({ ...s, ...p })); setDirty(true); setSaveOk(''); };

  const insertPlaceholder = (token) => {
    const el = lastFocused.current === 'subject' ? subjectRef.current : bodyRef.current;
    window.arInsertPillAtSelection(el, token);
  };

  const save = async () => {
    setBusy(true); setErr(''); setSaveOk('');
    try {
      await AVAIL.save(settings);
      setDirty(false);
      setSaveOk('Saved');
      setTimeout(() => setSaveOk(''), 2400);
    } catch (e) {
      setErr(e.message || 'Save failed');
    } finally { setBusy(false); }
  };

  const sendTest = async () => {
    setTestBusy(true); setTestMsg(''); setErr('');
    try {
      await AVAIL.sendTest();
      setTestMsg('Test email sent to your admin address. Check your inbox.');
    } catch (e) {
      setErr(e.message || 'Send test failed');
    } finally {
      setTestBusy(false);
      setTimeout(() => setTestMsg(''), 10000);
    }
  };

  const resetToDefault = () => {
    if (!window.confirm('Reset the subject + body to the default copy?')) return;
    patch({ subject: DEFAULT_TPL.subject, body: DEFAULT_TPL.body });
  };

  // ── Styles (consistent with admin-reminders.jsx) ──────────────────
  const card = { background:'#fff', borderRadius:14, border:'1px solid oklch(91% 0.01 265)', padding:'22px 26px', marginBottom:18, boxShadow:'0 2px 10px oklch(18% 0.06 265 / 0.05)' };
  const h2   = { fontFamily:"'Cormorant Garamond', serif", fontSize:20, fontWeight:600, color:'oklch(18% 0.03 265)', marginBottom:6 };
  const lbl  = { display:'block', fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(56% 0.04 265)', marginBottom:5 };
  const fld  = { padding:'9px 11px', borderRadius:8, border:'1.5px solid oklch(88% 0.015 265)', fontSize:13, fontFamily:"'Plus Jakarta Sans', sans-serif", color:'oklch(22% 0.06 265)', background:'#fff', outline:'none', boxSizing:'border-box' };
  const chipBtn = { fontSize:11, fontWeight:600, padding:'4px 9px', borderRadius:999, border:'1px solid oklch(86% 0.02 265)', background:'oklch(98% 0.005 265)', color:'oklch(36% 0.05 265)', cursor:'pointer', fontFamily:'ui-monospace, SFMono-Regular, Menlo, monospace' };
  const previewBox = { padding:'12px 14px', borderRadius:8, border:'1.5px solid oklch(92% 0.01 265)', background:'oklch(98% 0.005 265)', fontSize:13, lineHeight:1.55, color:'oklch(22% 0.06 265)', minHeight:200, overflow:'auto', boxSizing:'border-box' };

  if (settings === null) {
    return <div style={card}><div style={{ fontSize:13, color:'oklch(60% 0.03 265)' }}>Loading…</div></div>;
  }

  const enabled = settings.enabled !== false;

  // Toggle switch
  const Switch = ({ on, onClick }) => (
    <div onClick={onClick} role="switch" aria-checked={on} style={{
      width:46, height:26, borderRadius:999, cursor:'pointer', flexShrink:0,
      background: on ? 'oklch(58% 0.13 150)' : 'oklch(85% 0.02 265)',
      transition:'background 160ms', position:'relative',
    }}>
      <div style={{ position:'absolute', top:3, left: on ? 23 : 3, width:20, height:20, borderRadius:999, background:'#fff', transition:'left 160ms', boxShadow:'0 1px 3px rgba(0,0,0,0.2)' }} />
    </div>
  );

  return (
    <div style={card}>
      <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between' }}>
        <div style={h2}>Weekly availability reminder</div>
        <button type="button" onClick={resetToDefault}
          style={{ fontSize:11, fontWeight:600, color:'oklch(50% 0.03 265)', background:'transparent', border:'none', cursor:'pointer', textDecoration:'underline', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
          Reset to default
        </button>
      </div>
      <div style={{ fontSize:12, color:'oklch(56% 0.03 265)', marginBottom:18, lineHeight:1.5 }}>
        Emails every active teacher once a week, nudging them to keep their availability up to date.
      </div>

      {/* Enable toggle */}
      <div style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px', borderRadius:10, background:'oklch(98% 0.005 265)', border:'1px solid oklch(92% 0.01 265)', marginBottom:14 }}>
        <Switch on={enabled} onClick={() => patch({ enabled: !enabled })} />
        <div style={{ flex:1 }}>
          <div style={{ fontSize:13, fontWeight:600, color:'oklch(24% 0.05 265)' }}>{enabled ? 'On' : 'Off'} — weekly reminder is {enabled ? 'active' : 'paused'}</div>
          <div style={{ fontSize:12, color:'oklch(56% 0.03 265)' }}>Turn off to stop sending without losing your message.</div>
        </div>
      </div>

      {enabled && silent && (
        <div style={{ fontSize:12.5, color:'oklch(40% 0.12 70)', background:'oklch(97% 0.05 80)', border:'1px solid oklch(88% 0.06 80)', borderRadius:8, padding:'10px 12px', marginBottom:14, lineHeight:1.5 }}>
          Heads up: <strong>Silent Mode is on</strong>, so this weekly reminder is paused until you turn it off. Silent Mode pauses only this nudge — every other email keeps sending.
        </div>
      )}

      {/* Schedule */}
      <div style={{ marginBottom:16, opacity: enabled ? 1 : 0.55 }}>
        <label style={lbl}>When to send</label>
        <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap', fontSize:13, color:'oklch(36% 0.04 265)' }}>
          <span>Every</span>
          <select value={settings.send_dow ?? 0} onChange={e => patch({ send_dow: Number(e.target.value) })} style={fld} disabled={!enabled}>
            {DOW_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
          <span>at</span>
          <select value={settings.send_hour ?? 10} onChange={e => patch({ send_hour: Number(e.target.value) })} style={fld} disabled={!enabled}>
            {HOUR_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
          <select value={settings.send_tz || 'America/New_York'} onChange={e => patch({ send_tz: e.target.value })} style={fld} disabled={!enabled}>
            {TZ_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </div>
      </div>

      {/* Subject */}
      <div style={{ marginBottom:14 }}>
        <label style={lbl}>Subject</label>
        <window.ARRichEditor
          editorRef={(el) => { subjectRef.current = el; }}
          value={settings.subject || ''}
          onChange={(html) => patch({ subject: html })}
          onFocus={() => { lastFocused.current = 'subject'; }}
          placeholder="e.g. Quick check: is your availability up to date?"
          singleLine={true}
        />
        <div style={{ marginTop:6, fontSize:11, color:'oklch(56% 0.03 265)' }}>
          Renders as: <span style={{ color:'oklch(22% 0.06 265)' }}>{fillPreview(settings.subject || '')}</span>
        </div>
      </div>

      {/* Placeholder chips */}
      <div style={{ display:'flex', flexWrap:'wrap', gap:6, marginBottom:10 }}>
        <span style={{ fontSize:11, color:'oklch(56% 0.03 265)', marginRight:4, alignSelf:'center' }}>Insert:</span>
        {PLACEHOLDERS.map(p => (
          <button key={p} type="button" onClick={() => insertPlaceholder(p)} style={chipBtn} title={'Insert {' + p + '} at cursor'}>
            {'{' + p + '}'}
          </button>
        ))}
      </div>

      {/* Body + live preview */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:18 }}>
        <div>
          <label style={lbl}>Body</label>
          <window.ARRichEditor
            editorRef={(el) => { bodyRef.current = el; }}
            value={settings.body || ''}
            onChange={(html) => patch({ body: html })}
            onFocus={() => { lastFocused.current = 'body'; }}
            placeholder="Type your reminder message…"
            singleLine={false}
          />
        </div>
        <div>
          <label style={lbl}>Live preview</label>
          <div style={previewBox} dangerouslySetInnerHTML={{ __html: fillPreview(settings.body || '') }} />
        </div>
      </div>

      {err     && <div style={{ fontSize:13, color:'oklch(40% 0.15 25)',  marginBottom:10, padding:'10px 14px', background:'oklch(96% 0.06 25)',  borderRadius:8 }}>{err}</div>}
      {saveOk  && <div style={{ fontSize:13, color:'oklch(28% 0.13 150)', marginBottom:10, fontWeight:600 }}>{saveOk}</div>}
      {testMsg && <div style={{ fontSize:13, color:'oklch(28% 0.13 150)', marginBottom:10, padding:'10px 14px', background:'oklch(96% 0.04 150)', borderRadius:8, lineHeight:1.5 }}>{testMsg}</div>}

      <div style={{ display:'flex', gap:12, alignItems:'center' }}>
        <div style={{ flex:1, fontSize:12, color: dirty ? 'oklch(40% 0.18 25)' : 'oklch(56% 0.03 265)' }}>
          {dirty ? 'You have unsaved changes.' : 'All changes saved.'}
        </div>
        <button onClick={sendTest} disabled={testBusy}
          title="Sends one copy of this email to your admin address so you can preview it."
          style={{ background:'#fff', color:'oklch(22% 0.06 265)', border:'1.5px solid oklch(80% 0.02 265)', borderRadius:10, padding:'11px 16px', fontWeight:600, fontSize:13.5, cursor:testBusy?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity:testBusy?0.7:1 }}>
          {testBusy ? 'Sending…' : 'Send test to me'}
        </button>
        <button onClick={save} disabled={busy || !dirty}
          style={{ background: dirty ? 'oklch(22% 0.06 265)' : 'oklch(70% 0.02 265)', color:'#fff', border:'none', borderRadius:10, padding:'11px 20px', fontWeight:600, fontSize:13.5, cursor:(busy||!dirty)?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity:busy?0.7:1 }}>
          {busy ? 'Saving…' : 'Save changes'}
        </button>
      </div>
    </div>
  );
};

window.AdminRemindersAvailability = AdminRemindersAvailability;
