// src/features/instructor/ui/instructor-booking-calendar.jsx
//
// The month grid + time-slot column from InstructorBookingPage. A
// focused sub-component owning no state of its own — InstructorBooking-
// Page passes all derived values down. Split off so the parent stays
// under the 400 LOC budget.
//
// Reads from window: INST_DAYS is a bare-name ref into the parent
// file's scope (top-level Babel scripts share that scope at runtime).
//
// Public: window.BookingCalendarPicker, window.BookingConfirmForm.

// ── Design tokens ─────────────────────────────────────────────────────
const _B_DARK    = 'oklch(22% 0.06 265)';
const _B_MID     = 'oklch(55% 0.03 265)';
const _B_LIGHT   = 'oklch(72% 0.02 265)';
const _B_PAST    = 'oklch(86% 0.01 265)';
const _B_AVBG    = 'oklch(94% 0.04 150)';
const _B_AVFG    = 'oklch(28% 0.13 150)';
const _B_TODAY   = 'oklch(72% 0.17 80)';
const _B_BORDER  = 'oklch(91% 0.01 265)';
const _B_DIVIDER = 'oklch(94% 0.005 60)';

const BookingCalendarPicker = ({
  isMobile, canGoPrev, setMonthOffset, monthLabel, monthGrid, todayKey,
  slotsByViewerDate, selectedDateKey, setSelectedDateKey, setSelected,
  selected, slotsForDate, viewerTz, selectedDateLabel,
}) => {
  // ── Calendar column ──────────────────────────────────────────────────
  // Cap the grid at 308px so date cells stay ~40px regardless of viewport.
  // The outer calColumn wrapper can be wider (it aligns the legend) but the
  // actual 7-column grid is bounded. On desktop the card is a 2-col grid
  // (calendar | slots) so the column width is already bounded by 1fr; the
  // maxWidth is the safety net on wide screens and on mobile where 1fr = 100%.
  const calColumn = (
    <div style={{ minWidth:0 }}>
      {/* Bounded inner — keeps date cells compact */}
      <div style={{ maxWidth:308 }}>
        {/* Month navigation */}
        <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:16 }}>
          <button
            type="button"
            disabled={!canGoPrev}
            onClick={() => setMonthOffset(m => Math.max(0, m - 1))}
            style={{
              width:32, height:32, borderRadius:8,
              border:`1px solid ${_B_BORDER}`,
              background:'#fff',
              cursor: canGoPrev ? 'pointer' : 'default',
              fontSize:16, color: canGoPrev ? _B_DARK : _B_PAST,
              opacity: canGoPrev ? 1 : 0.4, flexShrink:0, padding:0,
              display:'flex', alignItems:'center', justifyContent:'center',
              fontFamily:"'Plus Jakarta Sans', sans-serif",
            }}
            aria-label="Previous month"
          >‹</button>
          <span style={{
            flex:1, textAlign:'center', fontSize:14, fontWeight:700,
            color: _B_DARK, fontFamily:"'Plus Jakarta Sans', sans-serif",
            letterSpacing:'0.01em',
          }}>{monthLabel}</span>
          <button
            type="button"
            onClick={() => setMonthOffset(m => m + 1)}
            style={{
              width:32, height:32, borderRadius:8,
              border:`1px solid ${_B_BORDER}`,
              background:'#fff', cursor:'pointer',
              fontSize:16, color: _B_DARK,
              flexShrink:0, padding:0,
              display:'flex', alignItems:'center', justifyContent:'center',
              fontFamily:"'Plus Jakarta Sans', sans-serif",
            }}
            aria-label="Next month"
          >›</button>
        </div>

        {/* Day-of-week headers */}
        <div style={{ display:'grid', gridTemplateColumns:'repeat(7, 1fr)', marginBottom:4 }}>
          {INST_DAYS.map(d => (
            <div key={d} style={{
              textAlign:'center', fontSize:10, fontWeight:700,
              color: _B_MID, textTransform:'uppercase',
              letterSpacing:'0.07em', padding:'0 0 6px',
            }}>{d}</div>
          ))}
        </div>

        {/* Date cells */}
        <div style={{ display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:2 }}>
          {monthGrid.map((cell, i) => {
            if (!cell) return <div key={i} style={{ aspectRatio:'1/1' }} />;
            const isPast   = cell.key < todayKey;
            const isToday  = cell.key === todayKey;
            const dayCount = (slotsByViewerDate[cell.key] || []).length;
            const open     = !isPast && dayCount > 0;
            const isSel    = selectedDateKey === cell.key;

            let bg, fg, border, fw;
            if (isSel) {
              bg = _B_DARK; fg = '#fff'; border = 'none'; fw = 700;
            } else if (open) {
              bg = _B_AVBG; fg = _B_AVFG; border = 'none'; fw = 600;
            } else if (isToday) {
              bg = 'transparent'; fg = _B_DARK;
              border = `1.5px solid ${_B_TODAY}`; fw = 600;
            } else {
              bg = 'transparent';
              fg = isPast ? _B_PAST : _B_LIGHT;
              border = 'none'; fw = 400;
            }

            return (
              <button
                key={cell.key}
                type="button"
                disabled={!open}
                onClick={() => { setSelectedDateKey(cell.key); setSelected(null); }}
                title={open ? `${dayCount} slot${dayCount === 1 ? '' : 's'} available` : undefined}
                style={{
                  aspectRatio:'1/1',
                  borderRadius:'50%',
                  border: border || 'none',
                  background: bg, color: fg,
                  fontSize:13, fontWeight: fw,
                  cursor: open ? 'pointer' : 'default',
                  fontFamily:"'Plus Jakarta Sans', sans-serif",
                  display:'flex', alignItems:'center', justifyContent:'center',
                  padding:0, minWidth:0, outline:'none',
                }}
              >
                {cell.day}
              </button>
            );
          })}
        </div>

        {/* Legend */}
        <div style={{
          display:'flex', gap:16, marginTop:12,
          fontSize:11, color: _B_MID, flexWrap:'wrap',
        }}>
          <span style={{ display:'inline-flex', alignItems:'center', gap:5 }}>
            <span style={{ width:10, height:10, borderRadius:'50%', background: _B_AVBG, flexShrink:0 }} />
            Available
          </span>
          <span style={{ display:'inline-flex', alignItems:'center', gap:5 }}>
            <span style={{ width:10, height:10, borderRadius:'50%', background: _B_DARK, flexShrink:0 }} />
            Selected
          </span>
        </div>
      </div>{/* end bounded inner */}
    </div>
  );

  // ── Time-slot panel ──────────────────────────────────────────────────
  const slotsPanel = selectedDateKey ? (
    <div style={{
      borderLeft: isMobile ? 'none' : `1px solid ${_B_DIVIDER}`,
      borderTop:  isMobile ? `1px solid ${_B_DIVIDER}` : 'none',
      paddingLeft: isMobile ? 0 : 20,
      paddingTop:  isMobile ? 16 : 0,
    }}>
      <div style={{
        fontSize:12, fontWeight:700, color: _B_DARK,
        marginBottom:10,
        fontFamily:"'Plus Jakarta Sans', sans-serif",
        letterSpacing:'0.01em',
      }}>{selectedDateLabel}</div>

      {slotsForDate.length === 0 ? (
        <div style={{
          fontSize:13, color: _B_MID, lineHeight:1.6,
          fontFamily:"'Plus Jakarta Sans', sans-serif",
        }}>
          No open times on this day. Try another date.
        </div>
      ) : (
        // Compact pill grid: 2 cols desktop, 3 cols mobile
        <div style={{
          display:'grid',
          gridTemplateColumns: isMobile ? 'repeat(3, 1fr)' : 'repeat(2, 1fr)',
          gap:6,
          maxHeight: isMobile ? 200 : 340,
          overflowY:'auto',
          paddingRight:2,
        }}>
          {slotsForDate.map(m => {
            const iso       = m.toISOString();
            const h         = window.Calendar.time.hourIn(m, viewerTz);
            const hourLabel = window.Calendar.time.hourLabel(h);
            const isSel     = selected?.absIso === iso;

            return (
              <button
                key={iso}
                type="button"
                onClick={() => {
                  const [y, mo, d] = selectedDateKey.split('-').map(Number);
                  const dayLabel = new Date(Date.UTC(y, mo - 1, d, 12)).toLocaleDateString(undefined, {
                    timeZone: viewerTz, weekday:'short', month:'short', day:'numeric',
                  });
                  setSelected({ absIso: iso, dayLabel, hourLabel });
                }}
                style={{
                  padding:'9px 4px',
                  borderRadius:8,
                  border:`1.5px solid ${isSel ? _B_DARK : _B_BORDER}`,
                  background: isSel ? _B_DARK : '#fff',
                  color: isSel ? '#fff' : _B_DARK,
                  fontSize:13, fontWeight: isSel ? 700 : 500,
                  cursor:'pointer',
                  fontFamily:"'Plus Jakarta Sans', sans-serif",
                  textAlign:'center',
                  minHeight:40,
                  outline:'none',
                  whiteSpace:'nowrap',
                  overflow:'hidden', textOverflow:'ellipsis',
                }}
              >
                {hourLabel}
              </button>
            );
          })}
        </div>
      )}
    </div>
  ) : null;

  // ── Outer card ───────────────────────────────────────────────────────
  // Desktop with a selected date: 2-column grid (calendar | time slots).
  // Desktop without selection / mobile: single column.
  // On mobile the card is not grid — calendar stacks above slots.
  return (
    <div style={{
      background:'#fff',
      border:`1px solid ${_B_BORDER}`,
      borderRadius:14,
      padding: isMobile ? '16px' : '20px 24px',
      marginBottom:24,
      display:'grid',
      gridTemplateColumns: (!isMobile && selectedDateKey) ? '1fr 200px' : '1fr',
      gap: isMobile ? 0 : 24,
      alignItems:'start',
    }}>
      {calColumn}
      {slotsPanel}
    </div>
  );
};

// ── Booking confirmation form ─────────────────────────────────────────
// Public visitors see name/phone/email + notes so admin can reach back.
// Signed-in students get a frictionless one-click "Book" version.
const BookingConfirmForm = ({
  selected, asStudent, reschedule, busy, error,
  form, setForm, handleBook,
}) => (
  <div style={{
    background:'#fff', borderRadius:14, padding:'20px 22px',
    border:`1px solid ${_B_BORDER}`,
    fontFamily:"'Plus Jakarta Sans', sans-serif",
  }}>
    <div style={{
      fontSize:13, fontWeight:700, color: _B_DARK, marginBottom:16,
    }}>
      {selected.dayLabel} at {selected.hourLabel}
    </div>
    <form onSubmit={handleBook}>
      {!asStudent && (
        <>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:14 }}>
            <div style={{ gridColumn:'1/-1' }}>
              <label style={instLabel}>Full name *</label>
              <input value={form.name} onChange={e => setForm(f => ({...f, name:e.target.value}))} placeholder="Your name" required style={instInput} />
            </div>
            <div>
              <label style={instLabel}>Phone</label>
              <input type="tel" inputMode="tel" autoComplete="tel" value={form.phone} onChange={e => setForm(f => ({...f, phone:e.target.value}))} placeholder="(555) 000-0000" style={instInput} />
            </div>
            <div>
              <label style={instLabel}>Email</label>
              <input type="email" inputMode="email" autoComplete="email" value={form.email} onChange={e => setForm(f => ({...f, email:e.target.value}))} placeholder="Optional" style={instInput} />
            </div>
          </div>
          <div style={{ marginBottom:14 }}>
            <label style={instLabel}>Notes</label>
            <input value={form.notes} onChange={e => setForm(f => ({...f, notes:e.target.value}))} placeholder="Level, goals, instrument…" style={instInput} />
          </div>
        </>
      )}
      {error && (
        <div style={{ fontSize:12, color:'oklch(40% 0.1 25)', marginBottom:12 }}>{error}</div>
      )}
      <button type="submit" disabled={busy} style={{
        width:'100%', background: _B_DARK, 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,
      }}>
        {busy
          ? (reschedule ? 'Requesting…' : 'Booking…')
          : (reschedule
              ? `Request reschedule to ${selected.dayLabel} at ${selected.hourLabel}`
              : asStudent
                ? `Book ${selected.dayLabel} at ${selected.hourLabel}`
                : `Request trial — ${selected.dayLabel} at ${selected.hourLabel}`)}
      </button>
    </form>
  </div>
);

Object.assign(window, { BookingCalendarPicker, BookingConfirmForm });
