// server.js (Node.js + Express backend)
const express = require('express');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
const app = express();

const SECRET_KEY = 'your_super_secret_key';
const PASSWORD = 'shardwalker2025'; // set your password here
const PORT = 3000;

app.use(express.static('public'));
app.use(bodyParser.json());
app.use(cookieParser());

// Serve login check
app.get('/check-auth', (req, res) => {
    const token = req.cookies.token;
    if (!token) return res.status(401).json({ authenticated: false });

    try {
        jwt.verify(token, SECRET_KEY);
        res.json({ authenticated: true });
    } catch (err) {
        res.status(403).json({ authenticated: false });
    }
});

// Login route
app.post('/login', (req, res) => {
    const { password } = req.body;
    if (password === PASSWORD) {
        const token = jwt.sign({ user: 'admin' }, SECRET_KEY, { expiresIn: '1d' });
        res.cookie('token', token, { httpOnly: true });
        res.json({ success: true });
    } else {
        res.status(403).json({ success: false });
    }
});

// Get current roadmap
app.get('/api/roadmap', (req, res) => {
    const data = fs.readFileSync(path.join(__dirname, 'roadmap.json'));
    res.json(JSON.parse(data));
});

// Update roadmap status
app.post('/api/roadmap', (req, res) => {
    const token = req.cookies.token;
    if (!token || !jwt.verify(token, SECRET_KEY)) {
        return res.status(403).json({ success: false });
    }
    const { id, status } = req.body;
    const filePath = path.join(__dirname, 'roadmap.json');
    const roadmap = JSON.parse(fs.readFileSync(filePath));
    const phase = roadmap.find(p => p.id === id);
    if (phase) {
        phase.status = status;
        fs.writeFileSync(filePath, JSON.stringify(roadmap, null, 2));
        res.json({ success: true });
    } else {
        res.status(404).json({ success: false });
    }
});

app.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`));
