// src/features/student/ui/student-home-availability.jsx
//
// The "Your availability" panel from StudentHome: view-mode shows the
// projected hours; edit-mode swaps in the shared AvailabilityStep
// chooser and saves to student_info.availability + profiles.timezone.
//
// Split off from student-home.jsx so both files stay under the 400
// LOC budget. The five avail-related useState hooks live here now,
// not in the parent — there's no other consumer.
//
// Reads from window: AvailabilityStep, stdBtnStyle, projectAvailability,
// AVAIL_DAYS, availFmtH (the last three are bare-name refs that work
// because Babel-standalone shares the top-level scope across scripts).
//
// Public: window.StudentAvailabilityPanel.

const { AvailabilityStep, stdBtnStyle } = window;

const StudentAvailabilityPanel = ({ data, viewerTz, setViewerTz, setShowBlock }) => {
  const [editingAvail,    setEditingAvail]    = React.useState(false);
  const [availDraft,      setAvailDraft]      = React.useState(null);
  const [availNoteDraft,  setAvailNoteDraft]  = React.useState('');
  const [availSaving,     setAvailSaving]     = React.useState(false);
  const [availError,      setAvailError]      = React.useState('');

  // Sync drafts whenever the user opens the editor (or studentInfo first loads).
  React.useEffect(() => {
    if (editingAvail && availDraft === null) {
      const empty = Object.fromEntries([0,1,2,3,4,5,6].map(i => [i, { enabled:false, blocks:[{from:9,to:17}] }]));
      setAvailDraft(data.studentInfo?.availability && Object.keys(data.studentInfo.availability).length
        ? data.studentInfo.availability : empty);
      setAvailNoteDraft(data.studentInfo?.availabilityNote || '');
    }
  }, [editingAvail]);

  return (
    <div style={{ background:'#fff', borderRadius:18, padding:'18px clamp(14px, 5vw, 20px)', border:'1px solid oklch(91% 0.01 265)', boxShadow:'0 2px 12px oklch(18% 0.06 265 / 0.05)', marginBottom:20 }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: editingAvail ? 18 : 10, gap:8, flexWrap:'wrap' }}>
        <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.1em', color:'oklch(62% 0.03 265)' }}>Your availability</div>
        {!editingAvail && (
          <div style={{ display:'flex', gap:8 }}>
            <button onClick={() => setShowBlock(true)} title="Block off a specific date or time you're not available"
              style={{ background:'none', border:'1px solid oklch(88% 0.02 265)', borderRadius:8, padding:'5px 12px', fontSize:12, fontWeight:600, cursor:'pointer', color:'oklch(40% 0.04 265)', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Block time</button>
            <button onClick={() => { setEditingAvail(true); setAvailDraft(null); setAvailError(''); }}
              style={{ background:'none', border:'1px solid oklch(88% 0.02 265)', borderRadius:8, padding:'5px 12px', fontSize:12, fontWeight:600, cursor:'pointer', color:'oklch(40% 0.04 265)', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Edit</button>
          </div>
        )}
      </div>
      {/* Timezone badge — shows the viewer's (student's) current browser
          zone so they always know what zone the displayed times are in.
          The dropdown lets them override for this view; we don't persist
          the override because profile.timezone is the ANCHOR (set when
          they / admin last saved their hours), not a viewing preference. */}
      <div style={{ marginBottom: 12 }}>
        <window.TimezoneBadge compact value={viewerTz} onChange={setViewerTz} />
      </div>
      {editingAvail ? (
        <>
          {availDraft && (
            <AvailabilityStep
              avail={availDraft} note={availNoteDraft}
              onChangeAvail={setAvailDraft} onChangeNote={setAvailNoteDraft}
            />
          )}
          {availError && <div style={{ background:'oklch(96% 0.06 25)', color:'oklch(40% 0.15 25)', padding:'9px 12px', borderRadius:8, fontSize:13, marginTop:10 }}>{availError}</div>}
          <div style={{ display:'flex', gap:10, marginTop:16 }}>
            <button
              onClick={async () => {
                setAvailSaving(true); setAvailError('');
                try {
                  // Save the wall-clock hours AND anchor profile.timezone
                  // to the student's current browser zone — they just typed
                  // the hours in their local time, so that's the anchor.
                  await data.saveStudentInfo({ availability: availDraft, availabilityNote: availNoteDraft });
                  try {
                    const { data: u } = await window.supa.auth.getUser();
                    const uid = u?.user?.id;
                    if (uid) await window.supa.from('profiles').update({ timezone: viewerTz }).eq('id', uid);
                  } catch (e) { /* non-fatal: hours saved either way */ }
                  setEditingAvail(false); setAvailDraft(null);
                } catch (e) {
                  setAvailError(e.message || 'Could not save.');
                } finally { setAvailSaving(false); }
              }}
              disabled={availSaving}
              style={stdBtnStyle(true)}
            >{availSaving ? 'Saving…' : 'Save'}</button>
            <button onClick={() => { setEditingAvail(false); setAvailDraft(null); }} style={stdBtnStyle(false)}>Cancel</button>
          </div>
        </>
      ) : (
        (() => {
          const rawAv = data.studentInfo?.availability || {};
          const anchorTz = data.userTimezone || 'America/New_York';
          // Project anchor → viewer so what the student sees is in their
          // current browser zone, no matter where the admin set things up.
          const av = projectAvailability(rawAv, anchorTz, viewerTz);
          const enabledDays = Object.entries(av).filter(([,d]) => d.enabled && (d.blocks || []).length > 0);
          if (!enabledDays.length) {
            return <div style={{ fontSize:14, color:'oklch(62% 0.03 265)' }}>Not set yet — tap <strong>Edit</strong> to add your availability.</div>;
          }
          return (
            <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
              {enabledDays.map(([di, d]) => (
                <div key={di} style={{ fontSize:14, color:'oklch(36% 0.04 265)' }}>
                  <strong>{AVAIL_DAYS[Number(di)]}</strong>:{' '}
                  {(d.blocks || []).map(b => `${availFmtH(b.from)} – ${availFmtH(b.to)}`).join(' · ')}
                </div>
              ))}
            </div>
          );
        })()
      )}
    </div>
  );
};

window.StudentAvailabilityPanel = StudentAvailabilityPanel;
