/* global React, Icon, UI, LessonHighData */
(function () {
const { useState, useMemo } = React;
const D2 = LessonHighData;

// ============================================================
// Schedule — weekly calendar (no horizontal scroll, unified day columns)
// ============================================================
function Schedule({ spaceLabel, onOpenMember }) {
  // Mode: 'teacher' | 'room' — determines secondary info shown in each block
  const [mode, setMode] = useState('teacher');
  const [view, setView] = useState('week'); // day | week | month
  // I3 — kiosk modal trigger from this page
  const [kioskOpen, setKioskOpen] = useState(false);
  const [newResOpen, setNewResOpen] = useState(false);
  const hourPx = 56;
  // Show a wide time range so the calendar always has content to scroll through
  const startHour = 8;
  const endHour = 22;

  const todayDow = 3;
  const weekStartLabel = '2025년 11월 17일';
  const weekEndLabel   = '11월 23일';

  const filteredReservations = D2.reservations;

  // 7 days of the week
  const days = [
    { dow: 1, dn: '월', date: 17 },
    { dow: 2, dn: '화', date: 18 },
    { dow: 3, dn: '수', date: 19, isToday: true },
    { dow: 4, dn: '목', date: 20 },
    { dow: 5, dn: '금', date: 21 },
    { dow: 6, dn: '토', date: 22 },
    { dow: 7, dn: '일', date: 23 },
  ];

  return (
    <React.Fragment>
      <header className="page-header">
        <div>
          <h1 className="page-title">일정</h1>
          <div className="page-sub">{weekStartLabel} – {weekEndLabel} · 단일 지점</div>
        </div>
        <div className="page-actions">
          <div className="row" style={{ background: 'var(--bg-subtle)', padding: 2, borderRadius: 'var(--radius-md)', gap: 0 }}>
            {[{ id: 'day', label: '일' }, { id: 'week', label: '주' }, { id: 'month', label: '월' }].map(v => (
              <button
                key={v.id}
                className={`btn is-sm ${view === v.id ? 'is-primary' : 'is-ghost'}`}
                style={{ borderColor: 'transparent', height: 28 }}
                onClick={() => setView(v.id)}
              >
                {v.label}
              </button>
            ))}
          </div>
          <UI.Button icon={Icon.ChevLeft} isIcon variant="ghost" onClick={() => window.toast && window.toast('이전 주로 이동 — 다음 분기에 실제 데이터 연동')}/>
          <UI.Button variant="ghost" onClick={() => window.toast && window.toast('오늘 (2025-11-20)으로 이동')}>오늘</UI.Button>
          <UI.Button icon={Icon.ChevRight} isIcon variant="ghost" onClick={() => window.toast && window.toast('다음 주로 이동')}/>
          <div className="divider-v" style={{ height: 24 }}></div>
          <div className="row" style={{ background: 'var(--bg-subtle)', padding: 2, borderRadius: 'var(--radius-md)', gap: 0 }}>
            {[{ id: 'teacher', label: '선생님별' }, { id: 'room', label: `${spaceLabel}별` }].map(v => (
              <button
                key={v.id}
                className={`btn is-sm ${mode === v.id ? 'is-primary' : 'is-ghost'}`}
                style={{ borderColor: 'transparent', height: 28 }}
                onClick={() => setMode(v.id)}
              >
                {v.label}
              </button>
            ))}
          </div>
          <UI.Button icon={Icon.Mobile} variant="ghost" onClick={() => setKioskOpen(true)}>키오스크</UI.Button>
          <UI.Button icon={Icon.Plus} variant="primary" onClick={() => setNewResOpen(true)}>새 예약</UI.Button>
        </div>
      </header>

      {/* Legend */}
      <div className="row" style={{ marginBottom: 12, gap: 16, color: 'var(--text-secondary)', fontSize: 12 }}>
        <span className="row" style={{ gap: 6 }}><span className="dot-tone-lesson"/>수업</span>
        <span className="row" style={{ gap: 6 }}><span className="dot-tone-consultation"/>상담</span>
        <span className="row" style={{ gap: 6 }}><span className="dot-tone-rental"/>{spaceLabel} 대여</span>
        <span className="row" style={{ gap: 6 }}><span className="dot-tone-practice"/>자율 연습</span>
        <span style={{ marginLeft: 'auto' }}>{view === 'day' ? '드래그하여 시간 이동 · 우측 클릭으로 변경 요청 처리' : '날짜/시간을 클릭하면 일 대셔보드로 이동합니다'}</span>
      </div>

      <UI.Card>
        <UI.CardBody flush>
          {view === 'week' && (
            <WeekListView
              days={days}
              reservations={filteredReservations}
              onOpenMember={onOpenMember}
              onJumpToDay={(dow) => setView('day') /* future: pin selected dow */}
              spaceLabel={spaceLabel}
            />
          )}
          {view === 'day' && (
            <DayView
              dow={todayDow}
              date={19}
              dn="수"
              reservations={filteredReservations}
              startHour={startHour} endHour={endHour} hourPx={hourPx}
              onOpenMember={onOpenMember}
              mode={mode}
            />
          )}
          {view === 'month' && (
            <MonthListView
              reservations={filteredReservations}
              onOpenMember={onOpenMember}
              spaceLabel={spaceLabel}
            />
          )}
        </UI.CardBody>
        <UI.CardFooter>
          <div className="row" style={{ gap: 12 }}>
            <span>이번 주 수업 <strong className="t-mono num" style={{ color: 'var(--text-primary)' }}>23건</strong></span>
            <span className="tertiary">·</span>
            <span>상담 <strong className="t-mono num" style={{ color: 'var(--text-primary)' }}>3건</strong></span>
            <span className="tertiary">·</span>
            <span>{spaceLabel} 대여 <strong className="t-mono num" style={{ color: 'var(--text-primary)' }}>2건</strong></span>
          </div>
          <span style={{ marginLeft: 'auto', color: 'var(--text-tertiary)' }}>좌측 컬러 바 = 예약 타입</span>
        </UI.CardFooter>
      </UI.Card>

      {/* I3 · 키오스크 모드 */}
      {window.Attendance && <window.Attendance.Kiosk open={kioskOpen} onClose={() => setKioskOpen(false)}/>}

      {/* 새 예약 모달 */}
      <NewReservationModal open={newResOpen} onClose={() => setNewResOpen(false)}/>
    </React.Fragment>
  );
}

// ════════════════════════════════════════════════════════════
// WeekListView — 7 day cards stacked, each w/ count summary + reservation list
// Calendar grid 은 동시간 다수 예약을 읽기 어려워서 리스트 형태로 표시
// ════════════════════════════════════════════════════════════
function WeekListView({ days, reservations, onOpenMember, onJumpToDay, spaceLabel }) {
  // Compute per-day buckets + max for density bars
  const buckets = days.map(d => {
    const list = reservations.filter(r => r.dow === d.dow).sort((a, b) => a.start - b.start);
    const counts = { lesson: 0, consultation: 0, rental: 0, practice: 0 };
    list.forEach(r => { counts[r.type] = (counts[r.type] || 0) + 1; });
    return { d, list, counts, total: list.length };
  });
  const maxTotal = Math.max(1, ...buckets.map(b => b.total));

  return (
    <div className="sched-list">
      {buckets.map(({ d, list, counts, total }) => (
        <section key={d.dow} className={`sched-list__day ${d.isToday ? 'is-today' : ''}`}>
          <header className="sched-list__day-head">
            <button className="sched-list__day-title" onClick={() => onJumpToDay && onJumpToDay(d.dow)}>
              <span className="t-micro" style={{ color: d.isToday ? 'var(--accent-default)' : 'var(--text-tertiary)' }}>{d.dn}</span>
              <span className="t-h3" style={{ color: d.isToday ? 'var(--accent-default)' : 'var(--text-primary)' }}>{d.date}</span>
              {d.isToday && <UI.Badge tone="accent" dot>오늘</UI.Badge>}
            </button>
            <div className="sched-list__day-counts">
              <DayDensity counts={counts} total={total} maxTotal={maxTotal} spaceLabel={spaceLabel}/>
            </div>
          </header>
          {total === 0 ? (
            <div className="sched-list__empty t-caption">예약 없음</div>
          ) : (
            <ul className="sched-list__items">
              {list.map(r => <ResRow key={r.id} r={r} onOpenMember={onOpenMember}/>)}
            </ul>
          )}
        </section>
      ))}
    </div>
  );
}

function DayDensity({ counts, total, maxTotal, spaceLabel }) {
  if (total === 0) {
    return <span className="t-caption" style={{ fontSize: 12 }}>예약 없음</span>;
  }
  const segs = [
    { key: 'lesson',       label: '수업', count: counts.lesson || 0 },
    { key: 'consultation', label: '상담', count: counts.consultation || 0 },
    { key: 'practice',     label: '자율 연습', count: counts.practice || 0 },
    { key: 'rental',       label: `${spaceLabel} 대여`, count: counts.rental || 0 },
  ].filter(s => s.count > 0);
  return (
    <React.Fragment>
      <div className="sched-list__bar" title={`총 ${total}건`}>
        {segs.map(s => (
          <span key={s.key} className={`sched-list__bar-seg type-${s.key}`} style={{ flex: s.count }}/>
        ))}
        <span className="sched-list__bar-rest" style={{ flex: Math.max(0, maxTotal - total) }}/>
      </div>
      <div className="sched-list__chips">
        <strong className="t-mono num" style={{ color: 'var(--text-primary)' }}>{total}</strong>
        <span style={{ color: 'var(--text-tertiary)' }}>건</span>
        {segs.map(s => (
          <span key={s.key} className={`sched-list__chip type-${s.key}`}>
            <span className="sched-list__chip-dot"/>
            <span>{s.label} <span className="t-mono num">{s.count}</span></span>
          </span>
        ))}
      </div>
    </React.Fragment>
  );
}

function ResRow({ r, onOpenMember }) {
  const m = r.memberId ? D2.getMember(r.memberId) : null;
  const teacher = r.teacherId ? D2.getTeacher(r.teacherId) : null;
  const room = r.roomId ? D2.getRoom(r.roomId) : null;
  const name = m ? m.name : (r.prospect || (r.type === 'practice' && teacher ? `${teacher.name} 선생님` : '대여'));
  const typeLabel = r.type === 'lesson' ? '수업' : r.type === 'consultation' ? '상담' : r.type === 'practice' ? '자율 연습' : '대여';
  return (
    <li className={`sched-list__row type-${r.type}`} onClick={() => m && onOpenMember && onOpenMember(m.id)}>
      <div className="sched-list__row-time t-mono num">
        <span>{D2.formatTime(r.start)}</span>
        <span className="sched-list__row-end">{D2.formatTime(r.end)}</span>
      </div>
      <div className="sched-list__row-body">
        <div className="sched-list__row-line1">
          {m && <UI.Avatar name={m.name} tone={m.tone} size="sm"/>}
          <span className="sched-list__row-name">{name}</span>
          <span className={`sched-list__type-tag type-${r.type}`}>{typeLabel}</span>
        </div>
        <div className="sched-list__row-line2">
          {teacher && <span>{teacher.name} 선생님</span>}
          {teacher && room && <span className="sched-list__row-sep">·</span>}
          {room && <span>{room.name}</span>}
        </div>
      </div>
      <span className="sched-list__row-chev">›</span>
    </li>
  );
}

// ════════════════════════════════════════════════════════════
// MonthListView — mini calendar grid (left) + selected day list (right)
// Density encoded as fill intensity on each date cell
// ════════════════════════════════════════════════════════════
function MonthListView({ reservations, onOpenMember, spaceLabel }) {
  const [selected, setSelected] = useState(20); // today

  // Build calendar — Nov 2025 starts on Saturday (Nov 1 = Sat)
  const cells = [];
  const padStart = 5; // Mon-Sun layout
  for (let i = 0; i < padStart; i++) cells.push(null);
  for (let d = 1; d <= 30; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  const dateToDow = (d) => (d >= 17 && d <= 23) ? d - 16 : null;

  // Pre-compute counts per date
  const countsByDate = useMemo(() => {
    const out = {};
    for (let d = 1; d <= 30; d++) {
      const dow = dateToDow(d);
      const list = dow ? reservations.filter(r => r.dow === dow) : [];
      out[d] = list.length;
    }
    return out;
  }, [reservations]);

  const maxCount = Math.max(1, ...Object.values(countsByDate));

  // Reservations for the selected day
  const selDow = dateToDow(selected);
  const selList = (selDow ? reservations.filter(r => r.dow === selDow) : []).sort((a, b) => a.start - b.start);
  const selCounts = { lesson: 0, consultation: 0, rental: 0, practice: 0 };
  selList.forEach(r => { selCounts[r.type] = (selCounts[r.type] || 0) + 1; });

  return (
    <div className="sched-month-list">
      <div className="sched-month-list__cal">
        <div className="sched-month-list__cal-head">
          {['월','화','수','목','금','토','일'].map(d => (
            <div key={d} className="sched-month-list__cal-dow">{d}</div>
          ))}
        </div>
        <div className="sched-month-list__cal-grid">
          {cells.map((d, i) => {
            if (!d) return <div key={i} className="sched-month-list__cal-cell is-pad"/>;
            const count = countsByDate[d] || 0;
            const intensity = count / maxCount; // 0..1
            const isToday = d === 20;
            const isSel = d === selected;
            return (
              <button
                key={i}
                className={`sched-month-list__cal-cell ${isToday ? 'is-today' : ''} ${isSel ? 'is-selected' : ''} ${count === 0 ? 'is-empty' : ''}`}
                onClick={() => setSelected(d)}
                style={count > 0 ? { '--cell-fill': intensity.toFixed(2) } : undefined}
              >
                <span className={`sched-month-list__cal-date t-mono num ${isToday ? 'is-today-date' : ''}`}>{d}</span>
                {count > 0 && (
                  <span className="sched-month-list__cal-count t-mono num">{count}</span>
                )}
              </button>
            );
          })}
        </div>
        <div className="sched-month-list__cal-legend">
          <span className="t-caption" style={{ fontSize: 11 }}>예약수 밀도</span>
          <span className="sched-month-list__cal-scale">
            <span style={{ '--cell-fill': 0.15 }}/>
            <span style={{ '--cell-fill': 0.40 }}/>
            <span style={{ '--cell-fill': 0.70 }}/>
            <span style={{ '--cell-fill': 1.00 }}/>
          </span>
          <span className="t-caption" style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>적은 → 많음</span>
        </div>
      </div>

      <div className="sched-month-list__panel">
        <header className="sched-month-list__panel-head">
          <div className="col" style={{ gap: 2 }}>
            <span className="t-micro">2025년 11월</span>
            <div className="row" style={{ gap: 8, alignItems: 'baseline' }}>
              <span className="t-h2" style={{ fontSize: 24, fontWeight: 700 }}>{selected}일</span>
              {selected === 20 && <UI.Badge tone="accent" dot>오늘</UI.Badge>}
            </div>
          </div>
          <div className="sched-month-list__panel-counts">
            <strong className="t-mono num" style={{ fontSize: 16, color: 'var(--text-primary)' }}>{selList.length}</strong>
            <span style={{ color: 'var(--text-tertiary)', fontSize: 12 }}>건</span>
            {selCounts.lesson > 0 && <span className="sched-list__chip type-lesson"><span className="sched-list__chip-dot"/><span>수업 <span className="t-mono num">{selCounts.lesson}</span></span></span>}
            {selCounts.consultation > 0 && <span className="sched-list__chip type-consultation"><span className="sched-list__chip-dot"/><span>상담 <span className="t-mono num">{selCounts.consultation}</span></span></span>}
            {selCounts.practice > 0 && <span className="sched-list__chip type-practice"><span className="sched-list__chip-dot"/><span>자율 연습 <span className="t-mono num">{selCounts.practice}</span></span></span>}
            {selCounts.rental > 0 && <span className="sched-list__chip type-rental"><span className="sched-list__chip-dot"/><span>{spaceLabel} 대여 <span className="t-mono num">{selCounts.rental}</span></span></span>}
          </div>
        </header>
        {selList.length === 0 ? (
          <div className="sched-list__empty t-caption" style={{ padding: 32 }}>
            이 날에는 예약이 없습니다
          </div>
        ) : (
          <ul className="sched-list__items sched-list__items--panel">
            {selList.map(r => <ResRow key={r.id} r={r} onOpenMember={onOpenMember}/>)}
          </ul>
        )}
      </div>
    </div>
  );
}

// ============================================================
// Week view — 7 day columns (no resource sub-columns)
// ============================================================
function WeekView({ days, reservations, startHour, endHour, hourPx, onOpenMember, mode }) {
  const NOW_MIN = 15 * 60 + 30; // 15:30 wed
  const totalH = (endHour - startHour) * hourPx;

  return (
    <div className="sched-scroll">
      <div className="sched-week">
      {/* Hours rail */}
      <div className="sched-week__rail">
        <div className="sched-week__rail-head"/>
        {Array.from({ length: endHour - startHour }).map((_, i) => (
          <div key={i} className="sched-week__hour" style={{ height: hourPx }}>
            <span className="t-mono num sched-week__hour-label">
              {String(startHour + i).padStart(2, '0')}:00
            </span>
          </div>
        ))}
      </div>

      {/* Day columns */}
      {days.map(d => {
        const dayRes = reservations.filter(r => r.dow === d.dow);
        return (
          <div key={d.dow} className={`sched-week__day ${d.isToday ? 'is-today' : ''}`}>
            <div className="sched-week__day-head">
              <div className="row" style={{ gap: 6 }}>
                <span className="t-micro" style={{ color: d.isToday ? 'var(--accent-default)' : 'var(--text-tertiary)' }}>{d.dn}</span>
                <span className="t-h3" style={{ color: d.isToday ? 'var(--accent-default)' : 'var(--text-primary)' }}>{d.date}</span>
                {d.isToday && <UI.Badge tone="accent" dot>오늘</UI.Badge>}
              </div>
            </div>
            <div className="sched-week__day-body" style={{ height: totalH }}>
              {/* Hour grid lines */}
              {Array.from({ length: endHour - startHour }).map((_, i) => (
                <div key={i} className="sched-week__hour-line" style={{ top: i * hourPx }}/>
              ))}
              {/* Now indicator — single line, only on today */}
              {d.isToday && (
                <div className="sched-week__now" style={{ top: ((NOW_MIN / 60) - startHour) * hourPx }}/>
              )}
              {/* Lay out reservations with simple overlap handling */}
              <LaidOutBlocks
                reservations={dayRes}
                startHour={startHour} hourPx={hourPx}
                onOpenMember={onOpenMember}
                mode={mode}
              />
            </div>
          </div>
        );
      })}
      </div>
    </div>
  );
}

// Lay out reservations within a day-column, handling overlaps by horizontal partitioning
function LaidOutBlocks({ reservations, startHour, hourPx, onOpenMember, mode }) {
  // Group overlapping reservations into "tracks"
  const sorted = [...reservations].sort((a, b) => a.start - b.start);
  // Assign each reservation a column index within an overlap group
  const placed = []; // { r, col, colsInGroup }
  const open = []; // currently overlapping
  let groupCols = 0;
  let groupResolved = [];

  function commitGroup() {
    groupResolved.forEach(p => { p.colsInGroup = groupCols; });
    placed.push(...groupResolved);
    groupResolved = [];
    groupCols = 0;
  }

  sorted.forEach(r => {
    // Remove finished
    for (let i = open.length - 1; i >= 0; i--) {
      if (open[i].r.end <= r.start) open.splice(i, 1);
    }
    if (open.length === 0 && groupResolved.length > 0) commitGroup();
    // Find lowest available column
    const usedCols = new Set(open.map(o => o.col));
    let col = 0;
    while (usedCols.has(col)) col++;
    const placement = { r, col };
    open.push(placement);
    groupResolved.push(placement);
    groupCols = Math.max(groupCols, col + 1);
  });
  if (groupResolved.length > 0) commitGroup();

  return placed.map(({ r, col, colsInGroup }) => {
    const top = ((r.start / 60) - startHour) * hourPx;
    const h = ((r.end - r.start) / 60) * hourPx;
    const m = r.memberId ? D2.getMember(r.memberId) : null;
    const teacher = r.teacherId ? D2.getTeacher(r.teacherId) : null;
    const room = r.roomId ? D2.getRoom(r.roomId) : null;
    const widthPct = 100 / colsInGroup;
    const leftPct = col * widthPct;
    // In '선생님별' mode, show room as secondary. In '연습실별' mode, show teacher.
    const secondary = mode === 'teacher'
      ? (room ? room.name : null)
      : (teacher ? `${teacher.name} 선생님` : null);
    return (
      <div
        key={r.id}
        className={`calblock type-${r.type}`}
        style={{
          top,
          height: h - 4,
          left: `calc(${leftPct}% + 4px)`,
          width: `calc(${widthPct}% - 8px)`,
          right: 'auto',
        }}
        onClick={() => m && onOpenMember && onOpenMember(m.id)}
        title={`${m ? m.name : r.prospect || '대여'} · ${teacher ? teacher.name + ' 선생님' : ''}${room ? ' · ' + room.name : ''}`}
      >
        <div className="calblock__head">
          <span className="calblock__name">{m ? m.name : r.prospect || '대여'}</span>
          {secondary && <span className="calblock__sub">· {secondary}</span>}
        </div>
        <div className="calblock__meta t-mono num">{D2.formatTime(r.start)}–{D2.formatTime(r.end)}</div>
      </div>
    );
  });
}

// ============================================================
// Day view — 1 day, all resources as columns (fits without scroll)
// ============================================================
function DayView({ dow, date, dn, reservations, startHour, endHour, hourPx, onOpenMember, mode }) {
  const dayRes = reservations.filter(r => r.dow === dow);
  const NOW_MIN = 15 * 60 + 30;
  const totalH = (endHour - startHour) * hourPx;

  // In 선생님별 mode: columns are teachers. In 연습실별 mode: columns are rooms.
  const useRooms = mode === 'room';
  const groups = useRooms ? D2.rooms : D2.teachers;

  return (
    <div className="sched-scroll">
    <div className="sched-day">
      <div className="sched-day__rail">
        <div className="sched-day__rail-head"/>
        {Array.from({ length: endHour - startHour }).map((_, i) => (
          <div key={i} className="sched-week__hour" style={{ height: hourPx }}>
            <span className="t-mono num sched-week__hour-label">
              {String(startHour + i).padStart(2, '0')}:00
            </span>
          </div>
        ))}
      </div>

      <div className="sched-day__cols">
        <div className="sched-day__head">
          <div className="row" style={{ gap: 6, padding: '12px 12px' }}>
            <span className="t-micro" style={{ color: 'var(--accent-default)' }}>{dn}</span>
            <span className="t-h3" style={{ color: 'var(--accent-default)' }}>{date}</span>
            <UI.Badge tone="accent" dot>오늘</UI.Badge>
            <span style={{ marginLeft: 'auto', color: 'var(--text-tertiary)', fontSize: 12 }}>{useRooms ? '공간별' : '선생님별'}</span>
          </div>
          <div className="sched-day__subhead">
            {groups.map(g => (
              <div key={g.id} className="sched-day__group-label">
                {useRooms ? g.name : `${g.name} 선생님`}
              </div>
            ))}
          </div>
        </div>
        <div className="sched-day__body" style={{ height: totalH }}>
          {/* Hour grid lines spanning whole body */}
          {Array.from({ length: endHour - startHour }).map((_, i) => (
            <div key={i} className="sched-week__hour-line" style={{ top: i * hourPx, left: 0, right: 0 }}/>
          ))}
          {/* Per-group columns */}
          {groups.map(g => (
            <div key={g.id} className="sched-day__col">
              <LaidOutBlocks
                reservations={dayRes.filter(r => useRooms ? r.roomId === g.id : r.teacherId === g.id)}
                startHour={startHour} hourPx={hourPx}
                onOpenMember={onOpenMember}
                mode={mode}
              />
            </div>
          ))}
          {/* Now indicator spanning full width */}
          <div className="sched-week__now sched-week__now--full" style={{ top: ((NOW_MIN / 60) - startHour) * hourPx }}/>
        </div>
      </div>
    </div>
    </div>
  );
}

// ============================================================
// Month view — traditional grid with reservation pills
// ============================================================
function MonthView({ reservations, onOpenMember }) {
  const cells = [];
  // November 2025: starts on Sat (Nov 1 was Sat)
  // Build 5 weeks × 7 cols
  let dayCounter = 0;
  // Pad start (offset by Nov 1 being Sat = position 6 if week starts Sun, or 5 if Mon)
  // We'll use Mon-Sun layout
  const padStart = 5; // Nov 1 = Saturday → 5 empty cells before in Mon-Sun layout
  for (let i = 0; i < padStart; i++) cells.push(null);
  for (let d = 1; d <= 30; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  // For demo, only Nov 17-23 has reservations (our dow data). Map dates:
  // Mon 17 → dow 1, ... Sun 23 → dow 7
  const dateToDow = (d) => {
    if (d >= 17 && d <= 23) return d - 16;
    return null;
  };

  return (
    <div className="sched-month">
      <div className="sched-month__head">
        {['월','화','수','목','금','토','일'].map(d => (
          <div key={d} className="sched-month__head-cell">{d}</div>
        ))}
      </div>
      <div className="sched-month__grid">
        {cells.map((d, i) => {
          if (!d) return <div key={i} className="sched-month__cell is-pad"/>;
          const dow = dateToDow(d);
          const dayRes = dow ? reservations.filter(r => r.dow === dow) : [];
          const isToday = d === 20; // today is Thu 20 in display data
          return (
            <div key={i} className={`sched-month__cell ${isToday ? 'is-today' : ''}`}>
              <div className="sched-month__date">
                <span className={`t-mono num ${isToday ? 'sched-month__date-today' : ''}`}>{d}</span>
              </div>
              <div className="sched-month__pills">
                {dayRes.slice(0, 3).map(r => {
                  const m = r.memberId ? D2.getMember(r.memberId) : null;
                  return (
                    <button
                      key={r.id}
                      className={`sched-month__pill type-${r.type}`}
                      onClick={() => m && onOpenMember && onOpenMember(m.id)}
                    >
                      <span className="t-mono num sched-month__pill-time">{D2.formatTime(r.start)}</span>
                      <span className="sched-month__pill-name">{m ? m.name : r.prospect || '대여'}</span>
                    </button>
                  );
                })}
                {dayRes.length > 3 && (
                  <div className="sched-month__more">+{dayRes.length - 3} 더</div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function NewReservationModal({ open, onClose }) {
  const [type, setType] = useState('lesson');
  const [memberId, setMemberId] = useState(D2.members[0].id);
  const [teacherId, setTeacherId] = useState('t1');
  const [roomId, setRoomId] = useState('r1');
  const [dow, setDow] = useState(3);
  const [time, setTime] = useState('14:00');
  const [duration, setDuration] = useState(50);
  const [recur, setRecur] = useState('once');
  const m = D2.getMember(memberId);
  const t = D2.getTeacher(teacherId);
  const r = D2.getRoom(roomId);

  return (
    <UI.Modal open={open} onClose={onClose} title="새 예약 만들기" width={520}
      footer={
        <React.Fragment>
          <UI.Button variant="ghost" onClick={onClose}>취소</UI.Button>
          <UI.Button variant="primary" icon={Icon.Check} onClick={() => {
            onClose();
            const typeLabel = type === 'lesson' ? '수업' : type === 'consultation' ? '상담' : type === 'practice' ? '자율 연습' : '대여';
            const target = type === 'lesson' ? m.name : type === 'consultation' ? '신규 상담' : type === 'practice' ? m.name : '외부 대여';
            window.toast && window.toast(`${typeLabel} 예약 생성 — ${target} · ${D2.dayNames[dow - 1]}요일 ${time} (${r.name})${recur !== 'once' ? ' · 반복' : ''}`, { tone: 'success' });
          }}>예약 생성</UI.Button>
        </React.Fragment>
      }>
      <div style={{ display: 'grid', gap: 14 }}>
        <div>
          <div className="t-micro" style={{ marginBottom: 6 }}>예약 유형</div>
          <div style={{ display: 'flex', gap: 6 }}>
            {[
              { id: 'lesson', label: '1:1 수업' },
              { id: 'consultation', label: '신규 상담' },
              { id: 'practice', label: '자율 연습' },
              { id: 'rental', label: '공간 대여' },
            ].map(o => (
              <button key={o.id} type="button" className={`pill ${type === o.id ? 'is-active' : ''}`} onClick={() => setType(o.id)}>{o.label}</button>
            ))}
          </div>
        </div>

        {type === 'lesson' && (
          <div>
            <div className="t-micro" style={{ marginBottom: 6 }}>회원</div>
            <select className="inp" style={{ width: '100%' }} value={memberId} onChange={e => setMemberId(e.target.value)}>
              {D2.members.filter(x => x.status === 'ACTIVE').map(x => (
                <option key={x.id} value={x.id}>{x.name} — {D2.getTeacher(x.teacherId)?.name} 선생님</option>
              ))}
            </select>
          </div>
        )}

        {type !== 'rental' && (
          <div>
            <div className="t-micro" style={{ marginBottom: 6 }}>강사</div>
            <select className="inp" style={{ width: '100%' }} value={teacherId} onChange={e => setTeacherId(e.target.value)}>
              {D2.teachers.map(x => <option key={x.id} value={x.id}>{x.name}</option>)}
            </select>
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <div>
            <div className="t-micro" style={{ marginBottom: 6 }}>요일</div>
            <select className="inp" style={{ width: '100%' }} value={dow} onChange={e => setDow(+e.target.value)}>
              {D2.dayNames.map((d, i) => <option key={i} value={i + 1}>{d}요일</option>)}
            </select>
          </div>
          <div>
            <div className="t-micro" style={{ marginBottom: 6 }}>공간</div>
            <select className="inp" style={{ width: '100%' }} value={roomId} onChange={e => setRoomId(e.target.value)}>
              {D2.rooms.map(x => <option key={x.id} value={x.id}>{x.name}</option>)}
            </select>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <div>
            <div className="t-micro" style={{ marginBottom: 6 }}>시작 시간</div>
            <input type="time" className="inp" style={{ width: '100%' }} value={time} onChange={e => setTime(e.target.value)}/>
          </div>
          <div>
            <div className="t-micro" style={{ marginBottom: 6 }}>수업 시간 (분)</div>
            <select className="inp" style={{ width: '100%' }} value={duration} onChange={e => setDuration(+e.target.value)}>
              <option value={30}>30분</option>
              <option value={50}>50분</option>
              <option value={80}>80분</option>
              <option value={110}>110분</option>
            </select>
          </div>
        </div>

        <div>
          <div className="t-micro" style={{ marginBottom: 6 }}>반복</div>
          <div style={{ display: 'flex', gap: 6 }}>
            {[
              { id: 'once', label: '1회만' },
              { id: 'weekly', label: '매주 같은 시간' },
              { id: 'bi', label: '격주' },
            ].map(o => (
              <button key={o.id} type="button" className={`pill ${recur === o.id ? 'is-active' : ''}`} onClick={() => setRecur(o.id)}>{o.label}</button>
            ))}
          </div>
        </div>

        <div style={{ padding: 12, background: 'var(--bg-canvas)', borderRadius: 8, fontSize: 12.5, lineHeight: 1.6 }}>
          <strong>요약.</strong> {type === 'lesson' ? `${m.name} ${t.name} 선생님` : type === 'consultation' ? `신규 상담 (${t.name} 선생님)` : type === 'practice' ? `${m.name} 자율 연습` : `공간 대여`} · {D2.dayNames[dow - 1]}요일 {time}부터 {duration}분 · {r.name} {recur === 'weekly' ? '· 매주 반복' : recur === 'bi' ? '· 격주 반복' : ''}
        </div>
      </div>
    </UI.Modal>
  );
}

window.SchedulePage = { Schedule };
})();
