// community.js — realtime community feed with timestamps & likes (button under post)

import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
import {
  getFirestore,
  collection,
  addDoc,
  onSnapshot,
  updateDoc,
  doc,
  increment,
  serverTimestamp,
  query,
  orderBy
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";

// --- Firebase (use your project values) ---
const firebaseConfig = {
  apiKey: "AIzaSyC-lsC7Xsp-K3gbdxXDdS7yTL5HzWggTx0",
  authDomain: "selftherapy-c61c6.firebaseapp.com",
  projectId: "selftherapy-c61c6",
  storageBucket: "selftherapy-c61c6.firebasestorage.app",
  messagingSenderId: "566396923513",
  appId: "1:566396923513:web:2affabac7c2072fbe62ea8"
};

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

// --- DOM refs ---
const postsList = document.getElementById("posts-list");
const submitBtn = document.getElementById("submit-post");
const userInput = document.getElementById("username-input");
const postInput = document.getElementById("post-input");

// --- Utils ---
function escapeHTML(s = "") {
  return s.replace(/[&<>"']/g, m => ({ "&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","'":"&#39;" }[m]));
}
function fmtTimestamp(ts) {
  // ts can be a Firestore Timestamp, Date, or null (e.g., immediately after write)
  let d;
  if (ts?.toDate) d = ts.toDate();
  else if (ts instanceof Date) d = ts;
  else d = new Date();
  return {
    display: d.toLocaleString(),   // visible label
    iso: d.toISOString()           // tooltip
  };
}

// --- Rendering ---
function renderPosts(snapshot) {
  postsList.innerHTML = "";
  snapshot.forEach((docSnap) => {
    const data = docSnap.data();
    const { display, iso } = fmtTimestamp(data.createdAt);

    const card = document.createElement("article");
    card.className = "post-card";
    card.innerHTML = `
      <div class="post-meta">
        <strong class="post-user">${escapeHTML(data.username || "Anonymous")}</strong>
        <span class="post-time" title="${iso}">${display}</span>
      </div>
      <p class="post-text">${escapeHTML(data.message || "")}</p>
      <div class="post-actions">
        <button class="like-btn" data-id="${docSnap.id}" aria-label="Like this post">❤️ ${data.likes ?? 0}</button>
      </div>
    `;

    // Like handler (atomic increment)
    const likeBtn = card.querySelector(".like-btn");
    likeBtn.addEventListener("click", async () => {
      likeBtn.disabled = true;
      const id = likeBtn.getAttribute("data-id");
      try {
        await updateDoc(doc(db, "community-posts", id), { likes: increment(1) });
      } finally {
        likeBtn.disabled = false;
      }
    });

    postsList.appendChild(card);
  });
}

// --- Realtime subscription (newest first) ---
const postsRef = collection(db, "community-posts");
const qRef = query(postsRef, orderBy("createdAt", "desc"));
onSnapshot(qRef, renderPosts);

// --- Create post ---
submitBtn.addEventListener("click", async () => {
  const username = userInput.value.trim() || "Anonymous";
  const message = postInput.value.trim();

  if (!message) {
    alert("Please write something before posting.");
    return;
  }

  submitBtn.disabled = true;
  try {
    await addDoc(postsRef, {
      username,
      message,
      likes: 0,
      createdAt: serverTimestamp()
    });
    postInput.value = "";
  } catch (e) {
    console.error(e);
    alert("Couldn't post. Please try again.");
  } finally {
    submitBtn.disabled = false;
  }
});
