// SkinJourney Dashboard — Calendar (month + agenda)
const { useState: useS_cal, useMemo: useM_cal } = React;

function CalendarScreen({ navigate, onBookAppointment, dataset }) {
  const [cursor, setCursor] = useS_cal(new Date(SJ_DATA.NOW.getFullYear(), SJ_DATA.NOW.getMonth(), 1));
  const [view, setView] = useS_cal('month');
  const [selected, setSelected] = useS_cal(new Date(SJ_DATA.NOW).toDateString());

  const appts = dataset === 'empty' ? [] : SJ_DATA.APPOINTMENTS;

  const apptsByDate = useM_cal(() => {
    const m = new Map();
    appts.forEach((a) => {
      const k = new Date(a.scheduled_at).toDateString();
      if (!m.has(k)) m.set(k, []);
      m.get(k).push(a);
    });
    return m;
  }, [appts]);

  const monthGrid = useM_cal(() => {
    // Hebrew calendar: Sunday-first
    const first = new Date(cursor);
    const startDay = first.getDay(); // 0 = Sunday
    const daysInMonth = new Date(cursor.getFullYear(), cursor.getMonth() + 1, 0).getDate();
    const cells = [];
    for (let i = 0; i < startDay; i++) cells.push({ blank: true });
    for (let d = 1; d <= daysInMonth; d++) {
      const date = new Date(cursor.getFullYear(), cursor.getMonth(), d);
      cells.push({ date, key: date.toDateString() });
    }
    while (cells.length % 7) cells.push({ blank: true });
    return cells;
  }, [cursor]);

  const monthLabel = `${SJ_DATA.HEB_MONTHS_FULL[cursor.getMonth()]} ${cursor.getFullYear()}`;
  const selectedDate = new Date(selected);
  const dayAppts = (apptsByDate.get(selected) || []).sort((a, b) => new Date(a.scheduled_at) - new Date(b.scheduled_at));

  const today = new Date(SJ_DATA.NOW).toDateString();

  return (
    <div className="screen content-scroll">
      <PageHeader
        title="יומן"
        subtitle="מבט חודשי על התורים שלך"
        actions={
          <>
            <Segmented value={view} onChange={setView} options={[
              { value: 'month', label: 'חודש' },
              { value: 'week', label: 'שבוע' },
              { value: 'agenda', label: 'אג׳נדה' },
            ]} />
            <Button kind="primary" icon="plus" onClick={onBookAppointment}>קבע תור חדש</Button>
          </>
        }
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 24, alignItems: 'start' }}>
        {/* Calendar grid */}
        <Card flush>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '18px 22px', borderBottom: '1px solid var(--border-subtle)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <IconButton icon="chevron_right" onClick={() => setCursor(new Date(cursor.getFullYear(), cursor.getMonth() - 1, 1))} />
              <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>{monthLabel}</h2>
              <IconButton icon="chevron_left" onClick={() => setCursor(new Date(cursor.getFullYear(), cursor.getMonth() + 1, 1))} />
            </div>
            <Button kind="ghost" size="sm" onClick={() => { setCursor(new Date(SJ_DATA.NOW.getFullYear(), SJ_DATA.NOW.getMonth(), 1)); setSelected(today); }}>
              היום
            </Button>
          </div>

          {/* Day-of-week header — RTL means Sun starts on the right */}
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)',
            padding: '12px 18px 0',
            fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)',
            letterSpacing: 0.4, textTransform: 'uppercase', textAlign: 'center',
          }}>
            {SJ_DATA.HEB_DAYS_SHORT.map((d) => <div key={d}>{d}</div>)}
          </div>

          {/* Cells */}
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6,
            padding: '12px 18px 20px',
          }}>
            {monthGrid.map((cell, i) => {
              if (cell.blank) return <div key={i} />;
              const cellAppts = apptsByDate.get(cell.key) || [];
              const isToday = cell.key === today;
              const isSel = cell.key === selected;
              return (
                <button key={cell.key} onClick={() => setSelected(cell.key)}
                  style={{
                    aspectRatio: '1 / 1.05',
                    border: '1px solid ' + (isSel ? 'var(--sage-500)' : 'var(--border-subtle)'),
                    background: isSel ? 'var(--sage-50)' : isToday ? 'var(--sand-100)' : 'var(--surface)',
                    borderRadius: 12,
                    padding: 8,
                    display: 'flex', flexDirection: 'column', gap: 4,
                    cursor: 'pointer',
                    transition: 'all var(--dur-quick) var(--ease-standard)',
                    fontFamily: 'inherit',
                  }}
                  onMouseEnter={(e) => { if (!isSel) e.currentTarget.style.background = 'var(--row-hover)'; }}
                  onMouseLeave={(e) => { if (!isSel) e.currentTarget.style.background = isToday ? 'var(--sand-100)' : 'var(--surface)'; }}
                >
                  <div className="tabular" style={{
                    fontSize: 13, fontWeight: isToday ? 700 : 500,
                    color: isToday ? 'var(--sage-700)' : 'var(--text-primary)',
                    textAlign: 'end',
                  }}>{cell.date.getDate()}</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 3, marginTop: 'auto' }}>
                    {cellAppts.slice(0, 2).map((a) => (
                      <div key={a.id} style={{
                        fontSize: 10, fontWeight: 600,
                        padding: '2px 6px', borderRadius: 4,
                        background: a.status === 'pending' ? 'var(--coral-100)' :
                                    a.status === 'confirmed' ? 'var(--sage-100)' : 'var(--warning-container)',
                        color: a.status === 'pending' ? 'var(--coral-700)' :
                                a.status === 'confirmed' ? 'var(--sage-700)' : 'var(--on-warning-container)',
                        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                        textAlign: 'start',
                      }}>
                        <span className="tabular ltr-run">{SJ_DATA.formatHebTime(a.scheduled_at)}</span>
                        {' · '}{SJ_DATA.byId(a.patient_id).name.split(' ')[0]}
                      </div>
                    ))}
                    {cellAppts.length > 2 && (
                      <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-tertiary)', textAlign: 'start', paddingInlineStart: 6 }}>
                        +{cellAppts.length - 2} נוספים
                      </div>
                    )}
                  </div>
                </button>
              );
            })}
          </div>

          {/* Legend */}
          <div style={{
            display: 'flex', gap: 16, padding: '12px 22px',
            borderTop: '1px solid var(--border-subtle)',
            background: 'var(--sand-100)',
            fontSize: 12, color: 'var(--text-tertiary)',
            borderRadius: '0 0 var(--radius-xl) var(--radius-xl)',
          }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--sage-500)' }} />
              מאושר
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--coral-400)' }} />
              ממתין לאישור
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--warning)' }} />
              בוטל
            </span>
          </div>
        </Card>

        {/* Day detail */}
        <Card flush>
          <div style={{ padding: '20px 22px', borderBottom: '1px solid var(--border-subtle)' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.6, textTransform: 'uppercase' }}>
              {SJ_DATA.HEB_DAYS[selectedDate.getDay()]}
            </div>
            <h2 style={{ margin: '4px 0 0', fontSize: 22, fontWeight: 700 }}>
              <span className="tabular">{selectedDate.getDate()}</span> ב{SJ_DATA.HEB_MONTHS_FULL[selectedDate.getMonth()]}
            </h2>
            <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--text-tertiary)' }}>
              {dayAppts.length === 0 ? 'אין תורים ליום זה' : `${dayAppts.length} ${dayAppts.length === 1 ? 'תור' : 'תורים'}`}
            </p>
          </div>

          {dayAppts.length === 0 ? (
            <Empty icon="calendar" title="יום פנוי"
                   body={'אין תורים מתוכננים. לחצי על "קבע תור חדש" כדי להוסיף.'}
                   action={<Button kind="primary" size="sm" icon="plus" onClick={onBookAppointment}>קבעי תור</Button>} />
          ) : (
            <div style={{ padding: '12px 0' }}>
              {dayAppts.map((a) => {
                const p = SJ_DATA.byId(a.patient_id);
                return (
                  <div key={a.id}
                    onClick={() => navigate({ name: 'patient', id: p.id })}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 14,
                      padding: '14px 22px', cursor: 'pointer',
                      transition: 'background var(--dur-quick) var(--ease-standard)',
                    }}
                    onMouseEnter={(e) => e.currentTarget.style.background = 'var(--row-hover)'}
                    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                  >
                    <div className="tabular ltr-run" style={{
                      fontSize: 16, fontWeight: 700,
                      color: a.status === 'pending' ? 'var(--coral-700)' : 'var(--sage-700)',
                      width: 56,
                    }}>{SJ_DATA.formatHebTime(a.scheduled_at)}</div>
                    <Avatar name={p.name} size="sm" />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600 }}>{p.name}</div>
                      <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
                        {a.practitioner_note || (a.status === 'pending' ? 'ממתין לאישור' : 'מעקב')}
                      </div>
                    </div>
                    <Chip kind={a.status === 'pending' ? 'coral' : 'success'}>
                      {a.status === 'pending' ? 'ממתין' : 'מאושר'}
                    </Chip>
                  </div>
                );
              })}
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}

window.CalendarScreen = CalendarScreen;
