<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>CELESTIUM DAO</title>
  <!-- Google Fonts for Improved Typography -->
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&family=Orbitron:wght@700&display=swap" rel="stylesheet">
  <style>
    /* RESET STYLES */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    /* BASE STYLES */
    body {
      font-family: 'Roboto', sans-serif;
      background-color: #0d0d0d;
      color: #e0e0e0;
      line-height: 1.6;
      min-height: 100vh;
      display: flex;
      flex-direction: column;
    }

    a {
      color: #00fff7;
      text-decoration: none;
      transition: color 0.3s;
    }

    a:hover {
      color: #ff00ea;
    }

    /* HEADER */
    header {
      background: #1a1a1a;
      padding: 20px;
      text-align: center;
      position: sticky;
      top: 0;
      z-index: 1000;
      box-shadow: 0 2px 4px rgba(0,0,0,0.5);
    }

    header h1 {
      font-family: 'Orbitron', sans-serif;
      font-size: 2.5rem;
      color: #00fff7;
      margin-bottom: 10px;
      text-shadow: 0 0 10px #00fff7, 0 0 20px #ff00ea;
    }

    header h2 {
      font-size: 1.5rem;
      color: #ff00ea;
    }

    /* NAVIGATION BAR */
    .navbar {
      display: flex;
      justify-content: center;
      gap: 20px;
      margin-top: 10px;
      flex-wrap: wrap;
    }

    .navbar a {
      font-size: 1rem;
      padding: 8px 16px;
      background: linear-gradient(135deg, #00fff7, #ff00ea);
      border-radius: 4px;
      color: #000;
      font-weight: bold;
      transition: background 0.3s, transform 0.3s;
    }

    .navbar a:hover {
      background: #ff00ea;
      transform: translateY(-2px);
    }

    /* MAIN CONTENT */
    main {
      flex: 1;
      padding: 20px;
      max-width: 1200px;
      margin: 0 auto;
    }

    .section {
      background: #1c1c1c;
      padding: 30px;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(255,255,255,0.1);
      margin-bottom: 40px;
    }

    .section h3 {
      font-family: 'Orbitron', sans-serif;
      font-size: 1.8rem;
      margin-bottom: 20px;
      color: #00fff7;
    }

    /* FORMS */
    form {
      display: flex;
      flex-direction: column;
      gap: 15px;
    }

    input[type="email"],
    input[type="password"],
    input[type="text"],
    textarea,
    select {
      padding: 12px;
      border: none;
      border-radius: 4px;
      font-size: 1rem;
      background: #333;
      color: #fff;
    }

    button {
      padding: 12px;
      border: none;
      border-radius: 4px;
      font-size: 1rem;
      background: linear-gradient(135deg, #00fff7, #ff00ea);
      color: #000;
      font-weight: bold;
      cursor: pointer;
      transition: background 0.3s, transform 0.3s;
    }

    button:hover {
      background: #ff00ea;
      transform: translateY(-2px);
    }

    /* AUTHENTICATION CONTAINER */
    .auth-container {
      background: #1c1c1c;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(255,255,255,0.1);
      margin-bottom: 40px;
    }

    .auth-container h3 {
      font-family: 'Orbitron', sans-serif;
      font-size: 1.8rem;
      margin-bottom: 20px;
      color: #00fff7;
      text-align: center;
    }

    .toggle-auth {
      text-align: center;
      margin-top: 10px;
    }

    .toggle-auth a {
      color: #00fff7;
      cursor: pointer;
      font-weight: bold;
    }

    /* VOTING CONTAINER */
    .vote-container {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .vote-item {
      background: #333;
      padding: 20px;
      border-radius: 6px;
      box-shadow: 0 2px 4px rgba(255,255,255,0.1);
      position: relative;
      transition: transform 0.3s;
    }

    .vote-item:hover {
      transform: translateY(-5px);
    }

    .vote-item h4 {
      font-size: 1.5rem;
      color: #ff00ea;
      margin-bottom: 10px;
    }

    .vote-item p {
      font-size: 1rem;
      margin-bottom: 15px;
    }

    .vote-actions {
      display: flex;
      gap: 10px;
    }

    .vote-actions button {
      flex: 1;
      background: #00fff7;
      color: #000;
      border: none;
      padding: 10px;
      border-radius: 4px;
      font-weight: bold;
      cursor: pointer;
      transition: background 0.3s, transform 0.3s;
    }

    .vote-actions button:hover {
      background: #ff00ea;
      transform: translateY(-2px);
    }

    /* EDIT/DELETE BUTTONS */
    .edit-button,
    .delete-button {
      position: absolute;
      top: 20px;
      color: #fff;
      border: none;
      padding: 5px 10px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 0.9rem;
      transition: background 0.3s;
    }

    .edit-button {
      right: 70px;
      background: #ff00ea;
    }
    .edit-button:hover {
      background: #00fff7;
    }

    .delete-button {
      right: 20px;
      background: #ff3535;
    }
    .delete-button:hover {
      background: #ff8080;
    }

    /* PROFILE SECTION */
    .profile-section {
      display: none;
    }

    .profile-section h4 {
      margin-top: 20px;
      font-size: 1.5rem;
      color: #00fff7;
    }

    /* TOP VOTED SECTION */
    .top-voted-section {
      background: #1c1c1c;
      padding: 30px;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(255,255,255,0.1);
      margin-bottom: 40px;
    }

    .top-voted-section h3 {
      font-family: 'Orbitron', sans-serif;
      font-size: 1.8rem;
      margin-bottom: 20px;
      color: #00fff7;
    }

    /* SEARCH BAR */
    .search-bar {
      margin-bottom: 20px;
      display: flex;
      justify-content: center;
    }

    .search-bar input {
      width: 100%;
      max-width: 400px;
      padding: 10px;
      border: none;
      border-radius: 4px;
      font-size: 1rem;
    }

    /* FOOTER */
    footer {
      background: #1a1a1a;
      color: #888;
      text-align: center;
      padding: 20px;
    }

    /* MODAL */
    .modal {
      display: none; /* Hidden by default */
      position: fixed; /* Stay in place */
      z-index: 1001; /* Sit on top */
      left: 0;
      top: 0;
      width: 100%; /* Full width */
      height: 100%; /* Full height */
      overflow: auto; /* Enable scroll if needed */
      background-color: rgba(0,0,0,0.7); /* Black w/ opacity */
    }

    .modal-content {
      background-color: #1c1c1c;
      margin: 15% auto; /* 15% from the top and centered */
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 500px;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(255,255,255,0.2);
      position: relative;
    }

    .close {
      color: #aaa;
      position: absolute;
      top: 10px;
      right: 20px;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    .close:hover,
    .close:focus {
      color: #fff;
      text-decoration: none;
      cursor: pointer;
    }

    /* EDIT FORM */
    .edit-form {
      display: none;
      margin-top: 20px;
      flex-direction: column;
      gap: 10px;
      background: #222;
      padding: 10px;
      border-radius: 6px;
    }
    .edit-form input,
    .edit-form textarea {
      background: #444;
    }

    /* NOTE */
    .note {
      font-size: 0.9rem;
      color: #888;
    }

    /* RESPONSIVE DESIGN */
    @media (max-width: 1024px) {
      .navbar {
        gap: 15px;
      }

      .section {
        padding: 25px;
      }

      .section h3 {
        font-size: 1.6rem;
      }

      .vote-item h4 {
        font-size: 1.3rem;
      }

      .vote-actions button {
        padding: 8px;
        font-size: 0.9rem;
      }

      .edit-button {
        font-size: 0.8rem;
        padding: 3px 6px;
        right: 80px;
      }
      .delete-button {
        right: 20px;
        font-size: 0.8rem;
        padding: 3px 6px;
      }

      /* Top Voted Section */
      .top-voted-section {
        padding: 25px;
      }
      .top-voted-section h3 {
        font-size: 1.6rem;
      }
    }

    @media (max-width: 768px) {
      header h1 {
        font-size: 2rem;
      }

      header h2 {
        font-size: 1.2rem;
      }

      .navbar a {
        font-size: 0.9rem;
        padding: 6px 12px;
      }

      .section {
        padding: 20px;
      }

      .section h3 {
        font-size: 1.5rem;
      }

      .vote-item h4 {
        font-size: 1.2rem;
      }

      .vote-actions button {
        padding: 8px;
        font-size: 0.9rem;
      }

      .edit-button {
        font-size: 0.8rem;
        padding: 3px 6px;
        right: 80px;
      }
      .delete-button {
        right: 20px;
        font-size: 0.8rem;
        padding: 3px 6px;
      }

      /* Top Voted Section */
      .top-voted-section {
        padding: 20px;
      }
      .top-voted-section h3 {
        font-size: 1.4rem;
      }

      /* Search Bar */
      .search-bar input {
        max-width: 300px;
      }
    }

    @media (max-width: 480px) {
      header h1 {
        font-size: 1.8rem;
      }

      header h2 {
        font-size: 1rem;
      }

      .navbar a {
        font-size: 0.8rem;
        padding: 5px 10px;
      }

      .section h3 {
        font-size: 1.3rem;
      }

      .vote-item h4 {
        font-size: 1rem;
      }

      .vote-actions button {
        padding: 6px;
        font-size: 0.8rem;
      }

      .edit-button,
      .delete-button {
        font-size: 0.7rem;
        padding: 2px 4px;
      }

      /* Top Voted Section */
      .top-voted-section h3 {
        font-size: 1.2rem;
      }

      /* Search Bar */
      .search-bar input {
        max-width: 250px;
      }
    }
  </style>
</head>
<body>

  <!-- HEADER -->
  <header>
    <h1>CELESTIUM DAO</h1>
    <h2>(Upcoming Community Governance Platform)</h2>
    <nav class="navbar">
      <a href="#" id="logoutBtn" style="display: none;">Logout</a>
    </nav>
  </header>

  <!-- MAIN CONTENT -->
  <main>
    <!-- USER AUTHENTICATION -->
    <div class="auth-container" id="authContainer">
      <!-- REGISTER FORM -->
      <div id="registerForm" style="display: none;">
        <h3>Register Account</h3>
        <form id="signUpForm">
          <input type="email" id="signUpEmail" placeholder="Email Address" required />
          <input type="password" id="signUpPassword" placeholder="Password" required />
          <button type="submit">Register</button>
        </form>
        <div class="toggle-auth">
          <p>Already have an account? <a id="showLogin">Login</a></p>
        </div>
      </div>

      <!-- LOGIN FORM -->
      <div id="loginForm">
        <h3>Login</h3>
        <form id="signInForm">
          <input type="email" id="signInEmail" placeholder="Email Address" required />
          <input type="password" id="signInPassword" placeholder="Password" required />
          <button type="submit">Login</button>
        </form>
        <div class="toggle-auth">
          <p>Don't have an account? <a id="showRegister">Register</a></p>
        </div>
      </div>
    </div>

    <!-- PROPOSAL SECTION -->
    <div class="section proposal-section">
      <h3>Create a Proposal</h3>
      <form id="proposalForm">
        <input type="text" id="proposalTitle" placeholder="Proposal Title" required />
        <textarea id="proposalDetails" rows="5" placeholder="Describe your proposal..." required></textarea>
        <button type="submit">Submit Proposal</button>
        <p class="note">
          *Note: Proposals will be permanently stored once the mainnet is operational.
        </p>
      </form>

      <!-- SEARCH BAR -->
      <div class="search-bar">
        <input type="text" id="searchInput" placeholder="Search Proposals..." />
      </div>

      <!-- TOP VOTED PROPOSALS -->
      <div class="top-voted-section">
        <h3>Top Voted Proposals</h3>
        <div class="vote-container" id="topVotedContainer">
          <!-- Top voted proposals will be loaded here -->
        </div>
      </div>

      <h3>Active Proposals</h3>
      <div class="vote-container" id="voteContainer">
        <!-- Active proposals will be dynamically loaded from Firestore -->
      </div>
    </div>

    <!-- PROFILE SECTION -->
    <div class="section profile-section" id="profileSection" style="display: none;">
      <h3>Your Profile</h3>
      <p>Email Address: <span id="userEmail"></span></p>
      <h4>Your Proposals</h4>
      <div class="vote-container" id="userProposalsContainer">
        <!-- User's proposals will be loaded here -->
      </div>
    </div>
  </main>

  <!-- FOOTER -->
  <footer>
    <p>© 2025-2030 CELESTIUM DAO. All rights reserved.</p>
  </footer>

  <!-- FEEDBACK MODAL -->
  <div id="modal" class="modal">
    <div class="modal-content">
      <span class="close">&times;</span>
      <p id="modalMessage"></p>
    </div>
  </div>

  <!-- FIREBASE SDKS -->
  <!-- Replace 'YOUR_FIREBASE_CONFIG' with your actual Firebase configuration -->
  <script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-app-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-auth-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-firestore-compat.js"></script>

  <script>
    // FIREBASE CONFIGURATION (REPLACE WITH YOUR ACTUAL DATA)
    const firebaseConfig = {
        apiKey: "AIzaSyBmZbMmY5pbX2OKjFg4pjIrEpKs_5U80as",
        authDomain: "etherealnexus-2d7fd.firebaseapp.com",
        projectId: "etherealnexus-2d7fd",
        storageBucket: "etherealnexus-2d7fd.firebasestorage.app",
        messagingSenderId: "841109571357",
        appId: "1:841109571357:web:b21747fc4391f8883483f4",
        measurementId: "G-G81SQMGLJY"
    };

    // INITIALIZE FIREBASE
    firebase.initializeApp(firebaseConfig);
    const auth = firebase.auth();
    const db = firebase.firestore();

    // DOM ELEMENTS
    const authContainer = document.getElementById('authContainer');
    const registerForm = document.getElementById('registerForm');
    const loginFormDiv = document.getElementById('loginForm');
    const showRegister = document.getElementById('showRegister');
    const showLogin = document.getElementById('showLogin');
    const logoutBtn = document.getElementById('logoutBtn');
    const modal = document.getElementById('modal');
    const closeModal = document.querySelector('.close');
    const modalMessage = document.getElementById('modalMessage');
    const voteContainer = document.getElementById('voteContainer');
    const profileSection = document.getElementById('profileSection');
    const userEmailSpan = document.getElementById('userEmail');
    const userProposalsContainer = document.getElementById('userProposalsContainer');
    const topVotedContainer = document.getElementById('topVotedContainer');
    const searchInput = document.getElementById('searchInput');

    // OFFENSIVE WORDS LIST
    const offensiveWords = ['badword1', 'badword2', 'spam', 'offensiveTerm'];

    // CURRENT USER
    let currentUser = null;

    // MODAL FUNCTIONS
    function showModal(message) {
      modalMessage.textContent = message;
      modal.style.display = "block";
    }
    function closeModalFunc() {
      modal.style.display = "none";
    }
    closeModal.onclick = closeModalFunc;
    window.onclick = function(e) {
      if (e.target === modal) {
        closeModalFunc();
      }
    };

    // TOGGLE REGISTER/LOGIN FORMS
    showRegister.onclick = () => {
      registerForm.style.display = "block";
      loginFormDiv.style.display = "none";
    };
    showLogin.onclick = () => {
      registerForm.style.display = "none";
      loginFormDiv.style.display = "block";
    };

    // REGISTER
    document.getElementById('signUpForm').addEventListener('submit', (e) => {
      e.preventDefault();
      const email = document.getElementById('signUpEmail').value.trim();
      const password = document.getElementById('signUpPassword').value.trim();
      if (!email || !password) {
        showModal("Please fill in all fields.");
        return;
      }
      auth.createUserWithEmailAndPassword(email, password)
        .then(userCred => {
          const user = userCred.user;
          return db.collection('users').doc(user.uid).set({
            email: user.email,
            createdAt: firebase.firestore.FieldValue.serverTimestamp(),
            lastProposal: null
          });
        })
        .then(() => {
          showModal("Registration successful! You can now log in.");
          document.getElementById('signUpForm').reset();
          registerForm.style.display = "none";
          loginFormDiv.style.display = "block";
        })
        .catch(err => showModal("Error: " + err.message));
    });

    // LOGIN
    document.getElementById('signInForm').addEventListener('submit', (e) => {
      e.preventDefault();
      const email = document.getElementById('signInEmail').value.trim();
      const password = document.getElementById('signInPassword').value.trim();
      if (!email || !password) {
        showModal("Please fill in all fields.");
        return;
      }
      auth.signInWithEmailAndPassword(email, password)
        .then(() => {
          showModal("Login successful!");
          document.getElementById('signInForm').reset();
        })
        .catch(err => showModal("Error: " + err.message));
    });

    // LOGOUT
    logoutBtn.onclick = () => {
      auth.signOut()
        .then(() => showModal("You have successfully logged out."))
        .catch(err => showModal("Error: " + err.message));
    };

    // AUTH STATE OBSERVER
    auth.onAuthStateChanged(user => {
        currentUser = user;
        if (user) {
          authContainer.style.display = "none";
          logoutBtn.style.display = "block";
          profileSection.style.display = "block";
          userEmailSpan.textContent = user.email;
          loadUserProposals(user.uid);
        } else {
          authContainer.style.display = "block";
          logoutBtn.style.display = "none";
          profileSection.style.display = "none";
          userProposalsContainer.innerHTML = "";
        }
        // Las propuestas y las más votadas siempre se cargan, estén o no autenticados.
        loadProposals();
        loadTopVotedProposals();
      });
      

    // CONTENT FILTERING
    function containsOffensiveWords(text) {
      return offensiveWords.some(word => text.toLowerCase().includes(word.toLowerCase()));
    }

    // CREATE PROPOSAL
    document.getElementById('proposalForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      if (!currentUser) {
        showModal("You must be logged in to create a proposal.");
        return;
      }
      const title = document.getElementById('proposalTitle').value.trim();
      const details = document.getElementById('proposalDetails').value.trim();
      if (!title || !details) {
        showModal("Please fill in all fields.");
        return;
      }
      if (containsOffensiveWords(title) || containsOffensiveWords(details)) {
        showModal("Your proposal contains offensive words. Please revise the content.");
        return;
      }
      try {
        const userDoc = await db.collection('users').doc(currentUser.uid).get();
        const userData = userDoc.data();
        const now = firebase.firestore.Timestamp.now();
        if (userData.lastProposal) {
          const diffHrs = (now.seconds - userData.lastProposal.seconds) / 3600;
          if (diffHrs < 48) {
            const hrsLeft = Math.ceil(48 - diffHrs);
            showModal(`You can create another proposal in ${hrsLeft} hour(s).`);
            return;
          }
        }
        // Create proposal
        await db.collection('proposals').add({
          title,
          details,
          createdBy: currentUser.email,
          createdAt: firebase.firestore.FieldValue.serverTimestamp(),
          votesYes: 0,
          votesNo: 0,
          voters: {}
        });
        // Update lastProposal
        await db.collection('users').doc(currentUser.uid).update({
          lastProposal: firebase.firestore.FieldValue.serverTimestamp()
        });
        showModal("Proposal created successfully!");
        e.target.reset();
      } catch (err) {
        showModal("Error: " + err.message);
      }
    });

    // LOAD ALL PROPOSALS
    function loadProposals() {
      db.collection('proposals').orderBy('createdAt','desc').onSnapshot(
        snapshot => {
          voteContainer.innerHTML = "";
          snapshot.forEach(doc => {
            const proposal = doc.data();
            const proposalId = doc.id;
            const voteItem = document.createElement('div');
            voteItem.classList.add('vote-item');
            voteItem.innerHTML = `
              <h4>${proposal.title}</h4>
              <p>${proposal.details}</p>
              <p>Created by: ${proposal.createdBy}</p>
              <p>Yes Votes: ${proposal.votesYes} | No Votes: ${proposal.votesNo}</p>
              <div class="vote-actions">
                <button class="vote-yes" data-id="${proposalId}">Yes</button>
                <button class="vote-no" data-id="${proposalId}">No</button>
              </div>
            `;
            voteContainer.appendChild(voteItem);
          });
        },
        err => showModal("Error loading proposals: " + err.message)
      );
    }

    // LOAD USER'S PROPOSALS
    function loadUserProposals(uid) {
      db.collection('proposals')
        .where('createdBy','==',currentUser.email)
        .orderBy('createdAt','desc')
        .onSnapshot(snapshot => {
          userProposalsContainer.innerHTML = "";
          if (snapshot.empty) {
            userProposalsContainer.innerHTML = "<p>You haven't created any proposals yet.</p>";
            return;
          }
          snapshot.forEach(doc => {
            const proposal = doc.data();
            const proposalId = doc.id;
            const userItem = document.createElement('div');
            userItem.classList.add('vote-item');
            userItem.setAttribute('data-id', proposalId);
            userItem.innerHTML = `
              <h4>${proposal.title}</h4>
              <p>${proposal.details}</p>
              <p>Yes Votes: ${proposal.votesYes} | No Votes: ${proposal.votesNo}</p>
              <button class="edit-button" data-id="${proposalId}">Edit</button>
              <button class="delete-button" data-id="${proposalId}">Delete</button>
            `;
            userProposalsContainer.appendChild(userItem);
          });
        },
        err => showModal("Error loading your proposals: " + err.message)
      );
    }

    // LOAD TOP VOTED PROPOSALS
    function loadTopVotedProposals() {
      db.collection('proposals').orderBy('votesYes', 'desc').limit(5).onSnapshot(
        snapshot => {
          topVotedContainer.innerHTML = "";
          if (snapshot.empty) {
            topVotedContainer.innerHTML = "<p>No proposals have been voted on yet.</p>";
            return;
          }
          snapshot.forEach(doc => {
            const proposal = doc.data();
            const proposalId = doc.id;
            const topItem = document.createElement('div');
            topItem.classList.add('vote-item');
            topItem.innerHTML = `
              <h4>${proposal.title}</h4>
              <p>${proposal.details}</p>
              <p>Created by: ${proposal.createdBy}</p>
              <p>Yes Votes: ${proposal.votesYes} | No Votes: ${proposal.votesNo}</p>
              <div class="vote-actions">
                <button class="vote-yes" data-id="${proposalId}">Yes</button>
                <button class="vote-no" data-id="${proposalId}">No</button>
              </div>
            `;
            topVotedContainer.appendChild(topItem);
          });
        },
        err => showModal("Error loading top voted proposals: " + err.message)
      );
    }

    // EDIT/DELETE USER'S PROPOSALS
    userProposalsContainer.addEventListener('click', e => {
      if (e.target.classList.contains('edit-button')) {
        const propId = e.target.getAttribute('data-id');
        openEditForm(propId);
      } else if (e.target.classList.contains('delete-button')) {
        const propId = e.target.getAttribute('data-id');
        deleteProposal(propId);
      }
    });

    // DELETE PROPOSAL
    function deleteProposal(propId) {
      if (!confirm("Are you sure you want to delete this proposal?")) return;
      db.collection('proposals').doc(propId).delete()
        .then(() => showModal("Proposal deleted successfully!"))
        .catch(err => showModal("Error deleting proposal: " + err.message));
    }

    // EDIT PROPOSAL FORM
    function openEditForm(propId) {
      db.collection('proposals').doc(propId).get()
        .then(docSnap => {
          if (!docSnap.exists) {
            showModal("The proposal does not exist or has been deleted.");
            return;
          }
          const proposal = docSnap.data();
          const parentDiv = document.querySelector(`[data-id="${propId}"]`);

          // Check if an edit form already exists
          let editForm = parentDiv.querySelector('.edit-form');
          if (editForm) {
            // Toggle visibility
            editForm.style.display = editForm.style.display === 'block' ? 'none' : 'block';
            return;
          }

          // Create edit form
          editForm = document.createElement('form');
          editForm.classList.add('edit-form');
          editForm.innerHTML = `
            <input type="text" name="editTitle" value="${proposal.title}" required />
            <textarea name="editDetails" rows="5" required>${proposal.details}</textarea>
            <button type="submit">Save Changes</button>
          `;
          parentDiv.appendChild(editForm);
          editForm.style.display = 'block';

          // Handle edit form submission
          editForm.addEventListener('submit', event => {
            event.preventDefault();
            const newTitle = editForm.editTitle.value.trim();
            const newDetails = editForm.editDetails.value.trim();
            if (!newTitle || !newDetails) {
              showModal("Please fill in all fields.");
              return;
            }
            if (containsOffensiveWords(newTitle) || containsOffensiveWords(newDetails)) {
              showModal("Your proposal contains offensive words. Please revise the content.");
              return;
            }
            // Update in Firestore
            db.collection('proposals').doc(propId).update({
              title: newTitle,
              details: newDetails
            })
            .then(() => {
              showModal("Proposal updated successfully!");
              editForm.remove();
            })
            .catch(err => showModal("Error updating proposal: " + err.message));
          });
        })
        .catch(err => showModal("Error fetching proposal: " + err.message));
    }

    // VOTE ON PUBLIC PROPOSALS
    document.addEventListener('click', e => {
      if (e.target.classList.contains('vote-yes') || e.target.classList.contains('vote-no')) {
        const propId = e.target.getAttribute('data-id');
        const voteType = e.target.classList.contains('vote-yes') ? 'votesYes' : 'votesNo';
        if (!currentUser) {
          showModal("You must be logged in to vote.");
          return;
        }
        const propRef = db.collection('proposals').doc(propId);
        propRef.get()
          .then(docSnap => {
            if (!docSnap.exists) {
              showModal("The proposal does not exist.");
              return;
            }
            const propData = docSnap.data();
            if (propData.voters && propData.voters[currentUser.uid]) {
              showModal("You have already voted on this proposal.");
            } else {
              propRef.update({
                [voteType]: firebase.firestore.FieldValue.increment(1),
                [`voters.${currentUser.uid}`]: true
              })
              .then(() => showModal("Thank you for your vote!"))
              .catch(err => showModal("Error voting: " + err.message));
            }
          })
          .catch(err => showModal("Error fetching proposal: " + err.message));
      }
    });

    // SEARCH FUNCTIONALITY
    searchInput.addEventListener('input', () => {
      const query = searchInput.value.trim().toLowerCase();
      const proposals = voteContainer.querySelectorAll('.vote-item');
      proposals.forEach(proposal => {
        const title = proposal.querySelector('h4').textContent.toLowerCase();
        if (title.includes(query)) {
          proposal.style.display = "block";
        } else {
          proposal.style.display = "none";
        }
      });
    });

  </script>
</body>
</html>
