// SkinJourney Dashboard — fixtures
// Realistic small-clinic dataset: 10 patients, mixed cadence, 5 appointments
// of various statuses, 3 patients flagged for attention.

const SKIN_TYPES = {
  oily: 'שמנוני',
  dry: 'יבש',
  combination: 'מעורב',
  normal: 'רגיל',
  sensitive: 'רגיש',
};
const FOCUS_LABELS = {
  acne: 'אקנה',
  pigmentation: 'פיגמנטציה',
  texture: 'מרקם',
  redness: 'אדמומיות',
  scars: 'צלקות',
  prevention: 'מניעה',
};
const ANGLE_LABELS = { front: 'חזית', right: 'צד ימין', left: 'צד שמאל' };

// ── Helpers ───────────────────────────────────────────────────────────────
const NOW = new Date('2026-06-06T10:00:00');
const daysAgo = (n) => new Date(NOW.getTime() - n * 86400000);
const iso = (d) => d.toISOString();

// Hebrew dates — short like "29 אפר׳", "6 יוני"
const HEB_MONTHS_SHORT = [
  'ינו׳','פבר׳','מרץ','אפר׳','מאי','יוני','יולי','אוג׳','ספט׳','אוק׳','נוב׳','דצמ׳'
];
const HEB_MONTHS_FULL = [
  'ינואר','פברואר','מרץ','אפריל','מאי','יוני','יולי','אוגוסט','ספטמבר','אוקטובר','נובמבר','דצמבר'
];
const HEB_DAYS = ['ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת'];
const HEB_DAYS_SHORT = ['א׳','ב׳','ג׳','ד׳','ה׳','ו׳','שבת'];

function formatHebShort(date) {
  const d = typeof date === 'string' ? new Date(date) : date;
  return `${d.getDate()} ${HEB_MONTHS_SHORT[d.getMonth()]}`;
}
function formatHebFull(date) {
  const d = typeof date === 'string' ? new Date(date) : date;
  return `${d.getDate()} ב${HEB_MONTHS_FULL[d.getMonth()]} ${d.getFullYear()}`;
}
function formatHebTime(date) {
  const d = typeof date === 'string' ? new Date(date) : date;
  return d.toTimeString().slice(0, 5);
}
function formatRelativeHe(date) {
  const d = typeof date === 'string' ? new Date(date) : date;
  const diff = Math.floor((NOW - d) / 86400000);
  if (diff === 0) return 'היום';
  if (diff === 1) return 'אתמול';
  if (diff < 7) return `לפני ${diff} ימים`;
  if (diff < 14) return 'לפני שבוע';
  if (diff < 30) return `לפני ${Math.floor(diff / 7)} שבועות`;
  if (diff < 60) return 'לפני חודש';
  return `לפני ${Math.floor(diff / 30)} חודשים`;
}
function weeksBetween(a, b) {
  const da = typeof a === 'string' ? new Date(a) : a;
  const db = typeof b === 'string' ? new Date(b) : b;
  return Math.max(1, Math.round(Math.abs(db - da) / (7 * 86400000)));
}

// ── Practitioner ──────────────────────────────────────────────────────────
const PRACTITIONER = {
  id: 'prac-1',
  name: 'אלעד לוי',
  clinic_name: 'מרפאת אור — תל אביב',
  invite_code: 'SJ-7K2M9P',
  email: 'elad@orclinic.co.il',
};

// ── Patients ──────────────────────────────────────────────────────────────
// Each patient has a generated weekly photo cadence (frontmost-recent date,
// total count, weekly-uploaded series for the sparkline).
const PATIENTS = [
  {
    id: 'p-1', name: 'מאיה לוין', age: 24, skin_type: 'oily',
    focus: ['acne', 'scars'], joined_days_ago: 84,
    weekly: [3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 2, 3], // 12 weeks
    note_last: 'התחילה Adapalene 0.1%, הגיבה היטב', flagged: null,
  },
  {
    id: 'p-2', name: 'נועה שטרן', age: 19, skin_type: 'oily',
    focus: ['acne', 'redness'], joined_days_ago: 56,
    weekly: [3, 3, 3, 3, 3, 3, 3, 2], note_last: 'מגמה חיובית — אדמומיות פחתה',
    flagged: null,
  },
  {
    id: 'p-3', name: 'תמר אבני', age: 32, skin_type: 'combination',
    focus: ['pigmentation', 'texture'], joined_days_ago: 154,
    weekly: [3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3],
    note_last: 'משלבת רטינול, התקדמות נראית בתמונות 4 שבועות אחרונים',
    flagged: null,
  },
  {
    id: 'p-4', name: 'יעל גלעדי', age: 28, skin_type: 'sensitive',
    focus: ['redness', 'prevention'], joined_days_ago: 42,
    weekly: [3, 3, 3, 3, 3, 3], note_last: '',
    flagged: null,
  },
  {
    id: 'p-5', name: 'שירה כהן', age: 22, skin_type: 'normal',
    focus: ['acne'], joined_days_ago: 21,
    weekly: [3, 3, 3], note_last: 'שבוע ראשון — בסיס תיעוד תקין',
    flagged: null,
  },
  // Flagged patients
  {
    id: 'p-6', name: 'דנה ברק', age: 35, skin_type: 'dry',
    focus: ['texture', 'prevention'], joined_days_ago: 119,
    weekly: [3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 2, 0, 0, 0, 0, 0, 0],
    note_last: '', flagged: 'no-upload', // 18 days since last upload
  },
  {
    id: 'p-7', name: 'הילה אברהם', age: 26, skin_type: 'combination',
    focus: ['acne', 'pigmentation'], joined_days_ago: 49,
    weekly: [3, 3, 3, 3, 3, 3, 3], note_last: 'ביקשה תור חדש',
    flagged: 'pending-appointment',
  },
  {
    id: 'p-8', name: 'אביגיל מרום', age: 30, skin_type: 'oily',
    focus: ['acne', 'redness'], joined_days_ago: 35,
    weekly: [3, 3, 3, 3, 3], note_last: '',
    flagged: 'cancelled',
  },
  {
    id: 'p-9', name: 'רוני שרון', age: 41, skin_type: 'combination',
    focus: ['texture', 'pigmentation'], joined_days_ago: 196,
    weekly: [3, 2, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3],
    note_last: 'התקדמות מצוינת לאורך 6 חודשים', flagged: null,
  },
  {
    id: 'p-10', name: 'אלינור פז', age: 17, skin_type: 'oily',
    focus: ['acne'], joined_days_ago: 63,
    weekly: [3, 3, 3, 3, 3, 3, 3, 3, 2],
    note_last: 'אם מצטרפת לפגישה הבאה', flagged: null,
  },
];

// Compute derived fields
PATIENTS.forEach((p) => {
  p.photo_count = p.weekly.reduce((s, n) => s + n, 0);
  p.weeks_tracked = p.weekly.length;
  // last upload was the end of the last non-zero week (in days ago)
  let trailingZero = 0;
  for (let i = p.weekly.length - 1; i >= 0; i--) {
    if (p.weekly[i] === 0) trailingZero++; else break;
  }
  p.last_upload_days_ago = trailingZero * 7 + 2;
  p.last_upload = daysAgo(p.last_upload_days_ago).toISOString();
  p.joined_at = daysAgo(p.joined_days_ago).toISOString();
  p.initial = p.name[0];
  p.focus_labels = p.focus.map((k) => FOCUS_LABELS[k]);
  p.skin_label = SKIN_TYPES[p.skin_type];
});

// ── Appointments ──────────────────────────────────────────────────────────
const APPOINTMENTS = [
  // Pending requests (2)
  {
    id: 'a-1', patient_id: 'p-7', scheduled_at: iso(daysAgo(-3).setHours ? (() => { const d = daysAgo(-3); d.setHours(15, 0, 0, 0); return d; })() : daysAgo(-3)),
    status: 'pending',
    patient_note: 'אפשר אחרי 15:00 בבקשה — אני עם הילדים עד אז.',
    requested_at: iso(daysAgo(0.5)),
  },
  {
    id: 'a-2', patient_id: 'p-2', scheduled_at: iso((() => { const d = daysAgo(-5); d.setHours(11, 30, 0, 0); return d; })()),
    status: 'pending', patient_note: '', requested_at: iso(daysAgo(1)),
  },
  // Confirmed upcoming (3)
  {
    id: 'a-3', patient_id: 'p-1', scheduled_at: iso((() => { const d = new Date(NOW); d.setHours(14, 0, 0, 0); return d; })()),
    status: 'confirmed', patient_note: '', practitioner_note: 'מעקב חודש שלישי — בדיקת הסתגלות לרטינואיד',
  },
  {
    id: 'a-4', patient_id: 'p-3', scheduled_at: iso((() => { const d = new Date(NOW); d.setHours(16, 30, 0, 0); return d; })()),
    status: 'confirmed', patient_note: '', practitioner_note: '',
  },
  {
    id: 'a-5', patient_id: 'p-9', scheduled_at: iso((() => { const d = daysAgo(-2); d.setHours(10, 0, 0, 0); return d; })()),
    status: 'confirmed', patient_note: '', practitioner_note: 'פילינג עדין',
  },
  {
    id: 'a-6', patient_id: 'p-4', scheduled_at: iso((() => { const d = daysAgo(-7); d.setHours(13, 0, 0, 0); return d; })()),
    status: 'confirmed', patient_note: '', practitioner_note: '',
  },
  // Cancelled by patient in last 14 days (1)
  {
    id: 'a-7', patient_id: 'p-8', scheduled_at: iso((() => { const d = daysAgo(3); d.setHours(11, 0, 0, 0); return d; })()),
    status: 'cancelled', cancelled_by: 'patient', cancelled_at: iso(daysAgo(4)),
    patient_note: 'מצטערת, חולה. אקבע מחדש בשבוע הבא.',
  },
];

// ── Clinical notes (per patient) ──────────────────────────────────────────
const NOTES = {
  'p-1': [
    { id: 'n1', date: iso(daysAgo(7)), body: 'מעקב — אדמומיות פחתה משמעותית. ממשיכה Adapalene 0.1% פעם ביום + לחות.', treatment: 'Adapalene 0.1%', visit: true },
    { id: 'n2', date: iso(daysAgo(35)), body: 'התחלת טיפול. הסבר על תהליך ההסתגלות (purge phase).', treatment: 'Adapalene 0.1%', visit: true },
    { id: 'n3', date: iso(daysAgo(70)), body: 'פגישה ראשונה — סקירת הסטוריה, מטרות.', visit: true },
  ],
  'p-3': [
    { id: 'n4', date: iso(daysAgo(14)), body: 'הוספת ויטמין C בבוקר. מרקם משתפר.', treatment: 'Vitamin C 15% + Retinol PM' },
    { id: 'n5', date: iso(daysAgo(56)), body: 'התחלת רטינול 0.3% במשולב עם פילינגים קלים.', visit: true },
  ],
  'p-9': [
    { id: 'n6', date: iso(daysAgo(21)), body: 'התקדמות מצוינת — שינוי גלוי בתמונות לפני/אחרי. ממליצה להמשיך בשגרה.', visit: true },
  ],
};

// ── Activity feed (recent uploads + actions) ──────────────────────────────
const ACTIVITY = [
  { type: 'upload', patient_id: 'p-1', at: iso(daysAgo(0.3)), text: '3 תמונות חדשות (חזית, ימין, שמאל)' },
  { type: 'upload', patient_id: 'p-5', at: iso(daysAgo(0.9)), text: '3 תמונות חדשות' },
  { type: 'upload', patient_id: 'p-3', at: iso(daysAgo(1.2)), text: '3 תמונות חדשות' },
  { type: 'connected', patient_id: 'p-5', at: iso(daysAgo(21)), text: 'הצטרפה למרפאה' },
  { type: 'upload', patient_id: 'p-9', at: iso(daysAgo(2)), text: '2 תמונות חדשות' },
  { type: 'upload', patient_id: 'p-2', at: iso(daysAgo(2.3)), text: '3 תמונות חדשות' },
];

// ── Photo timeline (per patient, last N weeks) ────────────────────────────
// Each cell: {angle, available, week_label, week_index, date}
function buildTimeline(patient) {
  const weeks = patient.weekly;
  const result = [];
  for (let w = 0; w < weeks.length; w++) {
    const weekIndex = w + 1;
    const filled = weeks[w]; // 0..3
    const angles = ['front', 'right', 'left'];
    const date = daysAgo((weeks.length - w - 1) * 7 + 2);
    for (let i = 0; i < 3; i++) {
      result.push({
        week: weekIndex,
        angle: angles[i],
        date: iso(date),
        date_short: formatHebShort(date),
        available: i < filled,
      });
    }
  }
  return result;
}

// Export
window.SJ_DATA = {
  PRACTITIONER, PATIENTS, APPOINTMENTS, NOTES, ACTIVITY,
  SKIN_TYPES, FOCUS_LABELS, ANGLE_LABELS,
  NOW, daysAgo, iso,
  formatHebShort, formatHebFull, formatHebTime, formatRelativeHe, weeksBetween,
  HEB_MONTHS_FULL, HEB_MONTHS_SHORT, HEB_DAYS, HEB_DAYS_SHORT,
  buildTimeline,
  byId(id) { return PATIENTS.find((p) => p.id === id); },
  patientsOf(ids) { return ids.map((id) => PATIENTS.find((p) => p.id === id)).filter(Boolean); },
};
