// 
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT_ID.appspot.com",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID"
};

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

let currentUser = null;
let points = 0;

// ---------------- MODAL ----------------
function closeModal(){ document.getElementById('modal').style.display='none'; }

function showGuide(){
    const guideContent = `
        <h2>Point Guide</h2>
        <p>1. Watch Video → Watch Ad → +20 points</p>
        <p>2. Read News → Watch Ad → +20 points</p>
        <p>3. Free Tips → Unlock + Watch Ad → +20 points</p>
        <p>4. VIP Tips → Join Viber link</p>
        <p>5. Top/Bottom Ads → Click → +20 points</p>
    `;
    document.getElementById('modal-body').innerHTML = guideContent;
    document.getElementById('modal').style.display='block';
}

function showRegister(){
    const registerForm = `
        <h2>Register</h2>
        <form onsubmit="registerUser(event)">
            <label>Name:</label><br>
            <input type="text" id="username" required><br>
            <label>Phone:</label><br>
            <input type="text" id="phone" required><br><br>
            <button type="submit">Submit</button>
        </form>
    `;
    document.getElementById('modal-body').innerHTML=registerForm;
    document.getElementById('modal').style.display='block';
}

// ---------------- USER ----------------
function registerUser(e){
    e.preventDefault();
    const name = document.getElementById('username').value;
    const phone = document.getElementById('phone').value;

    db.collection("users").add({
        name, phone, points:0, videosWatched:[], newsRead:[]
    }).then((docRef)=>{
        alert("Registered Successfully!");
        currentUser = docRef.id;
        points = 0;
        document.getElementById('points').innerText=points;
        closeModal();
        loadVideos(); loadNews(); loadFreeTips();
    });
}

// ---------------- TOP 20 ----------------
function showTop20(){
    const topListContent = `<h2>Top 20 Users</h2><ol id="top20List"></ol>`;
    document.getElementById('modal-body').innerHTML=topListContent;
    document.getElementById('modal').style.display='block';

    db.collection("users").orderBy("points","desc").limit(20).get()
    .then(querySnapshot=>{
        let listHtml='';
        querySnapshot.forEach(doc=>{
            const data=doc.data();
            listHtml+=`<li>${data.name} - ${data.points} pts</li>`;
        });
        document.getElementById('top20List').innerHTML=listHtml;
    });
}

// ---------------- BANNER ADS ----------------
function clickBanner(position){
    if(!currentUser){ alert("Register first!"); return; }
    alert(`Banner Ad clicked! +20 points`);
    points+=20;
    document.getElementById('points').innerText=points;
    db.collection("users").doc(currentUser).update({points});
}

// ---------------- VIDEOS ----------------
let videos = [];
function loadVideos(){
    db.collection("videos").get().then(snapshot=>{
        videos = snapshot.docs.map(doc=>({id:doc.id,...doc.data()}));
        const container = document.getElementById('videosList');
        container.innerHTML='';
        videos.forEach(v=>{
            container.innerHTML+=`
                <p>${v.title}</p>
                <iframe src="${v.url}" frameborder="0" allowfullscreen></iframe>
                <button class="medium" onclick="watchVideo('${v.id}')">Watch Video +20 Points</button>
            `;
        });
    });
}

function watchVideo(videoId){
    if(!currentUser){ alert("Register first!"); return; }
    const userRef = db.collection("users").doc(currentUser);
    userRef.get().then(doc=>{
        let data=doc.data();
        if(!data.videosWatched.includes(videoId)){
            let newPoints = data.points+20;
            userRef.update({
                points: newPoints,
                videosWatched: firebase.firestore.FieldValue.arrayUnion(videoId)
            });
            points = newPoints;
            document.getElementById('points').innerText=points;
            alert("+20 Points Added!");
        } else { alert("Already watched!"); }
    });
}

// ---------------- NEWS ----------------
let newsList = [];
function loadNews(){
    db.collection("news").get().then(snapshot=>{
        newsList = snapshot.docs.map(doc=>({id:doc.id,...doc.data()}));
        const container = document.getElementById('newsList');
        container.innerHTML='';
        newsList.forEach(n=>{
            container.innerHTML+=`
                <h4>${n.title}</h4>
                <p>${n.content}</p>
                <button class="medium" onclick="readNews('${n.id}')">Watch Ad +20 Points</button>
            `;
        });
    });
}

function readNews(newsId){
    if(!currentUser){ alert("Register first!"); return; }
    const userRef = db.collection("users").doc(currentUser);
    userRef.get().then(doc=>{
        let data = doc.data();
        if(!data.newsRead.includes(newsId)){
            let newPoints = data.points+20;
            userRef.update({
                points: newPoints,
                newsRead: firebase.firestore.FieldValue.arrayUnion(newsId)
            });
            points = newPoints;
            document.getElementById('points').innerText=points;
            alert("+20 Points Added!");
        } else { alert("Already read!"); }
    });
}

// ---------------- FREE TIPS ----------------
let freeTips = [];
function loadFreeTips(){
    db.collection("freetips").get().then(snapshot=>{
        freeTips = snapshot.docs.map(doc=>doc.data().tip);
        const container = document.getElementById('freeTipsList');
        container.innerHTML='';
        freeTips.forEach(tip=>container.innerHTML+=`<li>${tip}</li>`);
    });
}

function unlockFreeTips(){
    if(!currentUser){ alert("Register first!"); return; }
    alert("Watch ad to unlock Free Tips (+20 points)");
    points+=20;
    document.getElementById('points').innerText=points;
    db.collection("users").doc(currentUser).update({points});
    document.getElementById('freeTipsList').style.display='block';
}

// ---------------- ADMIN ----------------
function showAdminDashboard(){
    const adminContent = `
        <h2>Admin Panel (Full Control)</h2>
        <button onclick="addVideoAdmin()">Add Video</button>
        <button onclick="addNewsAdmin()">Add News</button>
        <button onclick="addFreeTipAdmin()">Add Free Tip</button>
        <button onclick="editGuideAdmin()">Edit Point Guide</button>
    `;
    document.getElementById('modal-body').innerHTML=adminContent;
    document.getElementById('modal').style.display='block';
}

function addVideoAdmin(){
    const title = prompt("Video Title:");
    const url = prompt("YouTube URL:");
    if(title && url){ db.collection("videos").add({title,url}); alert("Video added!"); loadVideos(); }
}

function addNewsAdmin(){
    const title = prompt("News Title:");
    const content = prompt("News Content:");
    if(title && content){ db.collection("news").add({title,content}); alert("News added!"); loadNews(); }
}

function addFreeTipAdmin(){
    const tip = prompt("Free Tip:");
    if(tip){ db.collection("freetips").add({tip}); alert("Tip added!"); loadFreeTips(); }
}

function editGuideAdmin(){
    alert("Guide editing demo – implement your guide storage in Firebase if needed");
}

// ---------------- INITIAL LOAD ----------------
window.onload = function(){
    loadVideos();
    loadNews();
    loadFreeTips();
};
