import { GoogleGenAI } from '@google/genai';
import { marked } from 'marked';

// --- Gemini AI Story Generator ---

const storyForm = document.getElementById('story-form') as HTMLFormElement;

if (storyForm) {
  const promptInput = document.getElementById(
    'story-prompt',
  ) as HTMLInputElement;
  const generateButton = document.getElementById(
    'generate-button',
  ) as HTMLButtonElement;
  const storyOutput = document.getElementById(
    'story-output',
  ) as HTMLDivElement;

  const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });

  storyForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const prompt = promptInput.value.trim();
    if (!prompt) return;

    generateButton.disabled = true;
    generateButton.textContent = 'Creando...';
    storyOutput.innerHTML = 'Generando tu cuento mágico, por favor espera...';

    try {
      const response = await ai.models.generateContent({
        model: 'gemini-2.5-flash',
        contents: `Escribe un cuento infantil corto (máximo 200 palabras) para niños de entre 5 y 8 años. El cuento debe ser positivo, con valores y fácil de entender. La temática es: ${prompt}`,
      });

      const text = response.text;
      storyOutput.innerHTML = marked(text) as string;
    } catch (error) {
      console.error(error);
      storyOutput.innerHTML =
        '<p style="color: red;">¡Ups! Algo salió mal. Por favor, inténtalo de nuevo.</p>';
    } finally {
      generateButton.disabled = false;
      generateButton.textContent = 'Crear Cuento';
    }
  });
}

// --- Course Registration Modal ---

const openModalButton = document.getElementById(
  'open-modal-button',
) as HTMLButtonElement;
const modal = document.getElementById('course-modal') as HTMLDivElement;

if (openModalButton && modal) {
  const closeModalButton = document.getElementById(
    'close-modal-button',
  ) as HTMLButtonElement;
  const modalForm = document.getElementById(
    'course-modal-form',
  ) as HTMLFormElement;
  const paymentLink =
    'https://escuelaycentrodeterapiaschile.kpages.online/reflexologia-emocional-evolutiva-4e7b1be0-de19-45cd-9bb3-df9c95eb2faf';

  const openModal = () => {
    modal.classList.add('is-visible');
  };

  const closeModal = () => {
    modal.classList.remove('is-visible');
  };

  openModalButton.addEventListener('click', openModal);
  closeModalButton.addEventListener('click', closeModal);
  modal.addEventListener('click', (event) => {
    if (event.target === modal) {
      closeModal();
    }
  });

  modalForm.addEventListener('submit', (event) => {
    event.preventDefault();
    // Here you could potentially save the form data
    // const name = (document.getElementById('modal-name') as HTMLInputElement).value;
    // const email = (document.getElementById('modal-email') as HTMLInputElement).value;
    // console.log('Inscripción de:', { name, email });

    window.open(paymentLink, '_blank');
    closeModal();
  });
}
