// admin-instructors.jsx — Real instructor management (was admin-members.jsx).
// Supabase-wired: reads via window.useAdminData(), writes via ADMIN_DATA helpers.
// Replaces the v4 mock-only design verbatim except where it touched mock state.

// 24-hour grid (was 8a–7p). Used by the metric strip and the inline weekly
// schedule cells; the modal picker now uses AvailabilityPicker which has its
// own AM/PM time-range dropdown UI.
const AI_HOURS = Array.from({ length: 24 }, (_, h) => h);
const AI_DAYS  = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']; // UI uses Mon=0
const aiFmtH   = h => h === 0 ? '12 AM' : h === 12 ? '12 PM' : h > 12 ? (h-12)+' PM' : h+' AM';
// Column-header label style for the minimal instructor table.
const aiHCol = { fontSize:10.5, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.05em', color:'oklch(56% 0.03 265)' };

// ── Address autosuggest (OpenStreetMap Nominatim, free + no API key) ──
// Joe asked for autocompletion on the studio-address field so admins don't
// have to type the whole address by hand. Nominatim's free tier requires
// a real User-Agent and 1 req/sec — we throttle by debouncing 350ms.
const AdminInstructors = () => {
  const data = window.useAdminData();
  const isMobile = window.useIsMobile();
  const [showAdd, setShowAdd] = React.useState(false);

  const realInstructors = (data.instructors || []).filter(i => !i.isSample);
  const totalStudents = (data.students || []).length;
  // Bug fix 2026-05-21: derive YYYY-MM-DD in the admin's TZ rather than
  // slicing the UTC ISO string, so late-evening lessons in negative-UTC
  // zones don't roll into the next day's bucket.
  const adminTz = window.adminSchTz;
  const ymdInAdminTz = (iso) => {
    if (!iso) return '';
    try { return window.Calendar.time.dateKey(new Date(iso), adminTz); }
    catch (e) { return (iso || '').slice(0, 10); }
  };
  const todayStr   = ymdInAdminTz(new Date().toISOString());
  const weekEnd    = new Date(); weekEnd.setDate(weekEnd.getDate()+6);
  const weekEndStr = ymdInAdminTz(weekEnd.toISOString());
  const lessonsThisWeek = (data.bookings || []).filter(b => {
    const d = ymdInAdminTz(b.scheduledAt);
    return d >= todayStr && d <= weekEndStr && b.status !== 'cancelled';
  }).length;

  if (data.loading) {
    return <div style={{ padding:60, textAlign:'center', color:'oklch(55% 0.03 265)', fontSize:14 }}>Loading instructors…</div>;
  }

  return (
    <div>
      {/* Summary strip */}
      <div style={{ background:'oklch(20% 0.07 265)', borderRadius:14, padding:'16px 24px', marginBottom:22, display:'flex', gap:32, alignItems:'center', flexWrap:'wrap' }}>
        {[
          { label:'Active Instructors', value: realInstructors.length },
          { label:'Total Students',     value: totalStudents          },
          { label:'Lessons This Week',  value: lessonsThisWeek        },
        ].map(s => (
          <div key={s.label}>
            <div style={{ fontSize:10, color:'rgba(255,255,255,0.48)', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:4 }}>{s.label}</div>
            <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:26, fontWeight:700, color:'#fff' }}>{s.value}</div>
          </div>
        ))}
        <div style={{ marginLeft:'auto' }}>
          <button onClick={()=>setShowAdd(true)} style={{ background:'oklch(72% 0.17 80)', color:'oklch(18% 0.06 265)', border:'none', borderRadius:9, padding:'9px 20px', fontWeight:700, fontSize:13, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", whiteSpace:'nowrap' }}>+ Add Instructor</button>
        </div>
      </div>

      {realInstructors.length === 0 ? (
        <div style={{ padding:60, textAlign:'center', color:'oklch(55% 0.03 265)', fontSize:14, background:'#fff', borderRadius:14, border:'1px solid oklch(91% 0.01 265)' }}>
          No real instructors yet. Click <strong>+ Add Instructor</strong> to create one.
        </div>
      ) : (
        <div style={{ background:'#fff', borderRadius:14, border:'1px solid oklch(91% 0.01 265)', overflow:'hidden', boxShadow:'0 1px 4px oklch(18% 0.06 265 / 0.04)' }}>
          {/* Column header — grid template MUST match AICard's collapsed row (admin-instructors-card.jsx).
              Desktop: Instructor · Teaches · Students · Classes(mo) · Payout(mo) · chevron.
              Mobile: Instructor · Payout(mo) · chevron (payout is the number Joe scans for). */}
          <div style={{ display:'grid', gridTemplateColumns: isMobile ? 'minmax(0,1fr) 76px 22px' : 'minmax(0,2.1fr) minmax(0,1.25fr) 52px 56px 80px 22px', alignItems:'center', gap:12, padding:'9px 16px', borderBottom:'1px solid oklch(92% 0.01 265)', background:'oklch(98.5% 0.005 265)' }}>
            <div style={aiHCol}>Instructor</div>
            {!isMobile && <div style={aiHCol}>Teaches</div>}
            {!isMobile && <div style={{ ...aiHCol, textAlign:'right' }}>Students</div>}
            {!isMobile && <div style={{ ...aiHCol, textAlign:'right' }} title="Lessons given this month">Classes</div>}
            <div style={{ ...aiHCol, textAlign:'right' }} title="Payout owed for this month — resets to $0 when you settle">Payout</div>
            <div />
          </div>
          {realInstructors.map(ins => <window.AICard key={ins.id} instructor={ins} />)}
        </div>
      )}

      {showAdd && <window.AIAddModal onClose={()=>setShowAdd(false)} />}
    </div>
  );
};

// Expose helpers used by admin-students.jsx (load order: this file BEFORE admin-students).
// MagicLinkPostCreate + Admin*-aliases are exposed in
// admin-instructors-modals.jsx — they're no longer in scope here.
Object.assign(window, { AdminInstructors });
