// ──────────────────────────────────────────────────────────────────
// Data layer for 타전(TAJEON)
//
// Two backends behind one API:
//   • localStorage  — works immediately, single-device demo (multi-tab sync)
//   • Firebase      — real-time, two-device. Auto-enabled when window.FIREBASE_CONFIG exists.
//
// Shape:
//   rooms/{roomId}/state            { currentVol, members, createdAt }
//   rooms/{roomId}/telegrams/{id}   { text, from, time, vol }
//   rooms/{roomId}/volumes/{volId}  { label, period, count, telegrams[], cover, title, closedAt }
// ──────────────────────────────────────────────────────────────────

const LS_KEY = 'tajeon.local.v1';

const nowISO = () => new Date().toISOString();
const fmtTime = (iso) => {
  const d = new Date(iso);
  const p = (n) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
};
const fmtPeriod = (a, b) => {
  const f = (iso) => {
    const d = new Date(iso); const p = (n) => String(n).padStart(2, '0');
    return `${d.getFullYear()}.${p(d.getMonth()+1)}.${p(d.getDate())}`;
  };
  return `${f(a)} — ${f(b)}`;
};

// ── DEMO DATA ──────────────────────────────────────────────────────
const seedDemo = () => ({
  currentVol: 4,
  me: 'a',
  telegrams: [
    { id: 't1', from: 'b', text: '오늘 퇴근길에 우리 자주가던 분식집 지나감 STOP 떡볶이 냄새에 발이 멈춤 STOP', time: '2026-05-19T18:42:00', vol: 4 },
    { id: 't2', from: 'b', text: '넷플릭스에서 다큐 하나 봤는데 꼭 말해줘야함 STOP 만나서 STOP', time: '2026-05-18T23:11:00', vol: 4 },
    { id: 't3', from: 'a', text: '아까 길에서 고양이가 나를 따라옴 STOP 증거는 내 기억뿐 STOP', time: '2026-05-19T20:15:00', vol: 4 },
    { id: 't4', from: 'a', text: '새로 산 향수가 실패 STOP 수박껍질 냄새남 STOP', time: '2026-05-18T09:30:00', vol: 4 },
    { id: 't5', from: 'b', text: '회사 화장실에서 울뻔함 STOP 별일아님 STOP 근데 만나면 말할거임 STOP', time: '2026-05-17T14:03:00', vol: 4 },
  ],
  volumes: [
    {
      id: 'vol-3', vol: 3, label: 'VOL.3', title: '봄날의 출퇴근',
      period: '2026.05.05 — 05.11', count: 14, cover: 'sage', closedAt: '2026-05-12',
      telegrams: [
        { from: 'a', text: '어제 꿈에 중학교 나옴 STOP 체육복 입고있었음 STOP', time: '05.05 08:20' },
        { from: 'b', text: '나도 요즘 맨날 학교꿈 STOP 시험못본 꿈 STOP', time: '05.05 19:44' },
        { from: 'a', text: '점심에 혼밥했는데 행복했음 STOP 이거 말하려고 메모함 STOP', time: '05.06 12:33' },
        { from: 'b', text: '카페에서 옆사람이 너랑 똑같은 말투 씀 STOP 깜짝놀람 STOP', time: '05.07 16:02' },
        { from: 'a', text: '저녁에 비가 와서 그냥 걸음 STOP 우산 안가져옴 STOP', time: '05.08 19:50' },
        { from: 'b', text: '요즘 자꾸 옛날 노래만 듣게됨 STOP 이상함 STOP', time: '05.09 22:11' },
        { from: 'a', text: '이번주 보고할거 많음 STOP 각오해 STOP', time: '05.10 22:15' },
      ],
    },
    {
      id: 'vol-2', vol: 2, label: 'VOL.2', title: '비오는 4월',
      period: '2026.04.28 — 05.04', count: 9, cover: 'burgundy', closedAt: '2026-05-04',
      telegrams: [
        { from: 'b', text: '비오는날 우산없이 걸음 STOP 일부러 STOP', time: '04.28 18:30' },
        { from: 'a', text: '오늘 엄마랑 통화함 STOP 한시간 STOP 별말없었는데 좋았음 STOP', time: '04.30 21:00' },
        { from: 'b', text: '출근길에 무지개봄 STOP 사진은 못찍음 STOP 믿어줘 STOP', time: '05.02 08:15' },
        { from: 'a', text: '서점에서 책 한권 삼 STOP 표지가 너랑 닮음 STOP', time: '05.03 15:20' },
      ],
    },
    {
      id: 'vol-1', vol: 1, label: 'VOL.1', title: '시작',
      period: '2026.04.21 — 04.27', count: 11, cover: 'sand', closedAt: '2026-04-27',
      telegrams: [
        { from: 'a', text: '이 앱 처음이다 STOP 잘부탁해 STOP', time: '04.21 20:00' },
        { from: 'b', text: '나도 STOP 근데 벌써 할말있음 STOP', time: '04.21 20:05' },
        { from: 'a', text: '점심 뭐먹지 STOP 답장하지마 STOP 만나서 STOP', time: '04.22 11:48' },
        { from: 'b', text: '편의점 신상 라면 발견 STOP 추천 STOP', time: '04.23 22:30' },
      ],
    },
  ],
});

// ── LOCAL STORE ────────────────────────────────────────────────────
function makeLocalStore() {
  const load = () => {
    try {
      const raw = localStorage.getItem(LS_KEY);
      if (!raw) {
        const seeded = seedDemo();
        localStorage.setItem(LS_KEY, JSON.stringify(seeded));
        return seeded;
      }
      return JSON.parse(raw);
    } catch {
      return seedDemo();
    }
  };
  const save = (s) => localStorage.setItem(LS_KEY, JSON.stringify(s));

  let state = load();
  const subs = new Set();
  const notify = () => subs.forEach((cb) => cb(state));

  // cross-tab sync
  window.addEventListener('storage', (e) => {
    if (e.key === LS_KEY && e.newValue) {
      state = JSON.parse(e.newValue);
      notify();
    }
  });

  return {
    mode: 'local',
    getState: () => state,
    subscribe: (cb) => { subs.add(cb); cb(state); return () => subs.delete(cb); },

    setMe: (who) => { state = { ...state, me: who }; save(state); notify(); },

    sendTelegram: (text) => {
      const t = {
        id: 't_' + Date.now() + '_' + Math.random().toString(36).slice(2,6),
        from: state.me, text, time: nowISO(), vol: state.currentVol,
      };
      state = { ...state, telegrams: [t, ...state.telegrams] };
      save(state); notify();
      return t;
    },

    closeVol: ({ title, cover }) => {
      const tg = state.telegrams.filter((t) => t.vol === state.currentVol);
      if (tg.length === 0) return null;
      const times = tg.map((t) => new Date(t.time).getTime());
      const period = fmtPeriod(new Date(Math.min(...times)).toISOString(), new Date(Math.max(...times)).toISOString());
      const newVol = {
        id: 'vol-' + state.currentVol,
        vol: state.currentVol,
        label: 'VOL.' + state.currentVol,
        title: title || `VOL.${state.currentVol}`,
        period, count: tg.length, cover: cover || 'sage',
        closedAt: nowISO(),
        telegrams: tg.slice().reverse().map((t) => ({
          from: t.from, text: t.text,
          time: fmtTime(t.time).slice(5,16).replace('-', '.'),
        })),
      };
      state = {
        ...state,
        currentVol: state.currentVol + 1,
        telegrams: state.telegrams.filter((t) => t.vol !== newVol.vol),
        volumes: [newVol, ...state.volumes],
      };
      save(state); notify();
      return newVol;
    },

    resetAll: () => {
      localStorage.removeItem(LS_KEY);
      state = load();
      notify();
    },
  };
}

// ── FIREBASE STORE (compat SDK loaded via <script> in index.html) ──
function makeFirebaseStore(cfg) {
  // Lazy require — only constructed when window.firebase exists
  const fb = window.firebase;
  fb.initializeApp(cfg);
  const db = fb.firestore();
  const auth = fb.auth();

  const roomId = cfg.roomId || 'default';
  const roomRef = db.collection('rooms').doc(roomId);
  const tgCol = roomRef.collection('telegrams');
  const volCol = roomRef.collection('volumes');

  let state = { currentVol: 1, me: 'a', telegrams: [], volumes: [], _loading: true };
  const subs = new Set();
  const notify = () => subs.forEach((cb) => cb(state));

  auth.signInAnonymously().catch(console.warn);
  auth.onAuthStateChanged((user) => {
    if (!user) return;
    state.me = user.uid;
    // Ensure room exists
    roomRef.get().then((snap) => {
      if (!snap.exists) roomRef.set({ currentVol: 1, createdAt: fb.firestore.FieldValue.serverTimestamp() });
    });
    roomRef.onSnapshot((snap) => {
      const d = snap.data() || {};
      state = { ...state, currentVol: d.currentVol || 1, _loading: false };
      notify();
    });
    tgCol.orderBy('time', 'desc').onSnapshot((snap) => {
      state = { ...state, telegrams: snap.docs.map((d) => ({ id: d.id, ...d.data() })) };
      notify();
    });
    volCol.orderBy('vol', 'desc').onSnapshot((snap) => {
      state = { ...state, volumes: snap.docs.map((d) => ({ id: d.id, ...d.data() })) };
      notify();
    });
  });

  return {
    mode: 'firebase',
    getState: () => state,
    subscribe: (cb) => { subs.add(cb); cb(state); return () => subs.delete(cb); },
    setMe: () => {}, // identity is auth uid

    sendTelegram: async (text) => {
      const me = auth.currentUser?.uid || 'anon';
      await tgCol.add({ text, from: me, time: nowISO(), vol: state.currentVol });
    },

    closeVol: async ({ title, cover }) => {
      const currentTg = state.telegrams.filter((t) => t.vol === state.currentVol);
      if (currentTg.length === 0) return null;
      const times = currentTg.map((t) => new Date(t.time).getTime());
      const period = fmtPeriod(new Date(Math.min(...times)).toISOString(), new Date(Math.max(...times)).toISOString());
      const v = state.currentVol;
      const newVol = {
        vol: v, label: 'VOL.' + v, title: title || `VOL.${v}`,
        period, count: currentTg.length, cover: cover || 'sage',
        closedAt: nowISO(),
        telegrams: currentTg.slice().reverse().map((t) => ({
          from: t.from, text: t.text,
          time: fmtTime(t.time).slice(5,16).replace('-', '.'),
        })),
      };
      const batch = db.batch();
      batch.set(volCol.doc('vol-' + v), newVol);
      currentTg.forEach((t) => batch.delete(tgCol.doc(t.id)));
      batch.update(roomRef, { currentVol: v + 1 });
      await batch.commit();
      return newVol;
    },

    resetAll: () => { /* not supported via UI for safety */ },
  };
}

// ── PUBLIC ─────────────────────────────────────────────────────────
window.tajeonStore = (() => {
  if (window.FIREBASE_CONFIG && window.firebase) {
    try { return makeFirebaseStore(window.FIREBASE_CONFIG); }
    catch (e) { console.warn('[tajeon] firebase init failed, falling back to local', e); }
  }
  return makeLocalStore();
})();
