{% extends "layout.html" %}

{% block title %}{{ this.title }}{% endblock %}

{% block bgstuff %}
background-color: black;
color:white;
{% endblock %}

{% block body %}
  {{ this.body }}

  <div id="wikipedia-data">
    <h2>Wikipedia Article</h2>
    <p>Loading...</p>
  </div>
  
  <!-- JavaScript code to fetch and display Wikipedia data -->
  <script>
    // Wikipedia API endpoint with a CORS proxy
    const wikipediaAPI = 'https://cors-anywhere.herokuapp.com/https://en.wikipedia.org/w/api.php';
    
    // Array of Wikipedia page titles
    const pageTitles = ['List_of_hackers', 'Cybersecurity', 'Open-source_software', 'History_of_Linux'];
    
    // Randomly select a page title from the array
    const pageTitle = pageTitles[Math.floor(Math.random() * pageTitles.length)];
    
    // Parameters for the API request
    const params = {
      action: 'query',
      format: 'json',
      titles: pageTitle,
      prop: 'extracts|pageimages',
      exintro: true, // Get the introductory section
      explaintext: true, // Get plain text
      piprop: 'original',
      pithumbsize: 400, // Size of the thumbnail image
    };
    
    // Construct the URL with query parameters
    const url = `${wikipediaAPI}?${new URLSearchParams(params)}`;
    
    // Fetch data from Wikipedia using the API
    fetch(url,{
      method:"GET",
      headers: {
        "Origin": "https://kernelpanic.lol"
      }
    })
      .then((response) => response.json())
      .then((data) => {
        // Extract data from the API response
        const pageId = Object.keys(data.query.pages)[0];
        const articleTitle = data.query.pages[pageId].title;
        const articleIntro = data.query.pages[pageId].extract;
        const articleImage = data.query.pages[pageId].original ? data.query.pages[pageId].original.source : '';
    
        // Display the results
        console.log('Article Title:', articleTitle);
        console.log('Article Intro:', articleIntro);
        console.log('Article Image:', articleImage);
    
        // Update your webpage with the retrieved data
        document.getElementById('article-title').textContent = articleTitle;
        document.getElementById('article-intro').textContent = articleIntro;
        document.getElementById('article-image').src = articleImage;
      })
      .catch((error) => {
        console.error('Error:', error);
      });
    </script>
{% endblock %}
