const SASHA = { name: 'Sasha', avatar: 'S', hue: 280 };

const TRACKS = [
  { id: 't1', title: 'Prejudice',               artist: 'Sasha', author: 'Human · Sasha', tag: 'human',    plays: 0, likes: 0, rating: 0, ratings: 0, comments: 0, duration: '0:00', durationSec: 0, art: 0 },
  { id: 't2', title: 'Someday',                  artist: 'Sasha', author: 'Human · Sasha', tag: 'human',    plays: 0, likes: 0, rating: 0, ratings: 0, comments: 0, duration: '0:00', durationSec: 0, art: 1 },
  { id: 't3', title: 'Life — Rap',               artist: 'Sasha', author: 'Human · Sasha', tag: 'ai',       plays: 0, likes: 0, rating: 0, ratings: 0, comments: 0, duration: '0:00', durationSec: 0, art: 2 },
  { id: 't4', title: 'Like the Sun — Opera',     artist: 'Sasha', author: 'Human · Sasha', tag: 'human+ai', plays: 0, likes: 0, rating: 0, ratings: 0, comments: 0, duration: '0:00', durationSec: 0, art: 3 },
  { id: 't5', title: 'Like the Sun — Hard Rock', artist: 'Sasha', author: 'Human · Sasha', tag: 'human+ai', plays: 0, likes: 0, rating: 0, ratings: 0, comments: 0, duration: '0:00', durationSec: 0, art: 4 },
  { id: 't6', title: "A Song I Can't Set Free",  artist: 'Sasha', author: 'Human · Sasha', tag: 'human',    plays: 0, likes: 0, rating: 0, ratings: 0, comments: 0, duration: '0:00', durationSec: 0, art: 5 },
];

const TRENDING = TRACKS.slice().map((t, i) => ({ ...t, rank: i + 1, change: 'new' }));

const COMMENTS      = [];
const PLAYLISTS     = [];
const HISTORY       = [];
const USERS         = [];
const NOTIFICATIONS = [];

const ANALYTICS = {
  totalPlays: 0, totalUsers: 0, totalComments: 0, avgRating: 0,
  playsDelta: 0, usersDelta: 0, commentsDelta: 0, ratingDelta: 0,
  playsByDay: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  topTracks: ['t1', 't2', 't3', 't4', 't5', 't6'],
};

Object.assign(window, { SASHA, TRACKS, TRENDING, COMMENTS, PLAYLISTS, HISTORY, USERS, ANALYTICS, NOTIFICATIONS });

async function loadFirestoreData() {
  if (!window.firestoreDB || !window.firestoreModule) return;
  const { collection, getDocs, onSnapshot } = window.firestoreModule;
  const db = window.firestoreDB;
  try {
    // One-time fetch for config (slow-changing)
    const [configSnap] = await Promise.all([
      getDocs(collection(db, 'config')),
    ]);

    // Process config docs; store trending order for use when tracks update
    const trendingOrder = [];
    configSnap.docs.forEach(d => {
      if (d.id === 'sasha')     window.SASHA    = d.data();
      if (d.id === 'analytics') window.ANALYTICS = d.data();
      if (d.id === 'history') {
        const { items } = d.data();
        if (Array.isArray(items)) window.HISTORY = items;
      }
      if (d.id === 'trending') {
        const { order } = d.data();
        if (Array.isArray(order)) trendingOrder.push(...order);
      }
    });

    // Real-time listener: users — fires on load + whenever a user is added/changed
    onSnapshot(collection(db, 'users'), (snap) => {
      window.USERS = snap.docs.map(d => ({ id: d.id, ...d.data() }));
      window.dispatchEvent(new CustomEvent('dataLoaded'));
    });

    // Real-time listener: tracks — fires on load + whenever any track changes
    onSnapshot(collection(db, 'tracks'), (snap) => {
      window.TRACKS = snap.docs.map(d => ({ id: d.id, ...d.data() }));
      if (trendingOrder.length) {
        window.TRENDING = trendingOrder.map((id, i) => {
          const track = window.TRACKS.find(t => t.id === id);
          return track ? { ...track, rank: i + 1 } : null;
        }).filter(Boolean);
      }
      window.dispatchEvent(new CustomEvent('dataLoaded'));
    });

    // Real-time listener: notifications — fires on load + whenever a notification is added
    onSnapshot(collection(db, 'notifications'), (snap) => {
      window.NOTIFICATIONS = snap.docs
        .map(d => ({ id: d.id, ...d.data() }))
        .sort((a, b) => (b.timestamp || '').localeCompare(a.timestamp || ''));
      window.dispatchEvent(new CustomEvent('dataLoaded'));
    });

    // Real-time listener: playlists — fires on load + whenever a playlist is added/changed
    onSnapshot(collection(db, 'playlists'), (snap) => {
      window.PLAYLISTS = snap.docs.map(d => ({ id: d.id, ...d.data() }));
      window.dispatchEvent(new CustomEvent('dataLoaded'));
    });

    // Real-time listener: comments — fires on load + whenever a comment is added/deleted
    onSnapshot(collection(db, 'comments'), (snap) => {
      window.COMMENTS = snap.docs.map(d => ({ id: d.id, ...d.data() }));
      window.dispatchEvent(new CustomEvent('dataLoaded'));
    });

  } catch (err) {
    console.error('Firestore load error:', err);
  }
}

window.dbHelpers = {
  async addTrack(trackData) {
    const { id, ...data } = trackData; // let Firestore generate the document ID
    const { collection, addDoc } = window.firestoreModule;
    return addDoc(collection(window.firestoreDB, 'tracks'), data);
  },
  async updateTrack(trackId, updates) {
    const { id, ...data } = updates; // never write 'id' into document fields
    const { doc, updateDoc } = window.firestoreModule;
    return updateDoc(doc(window.firestoreDB, 'tracks', trackId), data);
  },
  async deleteTrack(trackId) {
    const { doc, deleteDoc } = window.firestoreModule;
    return deleteDoc(doc(window.firestoreDB, 'tracks', trackId));
  },
  async setUserRole(email, name, role) {
    const { collection, getDocs, doc, setDoc, addDoc, query: fq, where } = window.firestoreModule;
    const db = window.firestoreDB;
    const snap = await getDocs(fq(collection(db, 'users'), where('email', '==', email)));
    if (!snap.empty) {
      return setDoc(snap.docs[0].ref, { role }, { merge: true });
    }
    // No existing doc — create one
    return addDoc(collection(db, 'users'), { email, name, role, status: 'active' });
  },
  async updateUser(userId, updates) {
    const { doc, updateDoc } = window.firestoreModule;
    return updateDoc(doc(window.firestoreDB, 'users', userId), updates);
  },
  async banUser(userId) {
    const { doc, updateDoc } = window.firestoreModule;
    return updateDoc(doc(window.firestoreDB, 'users', userId), { status: 'banned' });
  },
  async addComment(commentData) {
    const { doc, setDoc } = window.firestoreModule;
    return setDoc(doc(window.firestoreDB, 'comments', commentData.id), commentData);
  },
  async flagComment(commentId) {
    const { doc, updateDoc } = window.firestoreModule;
    return updateDoc(doc(window.firestoreDB, 'comments', commentId), { flagged: true });
  },
  async addPlaylist(playlistData) {
    const { doc, setDoc } = window.firestoreModule;
    return setDoc(doc(window.firestoreDB, 'playlists', playlistData.id), playlistData);
  },
  async updatePlaylist(playlistId, updates) {
    const { doc, updateDoc } = window.firestoreModule;
    return updateDoc(doc(window.firestoreDB, 'playlists', playlistId), updates);
  },
  async sendNotification(data) {
    // data: { title, message, type, sentBy }
    const notif = { ...data, timestamp: new Date().toISOString() };
    if (window.firestoreDB && window.firestoreModule) {
      const { collection, addDoc } = window.firestoreModule;
      const ref = await addDoc(collection(window.firestoreDB, 'notifications'), notif);
      notif.id = ref.id;
    } else {
      notif.id = 'n' + Date.now();
    }
    window.NOTIFICATIONS = [notif, ...(window.NOTIFICATIONS || [])];
    window.dispatchEvent(new CustomEvent('notificationSent', { detail: notif }));
    return notif;
  },
};

loadFirestoreData();
