// MedBridge — MyCalendar screen.
// One place to see every job/booking the user has — for both hosts (who is
// covering my practice, when?) and searchers (when am I working / training where?).
//
// Two views:
//   - List view (default): chronological by start date, grouped by month, with
//     past bookings collapsed at the bottom.
//   - Month view: classic month grid with date-anchored event chips,
//     navigable forward/back. Bookings spanning multiple days render as a
//     coloured strip across the cells they cover (capped at the visible month).
//
// Same component used on mobile and desktop. Desktop layout passes `wide` so
// the month grid uses bigger cells and the list shows extra columns.

const { useState: useC } = React;

// Pull bookings for a persona out of SAMPLE.bookings; default to empty array.
function bookingsFor(persona) {
  return (SAMPLE.bookings && SAMPLE.bookings[persona.key]) || [];
}

const MONTHS_DE = ['Jänner','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
const MONTHS_DE_SHORT = ['Jän','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];
const DOW_DE = ['Mo','Di','Mi','Do','Fr','Sa','So'];

const parseISO = (s) => { const [y,m,d] = s.split('-').map(Number); return new Date(y, m-1, d); };
const sameDay = (a, b) => a.getFullYear()===b.getFullYear() && a.getMonth()===b.getMonth() && a.getDate()===b.getDate();
const fmtMonth = (d) => `${MONTHS_DE[d.getMonth()]} ${d.getFullYear()}`;
const fmtDay = (d) => `${d.getDate()}. ${MONTHS_DE_SHORT[d.getMonth()]}`;

// Status → tone (green/amber/grey/red), independent of Angebotstyp.
function statusTone(status) {
  if (status === 'Heute')        return { fg: MB.brand[700], bg: MB.brand[50], bd: MB.brand[100] };
  if (status === 'Bestätigt')    return { fg: MB.success[700], bg: MB.success[100], bd: 'transparent' };
  if (status === 'Ausstehend')   return { fg: MB.warning[700], bg: MB.warning[100], bd: 'transparent' };
  if (status === 'Abgeschlossen')return { fg: MB.ink.tertiary, bg: MB.surface.canvas2, bd: MB.line.hair };
  if (status === 'Abgesagt')     return { fg: MB.danger[700],  bg: MB.danger[100], bd: 'transparent' };
  return { fg: MB.ink.secondary, bg: MB.surface.canvas2, bd: MB.line.hair };
}

// ─── Booking row (list view) ───────────────────────────────────
function BookingRow({ b, wide, onClick }) {
  const tone = b.type === 'Vertretung' ? MB.vertretung : MB.ausbildung;
  const s = statusTone(b.status);
  const start = parseISO(b.startDate);
  return (
    <div onClick={() => onClick && onClick(b)} style={{
      display: 'grid',
      gridTemplateColumns: wide ? '72px minmax(0,2fr) 180px 140px 120px 110px' : '52px minmax(0,1fr) auto',
      gap: wide ? 16 : 12, alignItems: 'center',
      padding: wide ? '14px 18px' : '12px 14px',
      background: MB.surface.raised,
      border: `1px solid ${MB.line.hair}`,
      borderLeft: `4px solid ${tone[600]}`,
      borderRadius: 12, marginBottom: 8,
      boxShadow: MB.shadow.card,
      cursor: 'pointer',
    }}>
      {/* Date column */}
      <div style={{ textAlign: 'center', color: MB.ink.primary, fontFamily: MB.font }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: tone[700], letterSpacing: 0.4, textTransform: 'uppercase' }}>
          {MONTHS_DE_SHORT[start.getMonth()]}
        </div>
        <div style={{ fontSize: wide ? 22 : 20, fontWeight: 700, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3 }}>
          {start.getDate()}
        </div>
        <div style={{ fontSize: 10, fontWeight: 600, color: MB.ink.tertiary, fontVariantNumeric: 'tabular-nums' }}>
          {DOW_DE[(start.getDay()+6)%7]}
        </div>
      </div>

      {/* Title + meta */}
      <div style={{ minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4, flexWrap: 'wrap' }}>
          <TypePill type={b.type} subtype={b.type === 'Ausbildung' ? 'Ausbildung' : null} size="sm" />
          <Chip tone="neutral" size="sm">{b.role === 'host' ? 'Als Anbieter' : 'Als Suchender'}</Chip>
        </div>
        <div style={{ fontFamily: MB.font, fontSize: wide ? 15 : 14, fontWeight: 700, color: MB.ink.primary, letterSpacing: -0.1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {b.title}
        </div>
        <div style={{ marginTop: 3, fontFamily: MB.font, fontSize: 12, color: MB.ink.tertiary, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <span><Icon name="pin" size={11} color={MB.ink.tertiary} /> {b.location}</span>
          {!wide && <span><Icon name="calendar" size={11} color={MB.ink.tertiary} /> {b.dateRange}</span>}
        </div>
      </div>

      {/* Wide-only columns */}
      {wide && (
        <>
          <div style={{ fontFamily: MB.font, fontSize: 13, color: MB.ink.secondary, fontVariantNumeric: 'tabular-nums' }}>{b.dateRange}</div>
          <div style={{ fontFamily: MB.font, fontSize: 13, color: MB.ink.secondary }}>{b.partner}</div>
          <div style={{ fontFamily: MB.font, fontSize: 13, color: MB.ink.secondary, fontVariantNumeric: 'tabular-nums' }}>{b.rate}</div>
        </>
      )}

      <span style={{
        padding: '3px 10px', borderRadius: 999, fontFamily: MB.font, fontSize: 12, fontWeight: 700,
        background: s.bg, color: s.fg, border: s.bd === 'transparent' ? 'none' : `1px solid ${s.bd}`,
        whiteSpace: 'nowrap',
      }}>{b.status}</span>
    </div>
  );
}

// ─── Month grid ─────────────────────────────────────────────────
function MonthGrid({ bookings, anchor, onPrev, onNext, wide }) {
  // Build the visible 6-week grid (Mon-first).
  const first = new Date(anchor.getFullYear(), anchor.getMonth(), 1);
  const startOffset = (first.getDay() + 6) % 7; // Mon = 0
  const gridStart = new Date(first); gridStart.setDate(1 - startOffset);
  const cells = Array.from({ length: 42 }, (_, i) => {
    const d = new Date(gridStart); d.setDate(gridStart.getDate() + i);
    return d;
  });

  // For each cell, the bookings active that day.
  const activeOn = (d) => bookings.filter(b => {
    const s = parseISO(b.startDate), e = parseISO(b.endDate);
    return d >= new Date(s.getFullYear(), s.getMonth(), s.getDate())
        && d <= new Date(e.getFullYear(), e.getMonth(), e.getDate());
  });

  const today = new Date(2026, 4, 11); // "Today" for the prototype is locked to 11 May 2026 per the design brief.

  const cellH = wide ? 92 : 66;
  const fontPx = wide ? 12 : 10;

  return (
    <div>
      {/* Month nav */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <button onClick={onPrev} style={{ border: 0, background: 'transparent', cursor: 'pointer', padding: '6px 10px', display: 'inline-flex', alignItems: 'center', gap: 4, color: MB.ink.secondary, fontFamily: MB.font, fontSize: 13, fontWeight: 600, borderRadius: 8 }}>
          <Icon name="chevron-l" size={14} /> Vorher
        </button>
        <div style={{ fontFamily: MB.font, fontSize: wide ? 18 : 16, fontWeight: 700, color: MB.ink.primary, letterSpacing: -0.2 }}>{fmtMonth(anchor)}</div>
        <button onClick={onNext} style={{ border: 0, background: 'transparent', cursor: 'pointer', padding: '6px 10px', display: 'inline-flex', alignItems: 'center', gap: 4, color: MB.ink.secondary, fontFamily: MB.font, fontSize: 13, fontWeight: 600, borderRadius: 8 }}>
          Nächster <Icon name="chevron-r" size={14} />
        </button>
      </div>

      {/* DOW header */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 6, marginBottom: 6, fontFamily: MB.font, fontSize: 11, fontWeight: 700, color: MB.ink.tertiary, letterSpacing: 0.4, textTransform: 'uppercase' }}>
        {DOW_DE.map(d => <div key={d} style={{ textAlign: 'center' }}>{d}</div>)}
      </div>

      {/* Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 6 }}>
        {cells.map((d, i) => {
          const inMonth = d.getMonth() === anchor.getMonth();
          const isToday = sameDay(d, today);
          const events = activeOn(d);
          return (
            <div key={i} style={{
              height: cellH, borderRadius: 8, padding: 6,
              background: inMonth ? MB.surface.raised : MB.surface.canvas,
              border: isToday ? `2px solid ${MB.brand[600]}` : `1px solid ${MB.line.hair}`,
              opacity: inMonth ? 1 : 0.6,
              display: 'flex', flexDirection: 'column', gap: 3, overflow: 'hidden',
            }}>
              <div style={{
                fontFamily: MB.font, fontSize: 11, fontWeight: isToday ? 800 : 600,
                color: isToday ? MB.brand[700] : (inMonth ? MB.ink.primary : MB.ink.tertiary),
                fontVariantNumeric: 'tabular-nums',
              }}>{d.getDate()}</div>
              {events.slice(0, wide ? 3 : 2).map((b, j) => {
                const tone = b.type === 'Vertretung' ? MB.vertretung : MB.ausbildung;
                return (
                  <div key={j} title={b.title} style={{
                    background: tone[100], color: tone[700],
                    borderLeft: `3px solid ${tone[600]}`,
                    borderRadius: 4, padding: wide ? '2px 6px' : '1px 4px',
                    fontFamily: MB.font, fontSize: fontPx, fontWeight: 700,
                    lineHeight: 1.2, overflow: 'hidden', textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap', minWidth: 0,
                  }}>{b.title}</div>
                );
              })}
              {events.length > (wide ? 3 : 2) && (
                <div style={{ fontFamily: MB.font, fontSize: 10, fontWeight: 600, color: MB.ink.tertiary }}>+ {events.length - (wide ? 3 : 2)}</div>
              )}
            </div>
          );
        })}
      </div>

      {/* Legend */}
      <div style={{ marginTop: 14, display: 'flex', gap: 18, flexWrap: 'wrap', fontFamily: MB.font, fontSize: 12, color: MB.ink.secondary }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: MB.vertretung[600] }} /> Vertretung</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: MB.ausbildung[600] }} /> Ausbildung</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, borderRadius: 3, border: `2px solid ${MB.brand[600]}` }} /> Heute</span>
      </div>
    </div>
  );
}

// ─── MyCalendar — top-level screen ─────────────────────────────
function MyCalendar({ persona, wide = false, embedHeader = true, onOpenBooking }) {
  const all = bookingsFor(persona);
  const [view, setView] = useC('list');
  const [anchor, setAnchor] = useC(new Date(2026, 7, 1)); // August 2026

  // Bucket the list view: today/upcoming first, then past.
  const today = new Date(2026, 4, 11);
  const upcoming = all
    .filter(b => parseISO(b.endDate) >= today)
    .sort((a, b) => parseISO(a.startDate) - parseISO(b.startDate));
  const past = all
    .filter(b => parseISO(b.endDate) < today)
    .sort((a, b) => parseISO(b.startDate) - parseISO(a.startDate));

  const hostCount = all.filter(b => b.role === 'host').length;
  const searcherCount = all.filter(b => b.role === 'searcher').length;

  return (
    <div style={{ background: MB.surface.canvas, paddingBottom: wide ? 24 : 110, minHeight: '100%' }}>
      {embedHeader && (
        <div style={{ padding: wide ? '24px 28px 12px' : '52px 20px 12px' }}>
          <h1 style={{ fontFamily: MB.font, fontSize: wide ? 24 : 28, fontWeight: 700, color: MB.ink.primary, letterSpacing: -0.4, margin: 0 }}>Kalender</h1>
          <div style={{ marginTop: 4, fontFamily: MB.font, fontSize: 14, color: MB.ink.secondary }}>
            {upcoming.length} bevorstehend · {past.length} abgeschlossen
            {hostCount > 0 && searcherCount > 0 && <> · {hostCount}× Anbieter, {searcherCount}× Suchend</>}
          </div>
        </div>
      )}

      {/* View toggle */}
      <div style={{ padding: wide ? '0 28px 16px' : '0 20px 12px' }}>
        <Segmented value={view} onChange={setView} size={wide ? 'md' : 'md'} options={[
          { value: 'list',  label: 'Liste',  icon: 'sort' },
          { value: 'month', label: 'Monat',  icon: 'calendar' },
        ]} />
      </div>

      {/* Body */}
      <div style={{ padding: wide ? '0 28px' : '0 20px' }}>
        {view === 'list' ? (
          <>
            {upcoming.length > 0 && (
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontFamily: MB.font, fontSize: 12, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: MB.ink.tertiary, marginBottom: 10 }}>
                  Bevorstehend
                </div>
                {upcoming.map(b => <BookingRow key={b.id} b={b} wide={wide} onClick={onOpenBooking} />)}
              </div>
            )}
            {past.length > 0 && (
              <div>
                <div style={{ fontFamily: MB.font, fontSize: 12, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: MB.ink.tertiary, marginBottom: 10 }}>
                  Abgeschlossen
                </div>
                {past.map(b => <BookingRow key={b.id} b={b} wide={wide} onClick={onOpenBooking} />)}
              </div>
            )}
            {all.length === 0 && (
              <div style={{
                background: MB.surface.raised, border: `1px dashed ${MB.line.border}`,
                borderRadius: 14, padding: '32px 20px', textAlign: 'center',
              }}>
                <Icon name="calendar" size={32} color={MB.ink.tertiary} />
                <div style={{ marginTop: 10, fontFamily: MB.font, fontSize: 15, fontWeight: 700, color: MB.ink.primary, letterSpacing: -0.1 }}>Noch keine Buchungen</div>
                <div style={{ marginTop: 4, fontFamily: MB.font, fontSize: 13, color: MB.ink.tertiary }}>Sobald eine Bewerbung bestätigt ist, erscheint sie hier.</div>
              </div>
            )}
          </>
        ) : (
          <div style={{
            background: MB.surface.raised, border: `1px solid ${MB.line.hair}`,
            borderRadius: 14, padding: wide ? 20 : 14, boxShadow: MB.shadow.card,
          }}>
            <MonthGrid bookings={all} anchor={anchor} wide={wide}
              onPrev={() => setAnchor(new Date(anchor.getFullYear(), anchor.getMonth() - 1, 1))}
              onNext={() => setAnchor(new Date(anchor.getFullYear(), anchor.getMonth() + 1, 1))} />
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MyCalendar, MonthGrid, bookingsFor });
