// SkinJourney Dashboard — Overview (the daily cockpit)
const { useState: useState_ov, useMemo: useMemo_ov } = React;

function NeedsAttentionItem({ patient, reason, onClick, onAction }) {
  const reasonMap = {
    'pending-appointment': {
      icon: 'appointments', kind: 'coral',
      title: 'ביקשה תור חדש',
      sub: 'לפני 18 שעות',
      cta: 'אשרי את הבקשה',
    },
    'cancelled': {
      icon: 'x', kind: 'warning',
      title: 'ביטלה תור',
      sub: 'לפני 4 ימים — מומלץ ליצור קשר',
      cta: 'קבעי תור חדש',
    },
    'no-upload': {
      icon: 'camera', kind: 'neutral',
      title: 'לא העלתה תמונות 18 ימים',
      sub: 'אולי שווה תזכורת עדינה',
      cta: 'שלחי תזכורת',
    },
  };
  const m = reasonMap[reason];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '14px 16px',
      borderTop: '1px solid var(--border-subtle)',
      transition: 'background var(--dur-quick) var(--ease-standard)',
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = 'var(--row-hover)'}
    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >
      <Avatar name={patient.name} size="sm" />
      <div style={{ flex: 1, minWidth: 0, cursor: 'pointer' }} onClick={onClick}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
          <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' }}>{patient.name}</span>
          <Chip kind={m.kind} dot>{m.title}</Chip>
        </div>
        <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>{m.sub}</div>
      </div>
      <Button kind="ghost" size="sm" iconRight="arrow_left" onClick={onAction}>{m.cta}</Button>
    </div>
  );
}

function UpcomingItem({ appt, patient, onClick }) {
  const d = new Date(appt.scheduled_at);
  const isToday = new Date(SJ_DATA.NOW).toDateString() === d.toDateString();
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '12px 16px',
      borderTop: '1px solid var(--border-subtle)',
      cursor: 'pointer',
    }}
    onClick={onClick}
    onMouseEnter={(e) => e.currentTarget.style.background = 'var(--row-hover)'}
    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >
      <div style={{
        width: 52, padding: 8,
        background: isToday ? 'var(--sage-50)' : 'var(--surface-sunken)',
        borderRadius: 10, textAlign: 'center',
        border: isToday ? '1px solid var(--sage-200)' : '1px solid transparent',
      }}>
        <div style={{ fontSize: 10, fontWeight: 700, color: isToday ? 'var(--sage-700)' : 'var(--text-tertiary)', textTransform: 'uppercase', letterSpacing: 0.4 }}>
          {isToday ? 'היום' : SJ_DATA.HEB_MONTHS_SHORT[d.getMonth()]}
        </div>
        <div style={{ fontSize: 16, fontWeight: 700, color: isToday ? 'var(--sage-700)' : 'var(--text-primary)', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
          {d.getDate()}
        </div>
      </div>
      <Avatar name={patient.name} size="sm" />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-primary)' }}>{patient.name}</div>
        <div style={{ fontSize: 12, color: 'var(--text-tertiary)', display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="tabular ltr-run">{SJ_DATA.formatHebTime(d)}</span>
          {appt.practitioner_note && <><span>·</span><span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{appt.practitioner_note}</span></>}
        </div>
      </div>
      <StatusDot kind="sage" />
    </div>
  );
}

function ActivityRow({ item }) {
  const patient = SJ_DATA.byId(item.patient_id);
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0',
      borderBottom: '1px solid var(--border-subtle)',
    }}>
      <span style={{
        width: 28, height: 28, borderRadius: 8,
        background: item.type === 'connected' ? 'var(--coral-100)' : 'var(--sage-50)',
        color: item.type === 'connected' ? 'var(--coral-700)' : 'var(--sage-700)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={item.type === 'connected' ? 'heart' : 'camera'} size={14} />
      </span>
      <Avatar name={patient.name} size="sm" />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, color: 'var(--text-primary)' }}>
          <strong>{patient.name}</strong> · {item.text}
        </div>
        <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 1 }}>{SJ_DATA.formatRelativeHe(item.at)}</div>
      </div>
    </div>
  );
}

function InviteCodeHero({ practitioner, onCopy, onShare, compact }) {
  return (
    <Card flush style={{ overflow: 'hidden' }}>
      <div style={{ display: 'flex' }}>
        <div style={{
          width: 6, background: 'linear-gradient(180deg, var(--sage-500), var(--sage-700))',
          flexShrink: 0,
        }} />
        <div style={{ display: 'grid', gridTemplateColumns: compact ? '1fr' : 'minmax(280px, 1fr) minmax(260px, 1fr)', gap: 0, flex: 1 }}>
          <div style={{ padding: '28px 32px', display: 'flex', flexDirection: 'column', gap: 14, justifyContent: 'center' }}>
            <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.8, color: 'var(--text-tertiary)', textTransform: 'uppercase' }}>
              קוד ההצטרפות שלך
            </span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
              <span className="wordmark tabular" style={{ fontSize: 38, color: 'var(--sage-700)', direction: 'ltr', letterSpacing: 3, lineHeight: 1, whiteSpace: 'nowrap' }}>
                {practitioner.invite_code}
              </span>
            </div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <Button kind="primary" icon="copy" onClick={onCopy}>העתיקי קוד</Button>
              <Button kind="secondary" icon="qr" onClick={onShare}>הראי QR</Button>
              <Button kind="secondary" icon="share" onClick={onShare}>שלחי בוואטסאפ</Button>
            </div>
          </div>
          <div style={{
            padding: '28px 32px',
            background: 'linear-gradient(160deg, var(--sage-50) 0%, var(--sand-100) 100%)',
            display: 'flex', flexDirection: 'column', gap: 10, justifyContent: 'center',
          }}>
            <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--sage-700)', letterSpacing: 0.4 }}>
              איך המטופלת מצטרפת
            </span>
            <ol style={{
              margin: 0, padding: 0, listStyle: 'none', counterReset: 'step',
              display: 'flex', flexDirection: 'column', gap: 6,
              fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.6,
            }}>
              {[
                'פתחי את אפליקציית SkinJourney',
                'הגדרות → "חיבור למטפל/ת"',
                'הזיני את הקוד למעלה',
                'ברגע שהיא תאשר תופיעי ברשימת המטופלות',
              ].map((step, i) => (
                <li key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                  <span style={{
                    flexShrink: 0, width: 22, height: 22, borderRadius: '50%',
                    background: 'var(--surface-elevated)', border: '1px solid var(--sage-200)',
                    color: 'var(--sage-700)', fontWeight: 700, fontSize: 11,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    fontVariantNumeric: 'tabular-nums',
                  }}>{i + 1}</span>
                  {step}
                </li>
              ))}
            </ol>
          </div>
        </div>
      </div>
    </Card>
  );
}

function OverviewScreen({ navigate, onCopyCode, onBookAppointment, dataset }) {
  const hour = new Date(SJ_DATA.NOW).getHours();
  const greeting = hour < 12 ? 'בוקר טוב' : hour < 17 ? 'צהריים טובים' : 'ערב טוב';

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

  const pending = appts.filter((a) => a.status === 'pending');
  const upcoming = appts
    .filter((a) => a.status === 'confirmed' && new Date(a.scheduled_at) >= new Date(SJ_DATA.NOW.getTime() - 3600 * 1000))
    .sort((a, b) => new Date(a.scheduled_at) - new Date(b.scheduled_at));
  const today = appts.filter((a) => a.status === 'confirmed' && new Date(a.scheduled_at).toDateString() === new Date(SJ_DATA.NOW).toDateString());
  const flagged = patients.filter((p) => p.flagged);

  const photosThisWeek = patients.reduce((acc, p) => acc + (p.weekly[p.weekly.length - 1] || 0), 0);

  // Sparkline: photos/week across the clinic for 8 weeks
  const photosTrend = useMemo_ov(() => {
    const weeks = 8;
    const series = new Array(weeks).fill(0);
    patients.forEach((p) => {
      const slice = p.weekly.slice(-weeks);
      slice.forEach((v, i) => { series[weeks - slice.length + i] += v; });
    });
    return series;
  }, [patients]);
  const trendDelta = photosTrend[photosTrend.length - 1] - photosTrend[photosTrend.length - 2] || 0;

  if (patients.length === 0) {
    return (
      <div className="screen content-scroll">
        <PageHeader
          title={`${greeting}, אלעד`}
          subtitle={SJ_DATA.formatHebFull(SJ_DATA.NOW) + ' · ' + SJ_DATA.HEB_DAYS[new Date(SJ_DATA.NOW).getDay()]}
        />
        <InviteCodeHero practitioner={SJ_DATA.PRACTITIONER} onCopy={onCopyCode} onShare={onCopyCode} />
        <div style={{ marginTop: 32 }}>
          <Empty
            icon="leaf"
            title="מוכנה להתחיל"
            body="שלחי את קוד ההצטרפות שלמעלה למטופלות הראשונות שלך. ברגע שהן יחברו את עצמן באפליקציה, את תראי כאן את המסע שלהן בזמן אמת."
          />
        </div>
      </div>
    );
  }

  return (
    <div className="screen content-scroll">
      <PageHeader
        title={`${greeting}, אלעד`}
        subtitle={`${SJ_DATA.HEB_DAYS[new Date(SJ_DATA.NOW).getDay()]} · ${SJ_DATA.formatHebFull(SJ_DATA.NOW)}`}
        actions={
          <>
            <Button kind="secondary" icon="upload">ייצוא דוח חודשי</Button>
            <Button kind="primary" icon="plus" onClick={onBookAppointment}>קבע תור חדש</Button>
          </>
        }
      />

      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 28 }}>
        <KPI label="מטופלות פעילות" value={patients.length} icon="patients" trend={null}
             sparkData={[7, 7, 8, 8, 9, 9, 9, patients.length]} />
        <KPI label="תמונות השבוע" value={photosThisWeek} icon="camera"
             trend={trendDelta > 0 ? Math.round((trendDelta / Math.max(1, photosTrend[photosTrend.length - 2])) * 100) : trendDelta < 0 ? -8 : 0}
             sparkData={photosTrend} sparkColor="var(--coral-500)" />
        <KPI label="בקשות תור" value={pending.length} icon="appointments"
             sparkData={[2, 1, 3, 2, 2, 1, 2, pending.length]} />
        <KPI label="תורים היום" value={today.length} icon="calendar"
             sparkData={[3, 1, 2, 4, 2, 3, 1, today.length]} />
      </div>

      {/* Two-col layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24, alignItems: 'start' }}>
        {/* Left: needs attention + invite code + activity */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <Card flush>
            <div style={{ padding: '18px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--coral-400)' }} />
                <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700 }}>דורשות תשומת לב</h3>
                <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>{flagged.length}</span>
              </div>
              <button onClick={() => navigate({ name: 'patients', filter: 'attention' })}
                style={{ background: 'none', border: 'none', fontSize: 13, fontWeight: 600, color: 'var(--sage-700)', cursor: 'pointer' }}>
                לכל הרשימה ←
              </button>
            </div>
            {flagged.length === 0 ? (
              <div style={{ padding: '40px 22px', textAlign: 'center', color: 'var(--text-tertiary)', fontSize: 13 }}>
                הכל רגוע כרגע ✨
              </div>
            ) : flagged.map((p) => (
              <NeedsAttentionItem key={p.id} patient={p} reason={p.flagged}
                onClick={() => navigate({ name: 'patient', id: p.id })}
                onAction={() => p.flagged === 'pending-appointment' ? navigate({ name: 'appointments' }) : navigate({ name: 'patient', id: p.id })}
              />
            ))}
          </Card>

          <InviteCodeHero practitioner={SJ_DATA.PRACTITIONER} onCopy={onCopyCode} onShare={onCopyCode} />
        </div>

        {/* Right: upcoming + activity */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <Card flush>
            <div style={{ padding: '18px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700 }}>תורים קרובים</h3>
              <button onClick={() => navigate({ name: 'calendar' })}
                style={{ background: 'none', border: 'none', fontSize: 13, fontWeight: 600, color: 'var(--sage-700)', cursor: 'pointer' }}>
                ביומן ←
              </button>
            </div>
            {upcoming.slice(0, 4).map((a) => (
              <UpcomingItem key={a.id} appt={a} patient={SJ_DATA.byId(a.patient_id)}
                onClick={() => navigate({ name: 'patient', id: a.patient_id })} />
            ))}
          </Card>

          <Card>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
              <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700 }}>פעילות אחרונה</h3>
              <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>48 שעות אחרונות</span>
            </div>
            {SJ_DATA.ACTIVITY.slice(0, 5).map((a, i) => <ActivityRow key={i} item={a} />)}
          </Card>
        </div>
      </div>
    </div>
  );
}

window.OverviewScreen = OverviewScreen;
window.InviteCodeHero = InviteCodeHero;
