<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مولد روابط الأفلام والمسلسلات باستخدام TMDb</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f0f4f8;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            color: #333;
        }
        h1 {
            color: #00B5CA;
            text-align: center;
        }
        .controls {
            background-color: #ffffff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 600px;
            text-align: center;
        }
        label, input, button, select {
            font-size: 16px;
            margin: 8px 0;
            display: block;
            width: 100%;
            box-sizing: border-box;
        }
        input, select {
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            transition: border-color 0.3s;
        }
        input:focus, select:focus {
            outline: none;
            border-color: #00B5CA;
        }
        .buttons-container {
            display: flex;
            justify-content: space-around;
            gap: 10px;
            margin-top: 15px;
        }
        button {
            background-color: #00B5CA;
            color: white;
            border: none;
            cursor: pointer;
            padding: 12px 25px;
            border-radius: 5px;
            font-weight: bold;
            transition: background-color 0.3s, transform 0.2s;
        }
        button:hover {
            background-color: #0095a8;
            transform: translateY(-2px);
        }
        button:active {
            transform: translateY(0);
        }
        #results {
            margin-top: 20px;
            background-color: #ffffff;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            width: 100%;
            max-width: 600px;
        }
        #results ul {
            list-style-type: none;
            padding: 0;
            margin: 0;
        }
        #results li {
            padding: 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            text-align: right;
            transition: background-color 0.2s;
        }
        #results li:hover {
            background-color: #f0f4f8;
        }
        #links-container {
            width: 100%;
            max-width: 600px;
            margin-top: 20px;
        }
        .link-section {
            background-color: #ffffff;
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 8px;
            position: relative;
        }
        .link-section h3 {
            margin-top: 0;
            color: #007991;
            border-bottom: 2px solid #00B5CA;
            padding-bottom: 5px;
        }
        .server-block {
            margin-top: 15px;
        }
        .server-block h4 {
            margin: 0 0 10px 0;
            color: #555;
        }
        textarea {
            width: 100%;
            height: 150px;
            padding: 10px;
            font-size: 14px;
            margin-top: 10px;
            resize: vertical;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        .copy-button {
            margin-top: 10px;
            width: auto;
            align-self: flex-start;
        }
        .alert {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.5s;
        }
        .alert.show {
            opacity: 1;
        }
    </style>
</head>
<body>
    <h1>مولد روابط الأفلام والمسلسلات</h1>

    <div class="controls">
        <label for="mediaType">نوع الوسائط:</label>
        <select id="mediaType">
            <option value="movie">فيلم</option>
            <option value="tv">مسلسل</option>
        </select>
        
        <label for="searchQuery">اسم الوسائط:</label>
        <input type="text" id="searchQuery" placeholder="أدخل اسم الفيلم أو المسلسل">
        <button onclick="searchByName()">بحث</button>
        
        <label for="mediaId">أو أدخل معرّف الوسائط (TMDb ID):</label>
        <input type="text" id="mediaId" placeholder="أدخل معرّف الوسائط">
        <button onclick="generateLinks()">توليد الروابط</button>
    </div>
    
    <div id="results"></div>
    <div id="links-container"></div>
    <div id="alertBox" class="alert"></div>

    <script>
        const API_KEY = '6ebe4cbba10ed6c6665cb4c02c48ba76';
        
        const servers = {
            'vidlink.pro': {
                movieBase: 'https://vidlink.pro/movie/',
                tvBase: 'https://vidlink.pro/tv/',
                queryParams: '?primaryColor=00B5CA&secondaryColor=00B5CA&iconColor=00B5CA&nextbutton=true'
            },
            'vidfast.pro': {
                movieBase: 'https://vidfast.pro/movie/',
                tvBase: 'https://vidfast.pro/tv/',
                queryParams: '?theme=00B5CA&poster&hideServer&autoPlay=true'
            },
            'videasy.net': {
                movieBase: 'https://player.videasy.net/movie/',
                tvBase: 'https://player.videasy.net/tv/',
                queryParams: '?color=00B5CA'
            },
            'watchug.to': {
                movieBase: 'https://x.watchug.to/embed/',
                tvBase: 'https://x.watchug.to/embed/',
                queryParams: ''
            }
        };

        function showAlert(message) {
            const alertBox = document.getElementById('alertBox');
            alertBox.innerText = message;
            alertBox.classList.add('show');
            setTimeout(() => {
                alertBox.classList.remove('show');
            }, 3000);
        }

        async function copyToClipboard(textArea) {
            try {
                await navigator.clipboard.writeText(textArea.value);
                showAlert("تم نسخ الروابط بنجاح!");
            } catch (err) {
                textArea.select();
                document.execCommand("copy");
                showAlert("تم نسخ الروابط بنجاح! (باستخدام طريقة بديلة)");
            }
        }

        async function searchByName() {
            const mediaType = document.getElementById("mediaType").value;
            const searchQuery = document.getElementById("searchQuery").value;
            const resultsDiv = document.getElementById("results");
            resultsDiv.innerHTML = "";

            if (!searchQuery.trim()) {
                resultsDiv.innerHTML = "<p>يرجى إدخال اسم للبحث.</p>";
                return;
            }

            try {
                const response = await fetch(`https://api.themoviedb.org/3/search/${mediaType}?api_key=${API_KEY}&query=${encodeURIComponent(searchQuery)}&language=ar`);
                const data = await response.json();

                if (data.results.length > 0) {
                    const ul = document.createElement("ul");
                    data.results.forEach(item => {
                        const title = item.title || item.name;
                        const year = (item.release_date || item.first_air_date || "").substring(0, 4);
                        const li = document.createElement("li");
                        li.innerText = `${title} (${year}) - ID: ${item.id}`;
                        li.onclick = () => {
                            document.getElementById("mediaId").value = item.id;
                            resultsDiv.innerHTML = `<p>تم اختيار: <strong>${title}</strong> (ID: ${item.id})</p>`;
                            generateLinks();
                        };
                        ul.appendChild(li);
                    });
                    resultsDiv.appendChild(ul);
                } else {
                    resultsDiv.innerHTML = "<p>لم يتم العثور على نتائج. حاول البحث باسم آخر.</p>";
                }
            } catch (error) {
                resultsDiv.innerHTML = "<p>حدث خطأ أثناء البحث. يرجى التحقق من اتصالك بالإنترنت والمحاولة مجددًا.</p>";
                console.error(error);
            }
        }

        async function generateLinks() {
            const mediaType = document.getElementById("mediaType").value;
            const mediaId = document.getElementById("mediaId").value;
            const linksContainer = document.getElementById("links-container");
            linksContainer.innerHTML = "";

            if (!mediaId) {
                linksContainer.innerHTML = "<p>يرجى إدخال معرّف الوسائط أو البحث بالاسم أولاً.</p>";
                return;
            }

            try {
                if (mediaType === "movie") {
                    const section = document.createElement("div");
                    section.className = "link-section";
                    section.innerHTML = `<h3>روابط الفيلم</h3>`;
                    
                    Object.keys(servers).forEach((serverName, index) => {
                        const server = servers[serverName];
                        let link = `${server.movieBase}${mediaId}${server.queryParams}`;

                        const serverBlock = document.createElement("div");
                        serverBlock.className = "server-block";
                        serverBlock.innerHTML = `<h4>Server ${index + 1}: ${serverName}</h4>`;
                        const textArea = document.createElement("textarea");
                        textArea.value = link;
                        textArea.style.height = "50px"; 
                        serverBlock.appendChild(textArea);
                        
                        const copyButton = document.createElement("button");
                        copyButton.className = "copy-button";
                        copyButton.innerText = "نسخ الرابط";
                        copyButton.onclick = () => copyToClipboard(textArea);
                        serverBlock.appendChild(copyButton);

                        section.appendChild(serverBlock);
                    });

                    linksContainer.appendChild(section);

                } else if (mediaType === "tv") {
                    const response = await fetch(`https://api.themoviedb.org/3/tv/${mediaId}?api_key=${API_KEY}&language=ar`);
                    const data = await response.json();

                    if (data.number_of_seasons) {
                        for (let season = 1; season <= data.number_of_seasons; season++) {
                            const section = document.createElement("div");
                            section.className = "link-section";
                            section.innerHTML = `<h3>روابط الموسم ${season}</h3>`;

                            const seasonResponse = await fetch(`https://api.themoviedb.org/3/tv/${mediaId}/season/${season}?api_key=${API_KEY}&language=ar`);
                            const seasonData = await seasonResponse.json();

                            if (seasonData.episodes && seasonData.episodes.length > 0) {
                                Object.keys(servers).forEach((serverName, index) => {
                                    const server = servers[serverName];
                                    let linksText = '';

                                    seasonData.episodes.forEach(episode => {
                                        const episodeNumber = episode.episode_number;
                                        const base = server.tvBase;
                                        let link = '';
                                        if (serverName === 'watchug.to') {
                                            link = `${base}${mediaId}-${season}-${episodeNumber}${server.queryParams}`;
                                        } else {
                                            link = `${base}${mediaId}/${season}/${episodeNumber}${server.queryParams}`;
                                        }
                                        linksText += `${link}\n`;
                                    });

                                    const serverBlock = document.createElement("div");
                                    serverBlock.className = "server-block";
                                    serverBlock.innerHTML = `<h4>Server ${index + 1}: ${serverName}</h4>`;
                                    
                                    const textArea = document.createElement("textarea");
                                    textArea.value = linksText.trim();
                                    serverBlock.appendChild(textArea);
                                    
                                    const copyButton = document.createElement("button");
                                    copyButton.className = "copy-button";
                                    copyButton.innerText = "نسخ كل روابط هذا السيرفر للموسم";
                                    copyButton.onclick = () => copyToClipboard(textArea);
                                    serverBlock.appendChild(copyButton);

                                    section.appendChild(serverBlock);
                                });
                            }
                            linksContainer.appendChild(section);
                        }
                    } else {
                        linksContainer.innerHTML = "<p>لم يتم العثور على بيانات المسلسل. تأكد من المعرّف.</p>";
                    }
                }
            } catch (error) {
                linksContainer.innerHTML = "<p>حدث خطأ أثناء جلب البيانات. تأكد من معرّف الوسائط وحاول مجددًا.</p>";
                console.error(error);
            }
        }
    </script>
</body>
</html>
