You are an advanced AI designed to excel across all domains and tasks, integrating technical expertise, logical reasoning, creative innovation, and conceptual clarity. Your mission is to deliver highly accurate, efficient, and context-aware solutions, synthesizing technical precision, analytical rigor, creative insights, and visual understanding into every response.


---

Core Directives for Unified Task Handling

1. Comprehensive Understanding of the Task

Analyze the user’s input to extract the core objectives, ensuring clarity of the requirements.

Break down multifaceted tasks to align coding, reasoning, creativity, and visualization seamlessly.


2. Structured and Contextual Outputs

Provide responses in an organized format, tailored to user specifications or defaulting to clear headings, logical flow, and concise steps.

Incorporate necessary technical details, logical frameworks, and creative elements into a unified response.


3. Precision and Practicality

Ensure all outputs—whether code, logic, or creative ideas—are actionable, robust, and aligned with real-world applicability.

Validate solutions with clear justifications or examples.


4. Integrated Problem-Solving Framework

For technical tasks: Generate efficient, scalable, and well-documented solutions, addressing potential bottlenecks or edge cases.

For reasoning and analysis: Apply structured methodologies (e.g., deductive reasoning, causal analysis) for accurate conclusions.

For creativity: Innovate practical yet original solutions, ensuring alignment with the problem context.

For visualization: Use descriptive language or pseudo-visual representations to explain abstract concepts effectively.


5. Critical and Reflective Thinking

Reflect deeply on the task’s requirements, potential challenges, and broader implications.

Offer alternative approaches or highlight trade-offs to maximize user understanding and task outcomes.


6. Adaptable Communication Style

Match the tone and depth to the task’s audience and purpose (e.g., formal for technical reports, conversational for creative brainstorming).

Respect cultural, linguistic, or contextual nuances as necessary.


7. Efficiency and Optimization

Optimize technical outputs for performance, scalability, and resource efficiency.

Refine creative solutions to balance feasibility and innovation.

Ensure logical conclusions are concise, comprehensive, and error-free.



---

Key Features for Unified Performance

Synthesis of Capabilities

Coding and Technical Expertise: Deliver robust, error-free solutions with explanations of design choices.

Logical Analysis: Utilize structured approaches (e.g., causal chains, SWOT analysis) for deep insights.

Creative Ideation: Blend practicality with imagination to propose unique yet actionable solutions.

Visual and Conceptual Support: Simplify complex ideas using pseudo-code, step-by-step explanations, or analogies.


Iterative Refinement

Dynamically refine responses based on user feedback or task evolution during interactions.


Advanced Techniques

Chain-of-Thought Reasoning: Explicitly outline intermediate steps in problem-solving.

Few-Shot Examples: Incorporate example scenarios to guide outputs.

Multimodal Integration: Address tasks that combine text, visuals, and data representation.


Ethical and Transparent Approach

Avoid bias and maintain inclusivity.

Highlight uncertainties or limitations when applicable.



---

Unified Workflow for Any Task

1. Approach and Planning

Start by outlining how the task will be addressed, integrating technical, analytical, creative, and visual aspects.

Present a clear roadmap for execution.


2. Core Response

Deliver the main solution, seamlessly blending:

Code: Clean, optimized, and well-documented.

Logic: Clear reasoning and analysis to justify conclusions.

Creativity: Original ideas or designs aligned with the task context.

Visualization: Conceptual aids, diagrams, or pseudo-representations to enhance understanding.



3. Enhancements and Reflections

Suggest improvements, alternative methods, or optimizations.

Highlight potential challenges or considerations for implementation.



---

Example Use Cases for Unified Tasks

Coding, Analysis, Creativity, and Visualization in Harmony

1. Prompt: “Analyze this dataset, optimize the algorithm, and propose innovative ways to present the insights visually.”

Response:

Provide optimized Python code for data processing.

Analyze trends using statistical methods and offer a concise explanation.

Propose innovative visualizations (e.g., interactive dashboards or graph-based summaries).




2. Prompt: “Design a futuristic city model, integrating technical feasibility and innovative concepts, and explain it step-by-step.”

Response:

Suggest sustainable technologies (e.g., renewable energy integration) with technical specs.

Present creative urban planning concepts (e.g., vertical farming, smart infrastructure).

Use descriptive language or pseudo-diagrams to visualize the city layout.




3. Prompt: “Debug this code and explain why it failed logically, then suggest a creative optimization.”

Response:

Provide corrected code with detailed comments on the error’s root cause.

Suggest a creative enhancement (e.g., new algorithmic approach) for better performance.




4. Prompt: “Explain the concept of neural networks in simple terms, propose a unique application, and provide a high-level code example.”

Response:

Explain neural networks using analogies for clarity.

Propose a novel application (e.g., AI for personalized education).

Provide high-level pseudo-code with comments.



---

Output Structure for Unified Tasks

Introduction: Summarize the task and the planned approach.

Main Content: Deliver integrated outputs (code, logic, creativity, and visualization).

Reflections: Offer insights, optimizations, or open questions for further exploration.



---


Task or instructions or issues: [

Dark theme is not toggling on.
Fix it and Make this into a production ready rss reader client side only web app. 
You know what to do don't ask me.
I just want a really practical, more usefull, more beautiful, more fast, more customisable, more user friendly, more efficient, more effective.
Add every necessary features.
Don't add anything that's need an backend or server to work.
Significantly improve it further.
add a very broad image supports.
make all of the process more fast, effective and efficient.(eg; parsing, extracting, )
Do EVERYTHING you can in one response.
Don't add any service worker for now. ]

Response: [Send the fully working full codes in one HTML file.]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Syndicate - Your Ultimate RSS Reader</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        /* Customizable Scrollbar */
        .custom-scrollbar::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        /* Dark Mode */
        .dark .custom-scrollbar::-webkit-scrollbar-track {
            background: #333;
        }
        .dark .custom-scrollbar::-webkit-scrollbar-thumb {
            background: #bbb;
        }
        .dark .custom-scrollbar::-webkit-scrollbar-thumb:hover {
            background: #999;
        }

        /* Feed Card Styling */
        .feed-card {
            transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
        }
        .feed-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        /* Spinner */
        .lds-dual-ring {
            display: inline-block;
            width: 80px;
            height: 80px;
        }
        .lds-dual-ring:after {
            content: " ";
            display: block;
            width: 64px;
            height: 64px;
            margin: 8px;
            border-radius: 50%;
            border: 6px solid #fff;
            border-color: #fff transparent #fff transparent;
            animation: lds-dual-ring 1.2s linear infinite;
        }
        @keyframes lds-dual-ring {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }

        /* Custom Select */
        select {
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='%234A5568'%3E%3Cpath d='M6.293 9.293a1 1 0 011.414 0L10 11.586l2.293-2.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 0.75rem center;
            background-size: 1em;
        }
        .dark select {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='%23A0AEC0'%3E%3Cpath d='M6.293 9.293a1 1 0 011.414 0L10 11.586l2.293-2.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z'/%3E%3C/svg%3E");
        }

        /* No feeds message */
        .no-feeds {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 200px;
          font-size: 1.2rem;
          color: #718096; /* Tailwind gray-500 */
        }
    </style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 transition-colors duration-200 font-sans">
    <div class="min-h-screen flex flex-col">
        <!-- Header -->
        <header class="bg-white dark:bg-gray-800 shadow-md sticky top-0 z-40">
            <div class="container mx-auto px-4 py-4">
                <div class="flex justify-between items-center">
                    <h1 class="text-3xl font-bold text-gray-800 dark:text-white">
                        <i class="fas fa-rss-square mr-2 text-blue-500"></i>
                        Syndicate
                    </h1>
                    <div class="flex space-x-4">
                        <button id="searchBtn" title="Search" class="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none">
                            <i class="fas fa-search text-gray-600 dark:text-gray-300"></i>
                        </button>
                        <button id="themeToggle" title="Toggle Theme" class="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none">
                            <i class="fas fa-moon text-gray-600 dark:text-gray-300"></i>
                        </button>
                        <button id="settingsBtn" title="Settings" class="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none">
                            <i class="fas fa-cog text-gray-600 dark:text-gray-300"></i>
                        </button>
                    </div>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="container mx-auto px-4 py-8 flex-grow">
            <!-- Feed Management -->
            <div class="mb-8">
                <div class="flex flex-wrap gap-4 mb-4">
                    <input type="url" id="feedUrl" placeholder="Enter RSS feed URL (e.g., https://www.example.com/rss)" required
                           class="flex-1 p-3 border rounded-md dark:bg-gray-800 dark:text-white dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                           pattern="https?://.+">
                    <button id="addFeedBtn" title="Add Feed"
                            class="px-6 py-3 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <i class="fas fa-plus mr-2"></i> Add
                    </button>
                </div>
                <h2 class="text-xl font-semibold mb-4 dark:text-white">Your Feeds</h2>
                <div id="feedList" class="space-y-2 custom-scrollbar max-h-48 overflow-y-auto">
                    <!-- Feed list will be rendered here -->
                </div>
            </div>

            <!-- Search Bar (Initially Hidden) -->
            <div id="searchBar" class="mb-8 hidden">
                <input type="text" id="searchInput" placeholder="Search articles..."
                       class="w-full p-3 border rounded-md dark:bg-gray-800 dark:text-white dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- Feed Content -->
            <div id="feedContent" class="grid gap-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                <!-- Feed items will be dynamically inserted here -->
            </div>

            <!-- Loading Indicator -->
            <div id="loading" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex justify-center items-center z-50 hidden">
                <div class="lds-dual-ring"></div>
            </div>
        </main>

        <!-- Footer -->
        <footer class="bg-white dark:bg-gray-800 shadow-md mt-auto py-6">
            <div class="container mx-auto px-4">
                <p class="text-center text-gray-600 dark:text-gray-400">
                    © 2023 <a href="#" class="hover:text-blue-500">Syndicate</a> -
                    Powered by <a href="#" class="hover:text-blue-500" target="_blank" rel="noopener noreferrer">You</a>
                </p>
            </div>
        </footer>

        <!-- Settings Modal -->
        <div id="settingsModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
            <div class="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white dark:bg-gray-800 p-6 rounded-lg shadow-xl w-full max-w-md">
                <h2 class="text-2xl font-bold mb-4 dark:text-white">Settings</h2>
                <div class="space-y-4">
                    <div>
                        <label for="articlesPerFeed" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Articles per Feed
                        </label>
                        <input type="number" id="articlesPerFeed" min="1" max="100" value="10"
                               class="w-full p-3 border rounded-md dark:bg-gray-700 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label for="refreshInterval" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Auto Refresh Interval (minutes)
                        </label>
                        <input type="number" id="refreshInterval" min="1" max="60" value="5"
                               class="w-full p-3 border rounded-md dark:bg-gray-700 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label for="enableCache" class="flex items-center">
                            <input type="checkbox" id="enableCache" class="form-checkbox h-5 w-5 text-blue-600">
                            <span class="ml-2 text-gray-700 dark:text-gray-300">Enable Cache</span>
                        </label>
                    </div>
                    <div>
                        <label for="displayMode" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Display Mode
                        </label>
                        <select id="displayMode"
                                class="w-full p-3 border rounded-md dark:bg-gray-700 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="grid">Grid</option>
                            <option value="list">List</option>
                        </select>
                    </div>
                </div>
                <div class="mt-6 flex justify-end space-x-4">
                    <button id="closeSettings"
                            class="px-4 py-2 text-gray-600 hover:text-gray-800 dark:text-gray-400 focus:outline-none">
                        Cancel
                    </button>
                    <button id="saveSettings"
                            class="px-6 py-3 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        Save
                    </button>
                </div>
            </div>
        </div>

        <!-- Article Modal -->
        <div id="articleModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
            <div class="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white dark:bg-gray-800 p-6 rounded-lg shadow-xl w-full max-w-4xl h-3/4 overflow-y-auto custom-scrollbar">
                <h2 id="articleTitle" class="text-2xl font-bold mb-4 dark:text-white"></h2>
                <p id="articleDate" class="text-sm text-gray-600 dark:text-gray-400 mb-4"></p>
                <div id="articleContent" class="prose dark:prose-invert max-w-none mb-6"></div>
                <div class="flex justify-between items-center">
                    <a id="articleLink" href="#" target="_blank" rel="noopener noreferrer"
                       class="inline-block px-6 py-3 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <i class="fas fa-external-link-alt mr-2"></i> Read Original
                    </a>
                    <button id="closeArticle"
                            class="px-4 py-2 text-gray-600 hover:text-gray-800 dark:text-gray-400 focus:outline-none">
                        Close
                    </button>
                </div>
            </div>
        </div>

        <!-- Notification Container -->
        <div id="notificationContainer" class="fixed bottom-4 right-4 z-50">
            <!-- Notifications will be dynamically inserted here -->
        </div>
    </div>

    <script>
        class RSSReader {
            constructor() {
                this.feeds = this.loadFeeds();
                this.settings = this.loadSettings();
                this.proxyUrl = 'https://api.allorigins.win/raw?url=';
                this.refreshTimer = null;
                this.currentArticles = [];
                this.init();
            }

            init() {
                this.setupEventListeners();
                this.applyTheme();
                this.renderFeedList();
                this.loadAndRenderFeeds();
                this.startAutoRefresh();
                if (this.feeds.length === 0) {
                    this.showWelcomeMessage();
                }
            }

            loadFeeds() {
                return JSON.parse(localStorage.getItem('rssFeeds') || '[]');
            }

             loadSettings() {
                return JSON.parse(localStorage.getItem('rssSettings') || JSON.stringify({
                    articlesPerFeed: 10,
                    refreshInterval: 5,
                    enableCache: true,
                    theme: 'light',
                    displayMode: 'grid'
                }));
            }

             saveFeeds() {
                localStorage.setItem('rssFeeds', JSON.stringify(this.feeds));
            }

            saveSettings() {
                localStorage.setItem('rssSettings', JSON.stringify(this.settings));
            }

            setupEventListeners() {
                document.getElementById('addFeedBtn').addEventListener('click', () => this.addFeed());
                document.getElementById('settingsBtn').addEventListener('click', () => this.openSettings());
                document.getElementById('closeSettings').addEventListener('click', () => this.closeSettings());
                document.getElementById('saveSettings').addEventListener('click', () => this.saveSettingsChanges());
                document.getElementById('themeToggle').addEventListener('click', () => this.toggleTheme());
                document.getElementById('searchBtn').addEventListener('click', () => this.toggleSearch());
                document.getElementById('searchInput').addEventListener('input', (e) => this.searchArticles(e.target.value));
                document.getElementById('closeArticle').addEventListener('click', () => this.closeArticleModal());
                document.addEventListener('keydown', (e) => {
                    if (e.key === 'Escape') {
                        this.closeSettings();
                        this.closeArticleModal();
                    }
                });
                window.addEventListener('storage', (e) => {
                    if (e.key === 'rssFeeds') {
                        this.feeds = this.loadFeeds();
                        this.loadAndRenderFeeds();
                        this.renderFeedList();
                    } else if (e.key === 'rssSettings') {
                        this.settings = this.loadSettings();
                        this.applySettings();
                    }
                });
            }

            applyTheme() {
                if (this.settings.theme === 'dark') {
                    document.documentElement.classList.add('dark');
                } else {
                    document.documentElement.classList.remove('dark');
                }
            }

            toggleTheme() {
                this.settings.theme = this.settings.theme === 'light' ? 'dark' : 'light';
                this.applyTheme();
                this.saveSettings();
            }

            async addFeed() {
                const input = document.getElementById('feedUrl');
                const url = input.value.trim();
                const isValidUrl = /^(https?):\/\/[^\s/$.?#].[^\s]*$/i.test(url);

                if (!url) {
                    this.showNotification('Please enter a feed URL.', 'error');
                    return;
                }

                if (!isValidUrl) {
                    this.showNotification('Please enter a valid URL.', 'error');
                    return;
                }

                if (this.feeds.some(feed => feed.url === url)) {
                    this.showNotification('Feed already exists.', 'error');
                    return;
                }

                this.showLoading();
                try {
                    const feed = await this.fetchFeed(url);
                    this.feeds.push({
                        url,
                        title: feed.title,
                        lastUpdated: new Date().toISOString()
                    });
                    this.saveFeeds();
                    this.loadAndRenderFeeds();
                    this.renderFeedList();
                    input.value = '';
                    this.showNotification(`Feed "${feed.title}" added successfully!`, 'success');
                } catch (error) {
                    console.error('Error adding feed:', error);
                    this.showNotification('Error adding feed. Please check the URL and try again.', 'error');
                } finally {
                    this.hideLoading();
                }
            }

            async fetchFeed(url) {
                try {
                    const response = await fetch(this.proxyUrl + encodeURIComponent(url), {
                        cache: this.settings.enableCache ? 'default' : 'no-store'
                    });
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                     const text = await response.text();
                    return this.parseFeed(text, url);
                } catch (error) {
                    throw new Error('Failed to fetch feed');
                }
            }

            parseFeed(xml, feedUrl) {
                const parser = new DOMParser();
                const doc = parser.parseFromString(xml, 'application/xml');
                const parseError = doc.querySelector('parsererror');
                if (parseError) {
                   console.error('Error parsing XML:', parseError);
                    throw new Error('Invalid RSS feed');
                }

                const channel = doc.querySelector('channel');
                const items = Array.from(doc.querySelectorAll('item'))
                    .slice(0, this.settings.articlesPerFeed)
                    .map(item => ({
                       title: item.querySelector('title')?.textContent || 'No title',
                        link: item.querySelector('link')?.textContent || '#',
                         description: this.extractContent(item, 'description'),
                        content: this.extractContent(item, 'encoded'),
                         pubDate: item.querySelector('pubDate')?.textContent || '',
                        image: this.extractImage(item),
                        feedUrl: feedUrl
                    }));

                 return {
                    title: channel.querySelector('title')?.textContent || 'Unknown Feed',
                     items
                };
            }

              extractContent(item, type) {
                const content = item.querySelector(`content\\:${type}, ${type}`);
                if (!content) return '';

                const textContent = content.textContent;
                const dom = new DOMParser().parseFromString(textContent, 'text/html');
                 return dom.body.textContent || "";
            }

              extractImage(item) {
                 const contentEncoded = item.querySelector('content\\:encoded, encoded')?.textContent;
                if (contentEncoded) {
                    const match = contentEncoded.match(/<img[^>]+src="([^">]+)"/);
                    if (match) return match[1];
                }

                const mediaContent = item.querySelector('media\\:content, content');
                if (mediaContent && mediaContent.getAttribute('url') && mediaContent.getAttribute('type') && mediaContent.getAttribute('type').startsWith('image/')) {
                    return mediaContent.getAttribute('url');
                 }

                 const description = item.querySelector('description')?.textContent;
                 if (description) {
                    const match = description.match(/<img[^>]+src="([^">]+)"/);
                    if (match) return match[1];
                }
                return null;
             }

              async loadAndRenderFeeds() {
                const container = document.getElementById('feedContent');
                container.innerHTML = '';

                if (this.feeds.length === 0) {
                     this.showWelcomeMessage();
                     return;
                }

                this.showLoading();

                try {
                    this.currentArticles = [];
                    const feedPromises = this.feeds.map(feed => this.fetchFeed(feed.url));
                    const feedResults = await Promise.allSettled(feedPromises);

                   feedResults.forEach((result, index) => {
                        if (result.status === 'fulfilled') {
                            this.currentArticles.push(...result.value.items);
                        } else {
                            console.error(`Error fetching feed ${this.feeds[index].url}:`, result.reason);
                         }
                   });

                   this.currentArticles.sort((a, b) => new Date(b.pubDate) - new Date(a.pubDate));

                   if (this.settings.displayMode === 'grid') {
                        container.classList.remove('flex', 'flex-col');
                        container.classList.add('grid', 'md:grid-cols-2', 'lg:grid-cols-3', 'xl:grid-cols-4');
                    } else {
                        container.classList.remove('grid', 'md:grid-cols-2', 'lg:grid-cols-3', 'xl:grid-cols-4');
                        container.classList.add('flex', 'flex-col');
                    }

                    this.currentArticles.forEach(item => {
                       container.appendChild(this.createArticleCard(item));
                   });

                   container.querySelectorAll('.feed-card').forEach(card => {
                        card.addEventListener('click', (e) => {
                            if (!e.target.closest('a')) {
                                this.openArticleModal(card.dataset.link);
                            }
                        });
                    });
                } catch (error) {
                   console.error('Error rendering feeds:', error);
                    this.showNotification('Error loading feeds. Please try again later.', 'error');
               } finally {
                   this.hideLoading();
                }
           }

            createArticleCard(item) {
                const card = document.createElement('article');
                 card.className = `feed-card bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden cursor-pointer ${this.settings.displayMode === 'list' ? 'mb-4' : ''}`;
                card.dataset.link = item.link;

                if (item.image) {
                    const img = document.createElement('img');
                   img.src = item.image;
                    img.alt = '';
                     img.className = 'w-full h-48 object-cover';
                    img.onerror = () => img.style.display = 'none';
                     card.appendChild(img);
                }

                const contentDiv = document.createElement('div');
                 contentDiv.className = 'p-4';

                const title = document.createElement('h3');
                title.className = 'text-lg font-semibold mb-2 dark:text-white line-clamp-2';
                 title.textContent = item.title;
                contentDiv.appendChild(title);

                 const date = document.createElement('p');
                 date.className = 'text-gray-600 dark:text-gray-400 text-sm mb-4';
                date.textContent = new Date(item.pubDate).toLocaleDateString();
                contentDiv.appendChild(date);

                const description = document.createElement('div');
                 description.className = 'text-gray-700 dark:text-gray-300 mb-4 line-clamp-3';
                description.innerHTML = item.description;
                contentDiv.appendChild(description);

                 const readMore = document.createElement('a');
                readMore.href = item.link;
                 readMore.target = '_blank';
                readMore.rel = 'noopener noreferrer';
                 readMore.className = 'inline-block px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500';
                 readMore.textContent = 'Read More';
                contentDiv.appendChild(readMore);

               card.appendChild(contentDiv);
                return card;
            }

            renderFeedList() {
                const feedListContainer = document.getElementById('feedList');
                feedListContainer.innerHTML = '';

               this.feeds.forEach((feed, index) => {
                    const feedItem = document.createElement('div');
                    feedItem.className = 'bg-gray-200 dark:bg-gray-700 p-3 rounded-md flex items-center justify-between hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors duration-200';

                    const feedTitle = document.createElement('span');
                    feedTitle.className = 'font-medium text-gray-800 dark:text-gray-200 line-clamp-1';
                     feedTitle.textContent = feed.title;
                    feedItem.appendChild(feedTitle);

                    const actions = document.createElement('div');

                     const refreshBtn = document.createElement('button');
                   refreshBtn.className = 'text-blue-500 hover:text-blue-700 dark:text-blue-300 dark:hover:text-blue-500 p-2 focus:outline-none';
                    refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i>';
                    refreshBtn.title = 'Refresh Feed';
                     refreshBtn.addEventListener('click', async () => {
                        this.showLoading();
                        try {
                             const updatedFeed = await this.fetchFeed(feed.url);
                             this.currentArticles = this.currentArticles.filter(article => article.feedUrl !== feed.url);
                             this.currentArticles.push(...updatedFeed.items);
                            this.currentArticles.sort((a, b) => new Date(b.pubDate) - new Date(a.pubDate));
                            this.loadAndRenderFeeds();
                            this.showNotification(`Feed "${feed.title}" refreshed!`, 'success');
                        } catch (error) {
                           console.error('Error refreshing feed:', error);
                             this.showNotification(`Error refreshing feed "${feed.title}".`, 'error');
                        } finally {
                            this.hideLoading();
                         }
                    });
                    actions.appendChild(refreshBtn);

                     const deleteBtn = document.createElement('button');
                    deleteBtn.className = 'text-red-500 hover:text-red-700 dark:text-red-300 dark:hover:text-red-500 p-2 focus:outline-none';
                    deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
                    deleteBtn.title = 'Delete Feed';
                     deleteBtn.addEventListener('click', () => {
                       if (confirm(`Are you sure you want to delete the feed "${feed.title}"?`)) {
                           this.feeds.splice(index, 1);
                            this.saveFeeds();
                            this.loadAndRenderFeeds();
                            this.renderFeedList();
                            this.showNotification(`Feed "${feed.title}" deleted!`, 'info');
                        }
                    });
                    actions.appendChild(deleteBtn);

                    feedItem.appendChild(actions);
                   feedListContainer.appendChild(feedItem);
                });
            }

            openSettings() {
                const settingsModal = document.getElementById('settingsModal');
                settingsModal.classList.remove('hidden');
                document.getElementById('articlesPerFeed').value = this.settings.articlesPerFeed;
                document.getElementById('refreshInterval').value = this.settings.refreshInterval;
                 document.getElementById('enableCache').checked = this.settings.enableCache;
                 document.getElementById('displayMode').value = this.settings.displayMode;
           }

            closeSettings() {
                const settingsModal = document.getElementById('settingsModal');
                settingsModal.classList.add('hidden');
            }

            saveSettingsChanges() {
                this.settings.articlesPerFeed = parseInt(document.getElementById('articlesPerFeed').value);
                 this.settings.refreshInterval = parseInt(document.getElementById('refreshInterval').value);
                 this.settings.enableCache = document.getElementById('enableCache').checked;
                 this.settings.displayMode = document.getElementById('displayMode').value;
                 this.saveSettings();
                 this.closeSettings();
                this.applySettings();
                this.showNotification('Settings saved!', 'success');
           }

            applySettings() {
               this.startAutoRefresh();
               this.loadAndRenderFeeds();
                this.applyTheme();
            }

            startAutoRefresh() {
                if (this.refreshTimer) {
                    clearInterval(this.refreshTimer);
                }
                if (this.settings.refreshInterval > 0) {
                    this.refreshTimer = setInterval(() => {
                        this.loadAndRenderFeeds();
                    }, this.settings.refreshInterval * 60 * 1000);
                }
            }

            toggleSearch() {
                const searchBar = document.getElementById('searchBar');
                searchBar.classList.toggle('hidden');
                if (!searchBar.classList.contains('hidden')) {
                    document.getElementById('searchInput').focus();
                }
            }

            searchArticles(query) {
                query = query.toLowerCase();
                const container = document.getElementById('feedContent');
                container.innerHTML = '';

                const filteredArticles = this.currentArticles.filter(article =>
                    article.title.toLowerCase().includes(query) ||
                    article.description.toLowerCase().includes(query)
                );

               if (filteredArticles.length === 0) {
                    const noResultsMessage = document.createElement('div');
                    noResultsMessage.className = 'text-center text-gray-600 dark:text-gray-400';
                    noResultsMessage.textContent = 'No articles found matching your search.';
                    container.appendChild(noResultsMessage);
                } else {
                    filteredArticles.forEach(item => {
                        container.appendChild(this.createArticleCard(item));
                    });
                }
            }

             openArticleModal(link) {
                const article = this.currentArticles.find(a => a.link === link);
                if (!article) return;

                const modal = document.getElementById('articleModal');
                const title = document.getElementById('articleTitle');
                 const date = document.getElementById('articleDate');
                const content = document.getElementById('articleContent');
                 const articleLink = document.getElementById('articleLink');

                title.textContent = article.title;
               date.textContent = new Date(article.pubDate).toLocaleString();
                content.innerHTML = article.content || article.description;
                articleLink.href = article.link;

                modal.classList.remove('hidden');
            }

             closeArticleModal() {
                const modal = document.getElementById('articleModal');
               modal.classList.add('hidden');
            }

            showLoading() {
                document.getElementById('loading').classList.remove('hidden');
            }

           hideLoading() {
                document.getElementById('loading').classList.add('hidden');
            }

            showNotification(message, type = 'info') {
                const container = document.getElementById('notificationContainer');
                const notification = document.createElement('div');
               notification.className = `p-4 rounded-lg text-white shadow-lg mb-2 ${type === 'error' ? 'bg-red-500' : type === 'success' ? 'bg-green-500' : 'bg-blue-500'}`;
                notification.textContent = message;

                const closeBtn = document.createElement('button');
                 closeBtn.className = 'absolute top-2 right-2 text-white';
                closeBtn.innerHTML = '<i class="fas fa-times"></i>';
                 closeBtn.addEventListener('click', () => {
                    container.removeChild(notification);
                });
                notification.appendChild(closeBtn);

                 container.appendChild(notification);

               setTimeout(() => {
                   if (container.contains(notification)) {
                         container.removeChild(notification);
                     }
                }, 5000);
           }

            showWelcomeMessage() {
                                const container = document.getElementById('feedContent');
                container.innerHTML = '';
                const welcomeMessage = document.createElement('div');
                welcomeMessage.className = 'flex flex-col items-center justify-center h-full';
                welcomeMessage.innerHTML = `
                    <div class="text-center">
                        <h2 class="text-2xl font-bold text-gray-700 dark:text-gray-200 mb-4">Welcome to Syndicate!</h2>
                        <p class="text-gray-600 dark:text-gray-400 mb-6">Your personalized RSS reader awaits.</p>
                        <div class="flex items-center bg-gray-200 dark:bg-gray-800 p-4 rounded-lg shadow-md mb-6">
                            <i class="fas fa-info-circle text-blue-500 text-2xl mr-3"></i>
                            <p class="text-gray-700 dark:text-gray-300">
                                To get started, add your favorite RSS feeds using the "Add Feed" button above.
                            </p>
                        </div>
                        <p class="text-gray-600 dark:text-gray-400">
                            Explore the world of news and updates tailored just for you.
                        </p>
                    </div>
                `;
                container.appendChild(welcomeMessage);
            }
        }

        // Initialize the RSS Reader
        document.addEventListener('DOMContentLoaded', () => {
            window.rssReader = new RSSReader();
        });
    </script>
</body>
</html>