// 하루결 — 데이터 스토어 (localStorage) + 라우터 + 유틸

const K = {
  schedules: 'haru:schedules',
  meals:     'haru:meals',
  symptoms:  'haru:symptoms',
  questions: 'haru:questions',
  meds:      'haru:meds',
  checks:    'haru:checks',     // 오늘의 회복 체크
  mood:      'haru:mood',       // 오늘 컨디션
  profile:   'haru:profile',
  mode:      'haru:mode',       // 'patient' | 'caregiver'
  onboarded: 'haru:onboarded',
  exerciseLog: 'haru:exerciseLog',  // { 'YYYY-MM-DD': [exerciseId, ...] }
  labValues:   'haru:labValues',    // [{ id, termId, value, date }]
  goals:       'haru:goals',        // [{ id, title, cat, period, icon, done, completedAt, createdAt }]
  encShown:    'haru:encShown',     // 'YYYY-MM-DD' (마지막 응원 모달 본 날)
  encEnabled:  'haru:encEnabled',   // boolean - 응원 메시지 받기
  community:   'haru:community',    // [{ id, roomId, nick, body, ago, ts, isAI }]
  medsLog:     'haru:medsLog',      // { 'YYYY-MM-DD': { medId: { time: 'taken'|'skipped' } } }
  safety:      'haru:safety',       // { lastCheckIn, lastActiveAt, thresholdHours, alertedAt }
  buddies:     'haru:buddies',      // [{ id, nick, avatar, stage, birthday, addedAt }]
  buddyMsgs:   'haru:buddyMsgs',    // [{ id, buddyId, from, body, ts }]
};

// ── 기본 데이터 (앱 처음 실행 시) ──────────────────────────
const DEFAULTS = {
  profile: {
    name: '지은',
    diagnosis: '유방암',
    stage: 'II',                  // 0 / I / II / III / IV
    birthday: '1985-04-15',       // 생일
    chatNick: '봄을 기다리는',     // 커뮤니티 표시 이름
    chatAvatar: '🌸',              // 이모지 또는 base64 image URL
    cycle: 3,
    cycleTotal: 8,
    cycleStartDate: '2026-05-22', // 3차 투여일 기준 - 회복 6일차
    nextCycleDate: '2026-05-29',
    nextCycleTime: '10:30',
    hospital: '○○병원 종양내과',
    doctor: '김민서 교수',
    hospitalPhone: '02-1234-5678',
    caregiverName: '민호',
    caregiverPhone: '010-0000-0000',
  },
  schedules: [
    { id: 's1', title: '항암 3차 외래',  date: '2026-05-29', time: '10:30', dept: '종양내과',  memo: '혈액검사 결과 확인, 손발저림 상담', tag: '투여일',  tone: 'clay' },
    { id: 's2', title: '주사실 예약',    date: '2026-06-02', time: '09:00', dept: '항암주사실', memo: '보호자 동행, 간식과 물 준비',           tag: '준비물',  tone: 'sage' },
    { id: 's3', title: '영양 상담',       date: '2026-06-09', time: '14:00', dept: '영양팀',    memo: '최근 체중 변화와 식사 기록 지참',       tag: '체중기록', tone: 'honey' },
  ],
  meals: [
    { id: 'm1', date: '2026-05-27', time: '08:30', name: '닭죽',           type: '아침', amount: '½공기', memo: '먹을만했음',   tone: 'ok'  },
    { id: 'm2', date: '2026-05-27', time: '10:30', name: '두유 + 바나나',   type: '간식', amount: '1잔',   memo: '메스꺼움 적음', tone: 'ok'  },
    { id: 'm3', date: '2026-05-27', time: '12:30', name: '미음',           type: '점심', amount: '⅓공기', memo: '입맛 없음',    tone: 'low' },
  ],
  symptoms: [
    { id: 'y1', date: '2026-05-27', time: '14:20', name: '피로',     severity: 4, memo: '오후부터 누워있는 시간이 많음' },
    { id: 'y2', date: '2026-05-27', time: '09:10', name: '손발저림', severity: 3, memo: '손끝 저림 지속' },
    { id: 'y3', date: '2026-05-26', time: '20:30', name: '메스꺼움', severity: 2, memo: '저녁 식사 직후' },
    { id: 'y4', date: '2026-05-25', time: '07:00', name: '두통',     severity: 3, memo: '아침 공복 시' },
  ],
  questions: [
    { id: 'q1', topic: '손발저림이 점점 심해지는데, 약 용량을 조정할 수 있나요?', ctx: '항암 3일째부터 손끝 저림 지속',     cat: '부작용',     done: false, urgent: true },
    { id: 'q2', topic: '체중이 2주 만에 1.5kg 줄었어요. 영양제 추가가 필요할까요?', ctx: '식욕 저하 + 메스꺼움',           cat: '식사·체중',  done: false, urgent: false },
    { id: 'q3', topic: '항암 기간에 가벼운 운동은 어느 정도 괜찮나요?',           ctx: '하루 20분 정도 산책 중',           cat: '생활',        done: false, urgent: false },
    { id: 'q4', topic: '비타민D 영양제는 항암제와 같이 먹어도 되나요?',           ctx: '약사가 먹어도 된다고 했음',         cat: '약·상호작용', done: true,  urgent: false },
  ],
  meds: [
    { id: 'd1', name: '타목시펜 (Tamoxifen)',  dose: '20mg',  schedule: ['09:00'],          type: 'daily', kind: 'hormone',  tone: 'clay',  note: '항호르몬제. 매일 같은 시각에 한 알.' },
    { id: 'd2', name: '버제니오 (Abemaciclib)', dose: '150mg', schedule: ['08:00', '20:00'], type: 'daily', kind: 'targeted', tone: 'mist',  note: 'CDK4/6 억제제. 식사와 관계없이.' },
    { id: 'd3', name: '진통제',                  dose: '500mg', schedule: [],                  type: 'asneeded', kind: 'support', tone: 'honey', note: '통증 시 4시간 간격.' },
    { id: 'd4', name: '항구토제',               dose: '8mg',   schedule: ['08:00', '20:00'], type: 'daily', kind: 'support',  tone: 'sage',  note: '아침·저녁. 메스꺼움 예방.' },
  ],
  checks: {
    '2026-05-27': { water: true, protein: true, walk: false, log: false },
  },
  mood: {
    '2026-05-27': 'ok', // good | ok | hard | very-hard
  },
};

// ── store ──
const Store = {
  load(key, fb) {
    try { const v = localStorage.getItem(key); return v ? JSON.parse(v) : fb; }
    catch { return fb; }
  },
  save(key, v) { localStorage.setItem(key, JSON.stringify(v)); window.dispatchEvent(new Event('haru:change')); },
  reset() { Object.values(K).forEach(k => localStorage.removeItem(k)); window.location.hash = ''; window.location.reload(); },
};

// ── 초기화 (한 번만) ──
function initStore() {
  if (!localStorage.getItem(K.profile))   Store.save(K.profile,   DEFAULTS.profile);
  if (!localStorage.getItem(K.schedules)) Store.save(K.schedules, DEFAULTS.schedules);
  if (!localStorage.getItem(K.meals))     Store.save(K.meals,     DEFAULTS.meals);
  if (!localStorage.getItem(K.symptoms))  Store.save(K.symptoms,  DEFAULTS.symptoms);
  if (!localStorage.getItem(K.questions)) Store.save(K.questions, DEFAULTS.questions);
  if (!localStorage.getItem(K.meds))      Store.save(K.meds,      DEFAULTS.meds);
  if (!localStorage.getItem(K.checks))    Store.save(K.checks,    DEFAULTS.checks);
  if (!localStorage.getItem(K.mood))      Store.save(K.mood,      DEFAULTS.mood);
  if (!localStorage.getItem(K.mode))      Store.save(K.mode,      'patient');
  if (!localStorage.getItem(K.encEnabled)) Store.save(K.encEnabled, true);
  if (!localStorage.getItem(K.safety))     Store.save(K.safety, { lastCheckIn: new Date().toISOString(), lastActiveAt: new Date().toISOString(), thresholdHours: 24 });
  if (!localStorage.getItem(K.buddies))    Store.save(K.buddies, [
    { id: 'b1', nick: '봄을 기다리는', avatar: '🌸', stage: 'II', birthday: '1980-04-15', addedAt: '2026-04-10', lastSeen: '2시간 전' },
    { id: 'b2', nick: '회복 6일차',     avatar: '🌿', stage: 'II', birthday: '1975-05-30', addedAt: '2026-05-01', lastSeen: '어제' },
    { id: 'b3', nick: '책 읽는 회복기', avatar: '📚', stage: 'I',  birthday: '1982-11-05', addedAt: '2026-04-20', lastSeen: '1주 전' },
  ]);
  if (!localStorage.getItem(K.buddyMsgs))  Store.save(K.buddyMsgs, [
    { id: 'bm1', buddyId: 'b1', from: 'them', body: '오늘 컨디션 어떠세요? 저는 산책 다녀왔어요 :)', ts: Date.now() - 1000 * 60 * 60 * 6 },
    { id: 'bm2', buddyId: 'b1', from: 'me',   body: '저도 오늘은 좀 나은 편이에요. 같이 화이팅해요!',   ts: Date.now() - 1000 * 60 * 60 * 5 },
    { id: 'bm3', buddyId: 'b2', from: 'them', body: '항암 3차 잘 받으시고 푹 쉬세요. 응원합니다.',     ts: Date.now() - 1000 * 60 * 60 * 30 },
  ]);
}
initStore();

// ── 모든 데이터 hook ──
function useStore() {
  const [version, setVersion] = React.useState(0);
  React.useEffect(() => {
    const fn = () => setVersion(v => v + 1);
    window.addEventListener('haru:change', fn);
    window.addEventListener('storage', fn);
    return () => {
      window.removeEventListener('haru:change', fn);
      window.removeEventListener('storage', fn);
    };
  }, []);

  return {
    version,
    profile:   Store.load(K.profile,   DEFAULTS.profile),
    schedules: Store.load(K.schedules, DEFAULTS.schedules),
    meals:     Store.load(K.meals,     DEFAULTS.meals),
    symptoms:  Store.load(K.symptoms,  DEFAULTS.symptoms),
    questions: Store.load(K.questions, DEFAULTS.questions),
    meds:      Store.load(K.meds,      DEFAULTS.meds),
    checks:    Store.load(K.checks,    DEFAULTS.checks),
    mood:      Store.load(K.mood,      DEFAULTS.mood),
    mode:      Store.load(K.mode,      'patient'),
    exerciseLog: Store.load(K.exerciseLog, {}),
    labValues:   Store.load(K.labValues, []),
    goals:       Store.load(K.goals, []),
    encEnabled:  Store.load(K.encEnabled, true),
    community:   Store.load(K.community, []),
    medsLog:     Store.load(K.medsLog, {}),
    safety:      Store.load(K.safety, { lastCheckIn: new Date().toISOString(), lastActiveAt: new Date().toISOString(), thresholdHours: 24 }),
    buddies:     Store.load(K.buddies, []),
    buddyMsgs:   Store.load(K.buddyMsgs, []),

    checkIn: () => {
      const cur = Store.load(K.safety, {});
      Store.save(K.safety, { ...cur, lastCheckIn: new Date().toISOString(), lastActiveAt: new Date().toISOString(), alertedAt: null });
    },
    touch: () => {
      const cur = Store.load(K.safety, {});
      Store.save(K.safety, { ...cur, lastActiveAt: new Date().toISOString() });
    },
    setSafety: (patch) => Store.save(K.safety, { ...Store.load(K.safety, {}), ...patch }),

    addBuddy: (b) => Store.save(K.buddies, [...Store.load(K.buddies, []), { ...b, id: 'b' + Date.now(), addedAt: todayISO() }]),
    removeBuddy: (id) => {
      Store.save(K.buddies, Store.load(K.buddies, []).filter(b => b.id !== id));
      Store.save(K.buddyMsgs, Store.load(K.buddyMsgs, []).filter(m => m.buddyId !== id));
    },
    sendBuddyMsg: (buddyId, body) => {
      const list = Store.load(K.buddyMsgs, []);
      Store.save(K.buddyMsgs, [...list, { id: 'bm' + Date.now(), buddyId, from: 'me', body, ts: Date.now() }]);
    },
    receiveBuddyMsg: (buddyId, body) => {
      const list = Store.load(K.buddyMsgs, []);
      Store.save(K.buddyMsgs, [...list, { id: 'bm' + Date.now(), buddyId, from: 'them', body, ts: Date.now() }]);
    },

    addMed: (m) => Store.save(K.meds, [...Store.load(K.meds, []), { ...m, id: 'd' + Date.now() }]),
    updateMed: (id, patch) => Store.save(K.meds, Store.load(K.meds, []).map(m => m.id === id ? { ...m, ...patch } : m)),
    removeMed: (id) => Store.save(K.meds, Store.load(K.meds, []).filter(m => m.id !== id)),

    setMedTaken: (date, medId, time, status) => {
      const log = Store.load(K.medsLog, {});
      const day = log[date] || {};
      const key = `${medId}|${time}`;
      Store.save(K.medsLog, { ...log, [date]: { ...day, [key]: status } });
    },

    setMode: (m) => Store.save(K.mode, m),
    setProfile: (p) => Store.save(K.profile, p),

    addSchedule: (s) => {
      const list = Store.load(K.schedules, []);
      Store.save(K.schedules, [...list, { ...s, id: 's' + Date.now() }].sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time)));
    },
    removeSchedule: (id) => Store.save(K.schedules, Store.load(K.schedules, []).filter(s => s.id !== id)),

    addMeal: (m) => Store.save(K.meals, [{ ...m, id: 'm' + Date.now() }, ...Store.load(K.meals, [])]),
    removeMeal: (id) => Store.save(K.meals, Store.load(K.meals, []).filter(m => m.id !== id)),

    addSymptom: (y) => Store.save(K.symptoms, [{ ...y, id: 'y' + Date.now() }, ...Store.load(K.symptoms, [])]),
    removeSymptom: (id) => Store.save(K.symptoms, Store.load(K.symptoms, []).filter(s => s.id !== id)),

    addQuestion: (q) => Store.save(K.questions, [{ ...q, id: 'q' + Date.now(), done: false, urgent: false }, ...Store.load(K.questions, [])]),
    toggleQuestion: (id) => {
      const list = Store.load(K.questions, []);
      Store.save(K.questions, list.map(q => q.id === id ? { ...q, done: !q.done } : q));
    },
    removeQuestion: (id) => Store.save(K.questions, Store.load(K.questions, []).filter(q => q.id !== id)),

    setCheck: (date, key, value) => {
      const all = Store.load(K.checks, {});
      const day = all[date] || {};
      Store.save(K.checks, { ...all, [date]: { ...day, [key]: value } });
    },
    setMood: (date, value) => {
      const all = Store.load(K.mood, {});
      Store.save(K.mood, { ...all, [date]: value });
    },

    reset: Store.reset,
  };
}

// ── 날짜 유틸 ──
const todayISO = () => {
  // 데모용 고정 날짜
  return '2026-05-27';
};
const nowHM = () => {
  const d = new Date();
  return `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
};
const fmtDateKR = (iso) => {
  const d = new Date(iso + 'T00:00:00');
  return new Intl.DateTimeFormat('ko-KR', { month: 'long', day: 'numeric', weekday: 'short' }).format(d);
};
const fmtMonth  = (iso) => {
  const d = new Date(iso + 'T00:00:00');
  return new Intl.DateTimeFormat('ko-KR', { month: 'numeric' }).format(d).replace('월','월 ') + d.getDate() + '일';
};
const daysBetween = (a, b) => {
  const A = new Date(a + 'T00:00:00');
  const B = new Date(b + 'T00:00:00');
  return Math.round((B - A) / 86400000);
};

// ── 라우터 ──
function useRoute() {
  const [hash, setHash] = React.useState(() => window.location.hash.slice(1) || 'home');
  React.useEffect(() => {
    const fn = () => setHash(window.location.hash.slice(1) || 'home');
    window.addEventListener('hashchange', fn);
    return () => window.removeEventListener('hashchange', fn);
  }, []);
  return [hash, (next) => { window.location.hash = next; window.scrollTo(0, 0); const el = document.querySelector('.hg-app__scroll'); if (el) el.scrollTop = 0; }];
}

// ── 토스트 ──
function showToast(msg) {
  const t = document.createElement('div');
  t.className = 'hg-toast';
  t.textContent = msg;
  document.body.appendChild(t);
  setTimeout(() => t.remove(), 1900);
}

Object.assign(window, { K, Store, useStore, useRoute, todayISO, nowHM, fmtDateKR, fmtMonth, daysBetween, showToast, DEFAULTS });
