// src/features/instructor/ui/instructor-dashboard-modals.jsx
//
// First half of the instructor dashboard helper modals. Contains the
// two write-side modals (add lesson, edit availability). The
// read/detail components live in instructor-dashboard-modals-2.jsx.
//
// Public: window.{AddLessonModal, AvailabilityModal}.
// (LessonDetailPopup + TeacherStudentRow are in -modals-2.jsx.)

// ── AddLessonModal ──────────────────────────────────────────────────
const AddLessonModal = ({ assignments, defaultDate, defaultHour, onAdd, onAddSeries, onClose }) => {
  const [studentId, setStudentId] = React.useState(assignments[0]?.studentId || '');
  const [date,      setDate]      = React.useState(defaultDate || localDateStr(new Date()));
  const [hour,      setHour]      = React.useState(defaultHour || 9);
  const [duration,  setDuration]  = React.useState(60);
  const [recurring, setRecurring] = React.useState(false);
  const [infinite,  setInfinite]  = React.useState(false);
  const [weeks,     setWeeks]     = React.useState(4);
  const [notes,     setNotes]     = React.useState('');
  const [busy,      setBusy]      = React.useState(false);
  // Which zone the teacher is THINKING in when typing date+hour. Defaults to
  // the browser's detected zone; the badge below lets the teacher flip it
  // (useful when they're travelling but want to book in their home zone).
  const [tz, setTz] = React.useState(() => window.Calendar.time.detect());

  const submit = async (e) => {
    e.preventDefault();
    if (!studentId) return;
    setBusy(true);
    try {
      // Construct the absolute UTC moment for "date at hour:00" interpreted
      // in the selected zone. Avoid the old `new Date(YYYY-MM-DDTHH:00:00)`
      // path which silently uses browser-local TZ — that was wrong any time
      // the teacher's actual zone differed from their laptop's setting.
      const [yy, mm, dd] = date.split('-').map(Number);
      const scheduledAt = window.Calendar.time.makeDate(yy, mm, dd, Number(hour), 0, tz).toISOString();
      const message = notes || '';
      if (recurring) {
        await onAddSeries({
          studentId, firstAt: scheduledAt, durationMinutes: Number(duration),
          weeks: Number(weeks), message: message.trim() || null,
          infinite: !!infinite,
        });
      } else {
        await onAdd({
          studentId, scheduledAt, durationMinutes: Number(duration),
          message: message.trim() || null,
          paymentMethod: null,
          status: 'confirmed',
        });
      }
      onClose();
    } catch (e2) {
      alert(e2.message || 'Could not add lesson.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(10,12,24,0.35)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:9000 }} onClick={onClose}>
      <div style={{ background:'#fff', borderRadius:16, padding:'24px 22px 22px', width:'min(420px, calc(100vw - 24px))', maxHeight:'92vh', overflowY:'auto', boxShadow:'0 20px 60px rgba(0,0,0,0.18)', fontFamily:"'Plus Jakarta Sans', sans-serif", boxSizing:'border-box' }} onClick={e => e.stopPropagation()}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:8, marginBottom:4 }}>
          <div style={{ fontFamily:"'Cormorant Garamond', serif", fontWeight:700, fontSize:22, color:'oklch(18% 0.03 265)', lineHeight:1.1 }}>Add lesson</div>
          <window.TimezoneBadge compact value={tz} onChange={setTz} />
        </div>
        <div style={{ fontSize:12, color:'oklch(60% 0.03 265)', marginBottom:18 }}>Schedule a one-off or recurring lesson with an assigned student.</div>
        {assignments.length === 0 ? (
          <div>
            <div style={{ fontSize:13, color:'oklch(45% 0.04 265)', lineHeight:1.6, marginBottom:18 }}>
              You don't have any assigned students yet. Your admin will assign students to you — we'll email you the moment they do, and they'll show up here automatically.
            </div>
            <div style={{ display:'flex', gap:10 }}>
              <a href="mailto:hello@themusicmastery.com?subject=Please%20assign%20me%20a%20student"
                 style={{ flex:1, padding:'11px 0', background:'oklch(72% 0.17 80)', border:'none', borderRadius:8, fontSize:13, cursor:'pointer', color:'oklch(18% 0.06 265)', fontWeight:700, fontFamily:"'Plus Jakarta Sans', sans-serif", textAlign:'center', textDecoration:'none' }}>
                Message admin
              </a>
              <button onClick={onClose} style={{ flex:1, padding:'11px 0', background:'oklch(95% 0.01 265)', border:'none', borderRadius:8, fontSize:13, cursor:'pointer', color:'oklch(44% 0.04 265)', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>OK</button>
            </div>
          </div>
        ) : (
          <form onSubmit={submit}>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:16 }}>
              <div style={{ gridColumn:'1/-1' }}>
                <label style={instLabel}>Student</label>
                <select value={studentId} onChange={e => setStudentId(e.target.value)} style={instInput}>
                  {assignments.map(a => <option key={a.studentId} value={a.studentId}>{a.student?.name || 'Unknown'}</option>)}
                </select>
              </div>
              <div>
                <label style={instLabel}>Duration</label>
                <select value={duration} onChange={e => setDuration(Number(e.target.value))} style={instInput}>
                  {[30, 45, 60, 90].map(d => <option key={d} value={d}>{d} min</option>)}
                </select>
              </div>
              <div>
                <label style={instLabel}>Time</label>
                <select value={hour} onChange={e => setHour(Number(e.target.value))} style={instInput}>
                  {INST_HOURS_FULL.map(h => <option key={h} value={h}>{instH(h)}</option>)}
                </select>
              </div>
              <div style={{ gridColumn:'1/-1' }}>
                <label style={instLabel}>Date</label>
                <input type="date" value={date} onChange={e => setDate(e.target.value)} style={instInput} />
              </div>
              <div style={{ gridColumn:'1/-1' }}>
                <label style={instLabel}>Notes</label>
                <input value={notes} onChange={e => setNotes(e.target.value)} placeholder="Optional" style={instInput} />
              </div>
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:recurring?6:18, padding:'8px 10px', background:'oklch(98% 0.005 265)', borderRadius:8, border:'1px dashed oklch(85% 0.02 265)' }}>
              <input type="checkbox" id="iRec" checked={recurring} onChange={e => { const v = e.target.checked; setRecurring(v); if (!v) setInfinite(false); }} style={{ width:14, height:14, accentColor:'oklch(22% 0.06 265)' }} />
              <label htmlFor="iRec" style={{ fontSize:13, color:'oklch(28% 0.05 265)', cursor:'pointer', fontWeight:600 }}>↻ Repeat weekly</label>
            </div>
            {recurring && (
              <>
                <div style={{ display:'flex', alignItems:'center', gap:9, marginBottom:infinite?12:8, paddingLeft:8 }}>
                  <input type="checkbox" id="iRecInf" checked={infinite} onChange={e => setInfinite(e.target.checked)} style={{ width:14, height:14, accentColor:'oklch(34% 0.13 150)' }} />
                  <label htmlFor="iRecInf" style={{ fontSize:13, color:'oklch(28% 0.05 265)', cursor:'pointer', fontWeight:600 }}>∞ Infinite — keep going forever</label>
                </div>
                {!infinite && (
                  <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8, paddingLeft:8, fontSize:13, color:'oklch(40% 0.04 265)' }}>
                    <span>For</span>
                    <input type="number" min={1} max={52} value={weeks} onChange={e => setWeeks(e.target.value)} style={{ width:60, padding:'5px 8px', borderRadius:6, border:'1.5px solid oklch(86% 0.02 265)', fontSize:13, fontFamily:"'Plus Jakarta Sans', sans-serif", textAlign:'center' }} />
                    <span>weeks (creates {weeks} lessons total)</span>
                  </div>
                )}
                {infinite ? (
                  <div style={{ marginBottom:18, padding:'9px 11px', background:'oklch(96% 0.04 150)', border:'1px solid oklch(82% 0.1 150)', borderRadius:7, fontSize:11.5, color:'oklch(34% 0.08 150)', lineHeight:1.5 }}>
                    Creates 104 weekly lessons up-front and tops itself up daily. Cancel any time via the lesson popup → Series.
                  </div>
                ) : (
                  <div style={{ marginBottom:18, padding:'9px 11px', background:'oklch(96% 0.04 80)', border:'1px solid oklch(82% 0.1 80)', borderRadius:7, fontSize:11.5, color:'oklch(35% 0.08 60)', lineHeight:1.5 }}>
                    Don't select this if it's your first lesson with the student — they might want to change the schedule later.
                  </div>
                )}
              </>
            )}
            <div style={{ display:'flex', gap:8 }}>
              <button type="submit" disabled={busy} style={{ flex:1, background:'oklch(22% 0.06 265)', color:'#fff', border:'none', borderRadius:9, padding:'13px 0', fontWeight:600, fontSize:14, cursor:busy?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity:busy?0.72:1, minHeight:44 }}>{busy ? 'Saving…' : 'Add lesson'}</button>
              <button type="button" onClick={onClose} style={{ padding:'13px 18px', background:'oklch(95% 0.01 265)', border:'none', borderRadius:9, fontSize:14, cursor:'pointer', color:'oklch(46% 0.04 265)', fontFamily:"'Plus Jakarta Sans', sans-serif", fontWeight:600, minHeight:44 }}>Cancel</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
};

// ── Availability Modal (uses shared AvailabilityPicker — AM/PM ranges) ──
// initialAvail comes in per-hour cells shape ({0:[8,9,...], ...}). We convert
// up to multi-block on mount and back down to DB rows on save.

// ── AvailabilityModal ───────────────────────────────────────────────
const AvailabilityModal = ({ initialAvail, onSave, onClose }) => {
  // Bootstrap: per-hour cells → multi-block shape
  const cellsToBlocks = (cells) => {
    const out = Object.fromEntries([0,1,2,3,4,5,6].map(i => [i, { enabled:false, blocks:[] }]));
    for (let i = 0; i < 7; i++) {
      const hours = (cells[i] || []).slice().sort((a,b) => a-b);
      if (!hours.length) continue;
      out[i].enabled = true;
      let from = hours[0], prev = hours[0];
      for (let j = 1; j < hours.length; j++) {
        if (hours[j] === prev + 1) { prev = hours[j]; continue; }
        out[i].blocks.push({ from, to: prev + 1 });
        from = hours[j]; prev = hours[j];
      }
      out[i].blocks.push({ from, to: prev + 1 });
    }
    for (let i = 0; i < 7; i++) if (!out[i].blocks.length) out[i].blocks = [{ from:9, to:17 }];
    return out;
  };

  const [avail, setAvail] = React.useState(() => cellsToBlocks(initialAvail));
  const [busy, setBusy]   = React.useState(false);
  const [err,  setErr]    = React.useState('');
  // Timezone is on profiles.timezone (default 'America/New_York'). Load
  // current user's value on mount; save back alongside availability rows
  // when the teacher hits Save. Reminder emails (v10-schema.sql) already
  // format times per-recipient using this column, so updating it here is
  // immediately useful end-to-end.
  //
  // Phase 2 auto-detect: if the user's profile has no timezone yet, or it
  // still matches the schema default 'America/New_York' that nobody has
  // explicitly picked, prefill the dropdown with the browser's detected
  // zone via Intl. The user can still change it before saving.
  const [tz, setTz] = React.useState(() => window.Calendar.time.detect());
  React.useEffect(() => {
    (async () => {
      try {
        const { data: u } = await window.supa.auth.getUser();
        const uid = u?.user?.id;
        if (!uid) return;
        const { data: row } = await window.supa.from('profiles').select('timezone').eq('id', uid).maybeSingle();
        if (row?.timezone) setTz(row.timezone);
      } catch (e) { /* keep detected default */ }
    })();
  }, []);

  const save = async () => {
    setBusy(true); setErr('');
    try {
      const rows = window.Calendar.shape.blocksToSlots(avail);
      // Hard timeout via logic.js — the modal can no longer hang on a flaky network.
      await window.MASTERY.withTimeout(Promise.resolve(onSave(rows)), 20000, 'Save availability');
      // Save timezone too. Non-fatal: if this errors we still close the modal
      // because availability did save — just surface a soft note.
      try {
        const { data: u } = await window.supa.auth.getUser();
        const uid = u?.user?.id;
        if (uid) await window.supa.from('profiles').update({ timezone: tz }).eq('id', uid);
      } catch (e) { console.warn('[avail] timezone save failed', e); }
      onClose();
    } catch (e) {
      setErr(e.message || 'Could not save.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(10,12,24,0.35)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:9000 }} onClick={onClose}>
      <div style={{ background:'#fff', borderRadius:16, padding:'24px 22px 20px', maxWidth:560, width:'min(560px, calc(100vw - 24px))', boxShadow:'0 20px 60px rgba(0,0,0,0.18)', fontFamily:"'Plus Jakarta Sans', sans-serif", maxHeight:'88vh', overflowY:'auto', boxSizing:'border-box' }} onClick={e => e.stopPropagation()}>
        <div style={{ fontFamily:"'Cormorant Garamond', serif", fontWeight:700, fontSize:22, color:'oklch(18% 0.03 265)', marginBottom:4, lineHeight:1.1 }}>Your weekly availability</div>
        <div style={{ fontSize:12, color:'oklch(60% 0.03 265)', marginBottom:20 }}>Pick start/end times per day. Add multiple blocks if there's a break.</div>
        <window.AvailabilityPicker value={avail} onChange={setAvail} compact timezone={tz} onTimezoneChange={setTz} />
        {err && <div style={{ marginTop:12, background:'oklch(95% 0.06 25)', color:'oklch(40% 0.15 25)', padding:'8px 12px', borderRadius:8, fontSize:12 }}>{err}</div>}
        <div style={{ display:'flex', gap:8, marginTop:20 }}>
          <button onClick={save} disabled={busy} style={{ flex:1, background:'oklch(22% 0.06 265)', color:'#fff', border:'none', borderRadius:9, padding:'13px 0', fontWeight:600, fontSize:14, cursor:busy?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity:busy?0.72:1, minHeight:44 }}>{busy ? 'Saving…' : 'Save availability'}</button>
          <button onClick={onClose} style={{ padding:'13px 18px', background:'oklch(95% 0.01 265)', border:'none', borderRadius:9, fontSize:14, cursor:'pointer', color:'oklch(46% 0.04 265)', fontFamily:"'Plus Jakarta Sans', sans-serif", fontWeight:600, minHeight:44 }}>Cancel</button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AddLessonModal, AvailabilityModal });
// LessonDetailPopup + TeacherStudentRow now live in
