{% 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>Y ahora, unas cuantas palabras de Wikipedia</h2>
    <h3 id="article-title"></h3>
    
  </div>
  
  <script>
    const wikipediaAPI = 'https://en.wikipedia.org/w/api.php';
  
    const pageTitles = ['List_of_hackers', 'Cybersecurity', 'Open-source_software', 'History_of_Linux'];
  
    const pageTitle = pageTitles[Math.floor(Math.random() * pageTitles.length)];
  
    const params = {
      origin: '*',                 // Required for CORS from Wikipedia
      action: 'query',
      format: 'json',
      titles: pageTitle,
      prop: 'extracts|pageimages',
      exintro: true,
      explaintext: true,
      piprop: 'original',
      pithumbsize: 400,
      ulssetlang: 'es',
    };
  
    const url = `${wikipediaAPI}?${new URLSearchParams(params)}`;
  
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        const pageId = Object.keys(data.query.pages)[0];
        const page = data.query.pages[pageId];
  
        const articleTitle = page.title;
        const articleIntro = page.extract;
        const articleImage = page.original ? page.original.source : '';
  
        console.log('Article Title:', articleTitle);
        console.log('Article Intro:', articleIntro);
        console.log('Article Image:', articleImage);
  
        document.getElementById('article-title').textContent = articleTitle;
        document.getElementById('article-intro').textContent = articleIntro;
  
        if (articleImage) {
          document.getElementById('article-image').src = articleImage;
          document.getElementById('article-image').style.display = 'block';
        } else {
          document.getElementById('article-image').style.display = 'none';
        }
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  </script>
  
{% endblock %}
