const express = require('express');
const path = require('path');
const fs = require('fs').promises;
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const app = express();
const port = 3000;

const JWT_SECRET = process.env.JWT_SECRET || 'your_secure_jwt_secret';
const ADMIN_PASSWORD_HASH = '$2a$10$ZGoPtwYYkpS3h0tUx.v4ue5X5P8zkd/ne6hJOJ4cY62jJLFV3GM4O';

app.use(express.json());

app.use(express.static(path.join(__dirname, 'public')));

app.post('/api/login', async (req, res) => {
    const { password } = req.body;
    if (!password) {
        return res.status(400).send('Password is required');
    }

    try {
        const isPasswordValid = await bcrypt.compare(password, ADMIN_PASSWORD_HASH);
        if (!isPasswordValid) {
            return res.status(401).send('Invalid password');
        }
        const token = jwt.sign({ role: 'admin' }, JWT_SECRET, { expiresIn: '1h' });
        res.json({ token });
    } catch (err) {
        console.error('Failed to login:', err);
        res.sendStatus(500);
    }
});

function authenticateJWT(req, res, next) {
    const authHeader = req.headers.authorization;
    const token = authHeader && authHeader.split(' ')[1];

    if (token) {
        jwt.verify(token, JWT_SECRET, (err, user) => {
            if (err) {
                return res.sendStatus(403);
            }
            req.user = user;
            next();
        });
    } else {
        res.sendStatus(401);
    }
}

app.get('/api/data', authenticateJWT, async (req, res) => {
    if (req.user.role !== 'admin') {
        return res.sendStatus(403);
    }

    try {
        const visitorsData = await fs.readFile('visitors.json', 'utf8').catch(() => '[]');
        const statsData = await fs.readFile('stats.json', 'utf8').catch(() => '{}');

        res.json({
            visitors: JSON.parse(visitorsData),
            stats: JSON.parse(statsData)
        });
    } catch (err) {
        console.error('Failed to retrieve data:', err);
        res.sendStatus(500);
    }
});

app.get('/api/check-new-user', async (req, res) => {
    const visitorIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;

    try {
        const content = await fs.readFile('visitors.json', 'utf8').catch(() => '[]');
        const visitors = JSON.parse(content);

        const newUser = !visitors.some(visitor => visitor.ip === visitorIp);
        res.json(newUser);
    } catch (err) {
        console.error('Failed to check new user:', err);
        res.sendStatus(500);
    }
});

app.post('/api/track', async (req, res) => {
    const visitorInfo = req.body;
    const visitorIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;

    try {
        let content = await fs.readFile('visitors.json', 'utf8').catch(() => '[]');
        const visitors = JSON.parse(content);
        const currentTime = new Date().toISOString();

        let visitorRecord = visitors.find(visitor => visitor.ip === visitorIp);
        if (visitorRecord) {
            visitorRecord.count++;
            visitorRecord.lastVisit = currentTime;
        } else {
            visitors.push({
                ip: visitorIp,
                deviceInfo: visitorInfo.deviceInfo,
                firstVisit: currentTime,
                lastVisit: currentTime,
                count: 1
            });
        }

        await fs.writeFile('visitors.json', JSON.stringify(visitors, null, 2));
        res.sendStatus(200);
    } catch (err) {
        console.error('Failed to process visitor data:', err);
        res.sendStatus(500);
    }
});

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

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

body {
    margin: 0;
    padding: 0;
    height: 100vh;
    width: 100vw;
    overflow: hidden;
    background-image: url('background.gif'); /* Укажите путь к вашему GIF-файлу */
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.container {
    position: relative;
    z-index: 1;
    color: white;
    text-align: center;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    padding-top: 10vh; 
}

.loading-wrapper {
    position: absolute;
    bottom: 50px; 
    left: 50%;
    transform: translateX(-50%);
    z-index: 2; 
}

.loading-gif {
    width: 50px;
    height: 50px; 
    border-radius: 50%;
}

.title {
    font-size: 3vw;
    font-weight: bold;
    margin-bottom: 10px;
}

.countdown-timer {
    font-size: 2.5vw;
    font-weight: bold;
}

.random-text {
    font-size: 2vw;
    margin-top: 10px;
}

@media (max-width: 768px) {
    .loading-wrapper {
        bottom: auto;
        top: 70%;
    }

    .random-text {
        margin-top: 20px;
    }

    .title {
        font-size: 9vw;
    }

    .countdown-timer {
        font-size: 7vw;
    }

    .random-text {
        font-size: 6vw;
    }
}

#introGif {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: black;
    display: none; /* скрыто по умолчанию для предотвращения мерцания */
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

#intro-animation {
    width: 100%;
    height: 100%;
    object-fit: cover;
}