// SkinJourney Dashboard — Patient detail
// Hero · Before/After with date picker + slider · Weekly timeline · Notes · Appointments
const { useState: useS_pd, useMemo: useM_pd, useRef: useR_pd } = React;

function StatBox({ label, value, suffix }) {
  return (
    <div style={{
      background: 'var(--surface-sunken)', padding: '14px 16px',
      borderRadius: 'var(--radius-md)', flex: 1, minWidth: 0,
    }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase' }}>{label}</div>
      <div className="tabular" style={{ fontSize: 22, fontWeight: 700, color: 'var(--text-primary)', marginTop: 2, lineHeight: 1.1 }}>
        {value}{suffix && <span style={{ fontSize: 13, color: 'var(--text-tertiary)', fontWeight: 600, marginInlineStart: 4 }}>{suffix}</span>}
      </div>
    </div>
  );
}

/* ── Before/After: side-by-side OR draggable slider ─────────────────── */
function ComparisonView({ leftPhoto, rightPhoto, mode }) {
  const [pos, setPos] = useS_pd(50);
  const rootRef = useR_pd(null);

  if (mode === 'slider') {
    return (
      <div
        ref={rootRef}
        style={{
          position: 'relative',
          height: 380, width: '100%',
          borderRadius: 'var(--radius-xl)', overflow: 'hidden',
          background: 'var(--sand-200)',
          cursor: 'ew-resize',
          userSelect: 'none',
        }}
        onMouseMove={(e) => {
          if (e.buttons !== 1) return;
          const r = rootRef.current.getBoundingClientRect();
          const x = e.clientX - r.left;
          setPos(Math.max(0, Math.min(100, (x / r.width) * 100)));
        }}
        onClick={(e) => {
          const r = rootRef.current.getBoundingClientRect();
          setPos(Math.max(0, Math.min(100, ((e.clientX - r.left) / r.width) * 100)));
        }}
      >
        <PhotoSlot {...leftPhoto} size="xl" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', borderRadius: 0 }} />
        <div style={{ position: 'absolute', inset: 0, clipPath: `inset(0 ${100 - pos}% 0 0)` }}>
          <PhotoSlot {...rightPhoto} size="xl" style={{ width: '100%', height: '100%', borderRadius: 0 }} />
        </div>
        <div style={{
          position: 'absolute', top: 0, bottom: 0, left: `${pos}%`,
          width: 3, background: 'white', transform: 'translateX(-50%)',
          boxShadow: '0 0 12px rgba(0,0,0,0.3)',
        }}>
          <div style={{
            position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
            width: 38, height: 38, borderRadius: '50%',
            background: 'white', boxShadow: 'var(--elev-3)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--sage-700)',
          }}>
            <Icon name="chevron_left" size={14} />
            <Icon name="chevron_right" size={14} style={{ marginInlineStart: -4 }} />
          </div>
        </div>
        <div style={{
          position: 'absolute', top: 14, insetInlineStart: 14,
          background: 'rgba(22,29,31,0.6)', color: 'white',
          padding: '4px 10px', borderRadius: 999,
          fontSize: 11, fontWeight: 700,
        }}>אחרי · {rightPhoto.date}</div>
        <div style={{
          position: 'absolute', top: 14, insetInlineEnd: 14,
          background: 'rgba(22,29,31,0.6)', color: 'white',
          padding: '4px 10px', borderRadius: 999,
          fontSize: 11, fontWeight: 700,
        }}>לפני · {leftPhoto.date}</div>
      </div>
    );
  }

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
      <div>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>
          לפני · {leftPhoto.date}
        </div>
        <PhotoSlot {...leftPhoto} size="xl" />
      </div>
      <div>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--sage-700)', letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>
          אחרי · {rightPhoto.date}
        </div>
        <PhotoSlot {...rightPhoto} size="xl" />
      </div>
    </div>
  );
}

function ComparisonModule({ patient, timeline }) {
  const [angle, setAngle] = useS_pd('front');
  const [mode, setMode] = useS_pd('side');

  const photos = timeline.filter((c) => c.angle === angle && c.available);
  const [leftIdx, setLeftIdx] = useS_pd(0);
  const [rightIdx, setRightIdx] = useS_pd(Math.max(0, photos.length - 1));

  if (photos.length < 2) {
    return (
      <Card>
        <h3 style={{ margin: '0 0 12px', fontSize: 16, fontWeight: 700 }}>השוואה לפני / אחרי</h3>
        <Empty icon="camera" title="צריך לפחות שתי תמונות" body="ההשוואה תהיה זמינה ברגע שיהיו יותר תמונות בזווית זו." />
      </Card>
    );
  }

  const left = photos[Math.min(leftIdx, photos.length - 1)];
  const right = photos[Math.min(rightIdx, photos.length - 1)];

  return (
    <Card>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, gap: 16, flexWrap: 'wrap' }}>
        <div>
          <h3 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>השוואה לפני / אחרי</h3>
          <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--text-tertiary)' }}>
            בחרי שתי תמונות כדי לראות את ההתקדמות
          </p>
        </div>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <Segmented value={angle} onChange={(a) => { setAngle(a); setLeftIdx(0); }} options={[
            { value: 'front', label: 'חזית' },
            { value: 'right', label: 'ימין' },
            { value: 'left', label: 'שמאל' },
          ]} />
          <Segmented value={mode} onChange={setMode} options={[
            { value: 'side', label: 'זו לצד זו' },
            { value: 'slider', label: 'סליידר' },
          ]} />
        </div>
      </div>

      <ComparisonView
        leftPhoto={{ angle, date: left.date_short, week: left.week }}
        rightPhoto={{ angle, date: right.date_short, week: right.week }}
        mode={mode}
      />

      {/* Date picker strip */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
        marginTop: 18, padding: '14px 16px',
        background: 'var(--surface-sunken)', borderRadius: 'var(--radius-md)',
      }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>
            תמונת התחלה
          </div>
          <select className="select" value={leftIdx} onChange={(e) => setLeftIdx(+e.target.value)}>
            {photos.map((p, i) => (
              <option key={i} value={i}>שבוע {p.week} · {p.date_short}</option>
            ))}
          </select>
        </div>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>
            תמונת סיום
          </div>
          <select className="select" value={rightIdx} onChange={(e) => setRightIdx(+e.target.value)}>
            {photos.map((p, i) => (
              <option key={i} value={i}>שבוע {p.week} · {p.date_short}</option>
            ))}
          </select>
        </div>
      </div>
    </Card>
  );
}

/* ── Weekly timeline ribbon ─────────────────────────────────────────── */
function WeeklyTimeline({ patient, timeline }) {
  const weeks = useM_pd(() => {
    const map = new Map();
    timeline.forEach((c) => {
      if (!map.has(c.week)) map.set(c.week, { week: c.week, date: c.date_short, cells: [] });
      map.get(c.week).cells.push(c);
    });
    return [...map.values()].sort((a, b) => b.week - a.week);
  }, [timeline]);

  return (
    <Card>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <h3 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>ציר זמן שבועי</h3>
          <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--text-tertiary)' }}>
            {patient.weeks_tracked} שבועות של תיעוד
          </p>
        </div>
        <Segmented value="grid" onChange={() => {}} options={[
          { value: 'grid', label: 'רשת' },
          { value: 'list', label: 'רשימה' },
        ]} />
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {weeks.slice(0, 6).map((w, i) => (
          <div key={w.week} style={{
            display: 'grid',
            gridTemplateColumns: '90px repeat(3, 1fr)',
            gap: 12, alignItems: 'center',
            padding: '12px 0',
            borderBottom: i < Math.min(5, weeks.length - 1) ? '1px solid var(--border-subtle)' : 'none',
          }}>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase' }}>
                שבוע {w.week}
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)', marginTop: 2 }}>{w.date}</div>
            </div>
            {w.cells.map((c, j) => (
              <PhotoSlot key={j} angle={c.angle} date={c.date_short} week={c.week}
                         available={c.available} size="sm"
                         style={{ width: '100%', height: 110 }} />
            ))}
          </div>
        ))}
      </div>

      {weeks.length > 6 && (
        <div style={{ marginTop: 12, textAlign: 'center' }}>
          <Button kind="ghost" size="sm">הצגת עוד {weeks.length - 6} שבועות</Button>
        </div>
      )}
    </Card>
  );
}

/* ── Clinical notes (NEW) ───────────────────────────────────────────── */
function ClinicalNotes({ patient }) {
  const [notes, setNotes] = useS_pd(SJ_DATA.NOTES[patient.id] || []);
  const [draft, setDraft] = useS_pd('');
  const [treatment, setTreatment] = useS_pd('');
  const toast = useToast();

  const add = () => {
    if (!draft.trim()) return;
    const n = {
      id: `n-${Date.now()}`,
      date: new Date(SJ_DATA.NOW).toISOString(),
      body: draft, treatment: treatment.trim() || undefined,
    };
    setNotes([n, ...notes]);
    setDraft(''); setTreatment('');
    toast.push('הוספת רשומה קלינית');
  };

  return (
    <Card flush>
      <div style={{ padding: '20px 22px', borderBottom: '1px solid var(--border-subtle)' }}>
        <h3 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>תיק קליני</h3>
        <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--text-tertiary)' }}>
          טיפולים, מוצרים והערות מפגישות
        </p>
      </div>

      {/* Composer */}
      <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--border-subtle)', background: 'var(--sand-100)' }}>
        <textarea
          className="textarea"
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          placeholder="הוסיפי הערה — לדוגמה: ׳התחלנו רטינואיד 0.025%, להמתין שבועיים לפני העלאת תדירות.׳"
          style={{ marginBottom: 10, background: 'var(--surface-elevated)' }}
        />
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <input
            className="input"
            value={treatment}
            onChange={(e) => setTreatment(e.target.value)}
            placeholder="טיפול / מוצר (אופציונלי)"
            style={{ flex: 1, background: 'var(--surface-elevated)' }}
          />
          <Button kind="primary" icon="plus" onClick={add}>הוספה</Button>
        </div>
      </div>

      {/* Timeline */}
      {notes.length === 0 ? (
        <Empty icon="note" title="אין רשומות עדיין" body="רשומות שתוסיפי יופיעו כאן בסדר כרונולוגי הפוך." />
      ) : (
        <div style={{ position: 'relative', padding: '24px 22px' }}>
          {/* Spine */}
          <div style={{
            position: 'absolute', top: 28, bottom: 28,
            insetInlineEnd: 28, width: 2, background: 'var(--border-subtle)',
          }} />
          {notes.map((n, i) => (
            <div key={n.id} style={{
              position: 'relative', display: 'flex',
              gap: 18, marginBottom: 22,
            }}>
              <div style={{ flex: 1, minWidth: 0, paddingInlineEnd: 40 }}>
                <div style={{ fontSize: 12, color: 'var(--text-tertiary)', fontWeight: 600, marginBottom: 4 }}>
                  {SJ_DATA.formatHebFull(n.date)} · {SJ_DATA.formatRelativeHe(n.date)}
                </div>
                <p style={{ margin: '0 0 8px', fontSize: 14, color: 'var(--text-primary)', lineHeight: 1.6 }}>{n.body}</p>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {n.treatment && <Chip kind="coral">{n.treatment}</Chip>}
                  {n.visit && <Chip><Icon name="check" size={10} /> פגישה במרפאה</Chip>}
                </div>
              </div>
              <div style={{
                width: 12, height: 12, borderRadius: '50%',
                background: i === 0 ? 'var(--sage-600)' : 'var(--surface)',
                border: '2px solid var(--sage-600)',
                position: 'relative', insetInlineEnd: 22,
                marginTop: 6, flexShrink: 0,
              }} />
            </div>
          ))}
        </div>
      )}
    </Card>
  );
}

/* ── Patient appointments mini list ─────────────────────────────────── */
function PatientAppointments({ patient }) {
  const appts = SJ_DATA.APPOINTMENTS.filter((a) => a.patient_id === patient.id)
    .sort((a, b) => new Date(b.scheduled_at) - new Date(a.scheduled_at));
  return (
    <Card flush>
      <div style={{ padding: '20px 22px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <h3 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>תורים</h3>
        <Button kind="ghost" size="sm" icon="plus">תור חדש</Button>
      </div>
      {appts.length === 0
        ? <Empty icon="calendar" title="אין תורים עדיין" />
        : appts.map((a) => {
            const d = new Date(a.scheduled_at);
            const kind = a.status === 'confirmed' ? 'success' : a.status === 'pending' ? 'coral' : 'warning';
            const statusLabel = a.status === 'confirmed' ? 'מאושר' : a.status === 'pending' ? 'ממתין' : 'בוטל';
            return (
              <div key={a.id} style={{
                display: 'flex', alignItems: 'center', gap: 14,
                padding: '14px 22px', borderBottom: '1px solid var(--border-subtle)',
              }}>
                <div style={{
                  width: 48, padding: '6px 4px',
                  textAlign: 'center', background: 'var(--surface-sunken)',
                  borderRadius: 10,
                }}>
                  <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-tertiary)' }}>
                    {SJ_DATA.HEB_MONTHS_SHORT[d.getMonth()]}
                  </div>
                  <div className="tabular" style={{ fontSize: 15, fontWeight: 700 }}>{d.getDate()}</div>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>
                    <span className="tabular ltr-run">{SJ_DATA.formatHebTime(d)}</span>
                    {a.practitioner_note && <span style={{ color: 'var(--text-secondary)', fontWeight: 400 }}> · {a.practitioner_note}</span>}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 }}>
                    {SJ_DATA.formatRelativeHe(a.scheduled_at)}
                  </div>
                </div>
                <Chip kind={kind}>{statusLabel}</Chip>
              </div>
            );
          })}
    </Card>
  );
}

/* ── Patient screen ─────────────────────────────────────────────────── */
function PatientScreen({ route, navigate, onBookAppointment }) {
  const patient = SJ_DATA.byId(route.id);
  const timeline = useM_pd(() => SJ_DATA.buildTimeline(patient), [patient]);
  const toast = useToast();

  if (!patient) {
    return <div className="screen content-scroll"><Empty icon="patients" title="מטופלת לא נמצאה" /></div>;
  }

  return (
    <div className="screen content-scroll">
      {/* Crumb */}
      <button onClick={() => navigate({ name: 'patients' })}
              style={{ background: 'none', border: 'none', color: 'var(--text-tertiary)', fontSize: 13, fontWeight: 600, cursor: 'pointer', marginBottom: 16, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
        <Icon name="arrow_right" size={14} />
        חזרה לרשימת המטופלות
      </button>

      {/* Hero */}
      <Card style={{ marginBottom: 24, padding: 28 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 24, alignItems: 'flex-start' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 20 }}>
            <Avatar name={patient.name} size="xl" />
            <div style={{ minWidth: 0 }}>
              <h1 style={{ margin: 0, fontSize: 30, fontWeight: 700, letterSpacing: '-0.4px' }}>{patient.name}</h1>
              <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
                <Chip kind="neutral">בת {patient.age}</Chip>
                <Chip>עור {patient.skin_label}</Chip>
                {patient.focus_labels.map((f) => <Chip key={f} kind="coral">{f}</Chip>)}
              </div>
              <p style={{ margin: '12px 0 0', fontSize: 13, color: 'var(--text-tertiary)' }}>
                במרפאה {SJ_DATA.formatRelativeHe(patient.joined_at).replace('לפני ', '')} · אחרון: {SJ_DATA.formatRelativeHe(patient.last_upload)}
              </p>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <Button kind="secondary" icon="plus" onClick={onBookAppointment}>קביעת תור</Button>
            <Button kind="accent" icon="pdf" onClick={() => { navigate({ name: 'report', id: patient.id }); }}>ייצוא PDF</Button>
            <IconButton icon="more" />
          </div>
        </div>

        {/* Stats row */}
        <div style={{ display: 'flex', gap: 12, marginTop: 24 }}>
          <StatBox label="תמונות" value={patient.photo_count} />
          <StatBox label="שבועות עקבים" value={patient.weeks_tracked} suffix="שבועות" />
          <StatBox label="זוויות צילום" value={3} />
          <StatBox label="עדכון אחרון" value={SJ_DATA.formatHebShort(patient.last_upload)} />
        </div>
      </Card>

      <ComparisonModule patient={patient} timeline={timeline} />

      <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24, alignItems: 'start' }}>
        <WeeklyTimeline patient={patient} timeline={timeline} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <PatientAppointments patient={patient} />
          <ClinicalNotes patient={patient} />
        </div>
      </div>
    </div>
  );
}

window.PatientScreen = PatientScreen;
