<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Forums</title>
  <link href="https://fonts.googleapis.com/css2?family=Geist:wght@100..900&display=swap" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">

  <style>
    body {
      background-color: rgb(5, 5, 5);
      margin: 0;
      padding: 0;
      font-family: 'Geist', serif;
      color: white;
    }

    .container {
      width: 80%;
      margin: 0 auto;
      padding: 20px;
    }

    h1 {
      text-align: center;
    }

    .header {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-bottom: 20px;
    }

    .discord-button {
      color: #5865F2;
      font-size: 24px;
      cursor: pointer;
      transition: transform 0.2s ease, color 0.2s ease;
    }

    .discord-button:hover {
      transform: scale(1.1);
      color: #404EED;
      text-decoration: none;
    }

    .dev-button {
      font-size: 16px;
      color: #FFFFFF;
      font-weight: 500;
      margin-right: 15px;
      cursor: pointer;
      text-decoration: none;
    }

    .dev-button:hover {
      color: #FFFF00;
    }

    .forum-posts {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .forum-post {
      background-color: rgba(255, 255, 255, 0.1);
      padding: 20px;
      border-radius: 15px;
      box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5);
      position: relative;
    }

    .forum-post h3 {
      margin: 0;
      color: #ffcb00;
    }

    .forum-post .author {
      font-size: 12px;
      color: #cccccc;
    }

    .forum-post .timestamp {
      font-size: 12px;
      color: #999;
      position: absolute;
      top: 10px;
      right: 10px;
    }

    .forum-post p {
      font-size: 14px;
    }

    .post-form {
      background-color: rgba(255, 255, 255, 0.1);
      padding: 20px;
      border-radius: 15px;
      box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5);
      margin-bottom: 20px;
    }

    .post-form input,
    .post-form textarea {
      width: 100%;
      max-width: 100%;
      padding: 10px;
      margin: 10px 0;
      border-radius: 8px;
      border: 1px solid #646464;
      background-color: #1e1e1e;
      color: white;
      font-family: 'Geist', serif;
      box-sizing: border-box;
    }

    .post-form button {
      width: 100%;
      padding: 10px;
      margin: 10px 0;
      border-radius: 8px;
      border: 1px solid #646464;
      background-color: #1e1e1e;
      color: white;
      font-family: 'Geist', serif;
      cursor: pointer;
    }

    .post-form button:hover {
      background-color: #333;
    }

    .image-preview {
      width: 100px;
      height: 100px;
      margin-top: 10px;
      display: inline-block;
      position: relative;
      overflow: hidden;
      cursor: pointer;
    }

    .image-preview img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="header">
      <a href="devmode37487348.html" class="dev-button">Developer</a>
      <a href="https://discord.gg/your-server-link" target="_blank" title="Join our Discord!">
        <i class="fab fa-discord discord-button"></i>
      </a>
      
    </div>

    <div class="post-form">
      <h2>Create a New Post</h2>
      <form id="postForm">
        <input type="text" id="postTitle" placeholder="Post Title" required>
        <textarea id="postContent" placeholder="Write your post here..." rows="4" required></textarea>
        <input type="text" id="postAuthor" placeholder="Your Name (optional)">
        <input type="file" id="imageUpload" accept="image/*">
        <div id="imagePreview" class="image-preview" style="display:none;">
          <img id="previewImage" src="" alt="Image Preview">
        </div>
        <button type="submit">Submit Post</button>
      </form>
    </div>

    <div class="forum-posts" id="forumPosts"></div>
  </div>

  <script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/11.2.0/firebase-app.js";
    import { getFirestore, collection, addDoc, getDocs } from "https://www.gstatic.com/firebasejs/11.2.0/firebase-firestore.js";
    import { getStorage, ref, uploadBytes, getDownloadURL } from "https://www.gstatic.com/firebasejs/11.2.0/firebase-storage.js";

    const firebaseConfig = {
      apiKey: "AIzaSyC3J6RZGiAzhOgyJTsC3WLs9O6qV7CprdM",
      authDomain: "atlastoby-site.firebaseapp.com",
      projectId: "atlastoby-site",
      storageBucket: "atlastoby-site.appspot.com",
      messagingSenderId: "1020680989557",
      appId: "1:1020680989557:web:dc1b1fb1170fa9a122813c"
    };

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

    const IMGBB_API_KEY = "92fc240352bb8acf3aaf533b5d69796c"; // Replace with your ImgBB API Key

    async function uploadImageToImgBB(file) {
      const formData = new FormData();
      formData.append("image", file);

      const response = await fetch(`https://api.imgbb.com/1/upload?key=${IMGBB_API_KEY}`, {
        method: "POST",
        body: formData
      });

      const result = await response.json();
      if (result.success) {
        return result.data.url; // Returning the image URL
      } else {
        throw new Error("Image upload failed.");
      }
    }

    async function addPostToFirestore(title, content, author, imageUrl) {
      try {
        const docRef = await addDoc(collection(db, "forumPosts"), {
          title: title,
          content: content,
          author: author || "Anonymous",
          timestamp: new Date().toISOString(),
          imageUrl: imageUrl || null
        });
        console.log("Post added with ID: ", docRef.id);
        fetchPosts();
      } catch (e) {
        console.error("Error adding post: ", e);
        alert("Failed to add post: " + e.message);
      }
    }

    async function fetchPosts() {
      const querySnapshot = await getDocs(collection(db, "forumPosts"));
      const forumPosts = document.getElementById("forumPosts");
      forumPosts.innerHTML = "";

      const postsArray = [];
      querySnapshot.forEach((doc) => {
        postsArray.push(doc.data());
      });

      postsArray.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));

      postsArray.forEach((post) => {
        const date = new Date(post.timestamp).toLocaleString();

        const newPost = document.createElement("div");
        newPost.classList.add("forum-post");
        newPost.innerHTML = `
          <div class="timestamp">${date}</div>
          <h3>${post.title}</h3>
          <p>${post.content}</p>
          ${post.imageUrl ? `<div class="image-preview">
                               <a href="${post.imageUrl}" target="_blank">
                                 <img src="${post.imageUrl}" alt="Post Image">
                               </a>
                             </div>` : ''}
          <div class="author">Posted by: ${post.author}</div>
        `;
        forumPosts.appendChild(newPost);
      });
    }

    const imageUpload = document.getElementById("imageUpload");
    const imagePreview = document.getElementById("imagePreview");
    const previewImage = document.getElementById("previewImage");

    imageUpload.addEventListener("change", () => {
      const file = imageUpload.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = () => {
          previewImage.src = reader.result;
          imagePreview.style.display = "block";
        };
        reader.readAsDataURL(file);
      }
    });

    const postForm = document.getElementById("postForm");
    postForm.addEventListener("submit", async (event) => {
      event.preventDefault();

      const title = document.getElementById("postTitle").value;
      const content = document.getElementById("postContent").value;
      const author = document.getElementById("postAuthor").value;
      const file = imageUpload.files[0];

      let imageUrl = null;

      if (file) {
        try {
          imageUrl = await uploadImageToImgBB(file);
        } catch (error) {
          alert("Error uploading image: " + error.message);
          return;
        }
      }

      addPostToFirestore(title, content, author, imageUrl);
      postForm.reset();
      imagePreview.style.display = "none";
    });

    window.onload = fetchPosts;
  </script>
</body>

</html>
