import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js";
import {
  getFirestore,
  collection,
  getDocs,
  onSnapshot
} from "https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore.js";

// 🔥 CONFIG FIREBASE
const firebaseConfig = {
  apiKey: "AIzaSyBHsMytHdwVU2W3YZy-HTGMwTJeLbQ3Fi8",
  authDomain: "poultryrail-1205e.firebaseapp.com",
  projectId: "poultryrail-1205e",
  storageBucket: "poultryrail-1205e.firebasestorage.app",
  messagingSenderId: "413502718068",
  appId: "1:413502718068:web:b1f0cfa68a67d971cd5121",
  measurementId: "G-MS3V545ZT0"
};

// INIT
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

// 🔥 FUNCTION RENDER TABLE (biar tidak dobel kode)
function renderTable(snapshot) {
  const table = document.querySelector("#tabelData tbody");
  table.innerHTML = "";

  snapshot.forEach((doc) => {
    const data = doc.data();

    table.innerHTML += `
      <tr>
        <td>${data.status}</td>
        <td>${data.jam}</td>
        <td>${data.sisa}%</td>
        <td>${data.persen}%</td>
        <td>${data.gram} Gram</td>
      </tr>
    `;
  });
}

// 🔥 LOAD AWAL
async function loadData() {
  const querySnapshot = await getDocs(collection(db, "jadwal_pakan"));
  renderTable(querySnapshot);
}

// 🔥 REALTIME LISTENER
function realtimeData() {
  onSnapshot(collection(db, "jadwal_pakan"), (snapshot) => {
    renderTable(snapshot);
  });
}

// JALANKAN
loadData();
realtimeData();