/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
*/
import { GoogleGenAI } from '@google/genai';

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

const form = document.getElementById('prompt-form') as HTMLFormElement;
const input = document.getElementById('prompt-input') as HTMLTextAreaElement;
const instructionsInput = document.getElementById('instructions-input') as HTMLTextAreaElement;
const languageSelect = document.getElementById('language-select') as HTMLSelectElement;
const responseContainer = document.getElementById('response-container');
const button = form.querySelector('button');
const copyButton = document.getElementById('copy-button') as HTMLButtonElement;

const copyIconSVG = `<svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20" fill="currentColor"><path d="M360-240q-33 0-56.5-23.5T280-320v-480q0-33 23.5-56.5T360-880h360q33 0 56.5 23.5T800-800v480q0 33-23.5 56.5T720-240H360Zm0-80h360v-480H360v480ZM200-80q-33 0-56.5-23.5T120-160v-560h80v560h560v80H200Zm160-720v480-480Z"/></svg>`;
const checkIconSVG = `<svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20" fill="currentColor"><path d="M382-240 154-468l57-57 171 171 367-367 57 57-424 424Z"/></svg>`;

// --- Instructions Management ---
interface SavedInstruction {
  title: string;
  text: string;
}

const manageInstructionsBtn = document.getElementById('manage-instructions-btn') as HTMLButtonElement;
const insertInstructionBtn = document.getElementById('insert-instruction-btn') as HTMLButtonElement;

const instructionsModal = document.getElementById('instructions-modal') as HTMLDivElement;
const addInstructionForm = document.getElementById('add-instruction-form') as HTMLFormElement;
const newInstructionTitleInput = document.getElementById('new-instruction-title-input') as HTMLInputElement;
const newInstructionInput = document.getElementById('new-instruction-input') as HTMLTextAreaElement;
const savedInstructionsList = document.getElementById('saved-instructions-list');

const insertInstructionsPopup = document.getElementById('insert-instructions-popup') as HTMLDivElement;

const INSTRUCTIONS_STORAGE_KEY = 'ai_translator_saved_instructions_v2';

function getSavedInstructions(): SavedInstruction[] {
  try {
    const stored = localStorage.getItem(INSTRUCTIONS_STORAGE_KEY);
    return stored ? JSON.parse(stored) : [];
  } catch (error) {
    console.error("Failed to parse saved instructions:", error);
    return [];
  }
}

function saveInstructions(instructions: SavedInstruction[]) {
  localStorage.setItem(INSTRUCTIONS_STORAGE_KEY, JSON.stringify(instructions));
  renderInstructions();
}

function renderInstructions() {
  const instructions = getSavedInstructions();

  // Clear existing lists
  if (savedInstructionsList) savedInstructionsList.innerHTML = '';
  if (insertInstructionsPopup) insertInstructionsPopup.innerHTML = '';

  // Update Insert button state
  insertInstructionBtn.disabled = instructions.length === 0;

  if (instructions.length === 0) {
    if (savedInstructionsList) {
        savedInstructionsList.innerHTML = '<p class="empty-state">No saved instructions yet.</p>';
    }
    if (insertInstructionsPopup) {
        insertInstructionsPopup.innerHTML = '<div class="popup-item empty-state">No instructions to insert.</div>';
    }
    return;
  }

  instructions.forEach((inst) => {
    // Populate manager list
    if (savedInstructionsList) {
        const item = document.createElement('div');
        item.className = 'saved-instruction-item';

        const contentDiv = document.createElement('div');
        contentDiv.className = 'saved-instruction-content';
        
        const title = document.createElement('h4');
        title.textContent = inst.title;
        
        const text = document.createElement('p');
        text.textContent = inst.text;
        
        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = 'Delete';
        deleteBtn.className = 'delete-instruction-btn';
        deleteBtn.onclick = () => {
            const currentInstructions = getSavedInstructions();
            const updatedInstructions = currentInstructions.filter(i => i.title !== inst.title);
            saveInstructions(updatedInstructions);
        };
        
        contentDiv.appendChild(title);
        contentDiv.appendChild(text);
        item.appendChild(contentDiv);
        item.appendChild(deleteBtn);
        savedInstructionsList.appendChild(item);
    }

    // Populate insert popup
    if (insertInstructionsPopup) {
        const popupItem = document.createElement('div');
        popupItem.className = 'popup-item';
        popupItem.textContent = inst.title;
        popupItem.title = inst.text; // Show full text on hover
        popupItem.onclick = () => {
            instructionsInput.value = inst.text;
            insertInstructionsPopup.hidden = true;
        };
        insertInstructionsPopup.appendChild(popupItem);
    }
  });
}

// Modal listeners
manageInstructionsBtn.addEventListener('click', () => {
  instructionsModal.hidden = false;
});

instructionsModal.addEventListener('click', (e) => {
  const target = e.target as HTMLElement;
  // Close if the backdrop or the close button (or its child) is clicked
  if (target === instructionsModal || target.closest('.modal-close')) {
    instructionsModal.hidden = true;
  }
});

// Add instruction form
addInstructionForm.addEventListener('submit', (e) => {
  e.preventDefault();
  const newTitle = newInstructionTitleInput.value.trim();
  const newText = newInstructionInput.value.trim();

  if (newTitle && newText) {
    const currentInstructions = getSavedInstructions();
    if (currentInstructions.some(i => i.title.toLowerCase() === newTitle.toLowerCase())) {
      alert('An instruction with this title already exists. Please use a unique title.');
      return;
    }
    const newInstruction: SavedInstruction = { title: newTitle, text: newText };
    saveInstructions([...currentInstructions, newInstruction]);
    newInstructionTitleInput.value = '';
    newInstructionInput.value = '';
    newInstructionTitleInput.focus();
  }
});

// Insert instruction popup
insertInstructionBtn.addEventListener('click', (e) => {
    e.stopPropagation(); // Prevent document click listener from firing immediately
    insertInstructionsPopup.hidden = !insertInstructionsPopup.hidden;
});

document.addEventListener('click', (e) => {
    if (!insertInstructionBtn.contains(e.target as Node) && !insertInstructionsPopup.contains(e.target as Node)) {
        insertInstructionsPopup.hidden = true;
    }
});
// --- End Instructions Management ---

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const sourceText = input.value;
  const instructions = instructionsInput.value;
  const targetLanguage = languageSelect.value;

  if (!sourceText || !targetLanguage || !responseContainer) {
    return;
  }
  
  const instructionsText = instructions ? `\n\nFollow these instructions carefully: ${instructions}` : '';

  const prompt = `You are a translator. Translate the following content to ${targetLanguage}. If the content is HTML, you must preserve all HTML tags and structure, only translating the text within them. Your response must only be the translated content, without any additional text, explanations, or markdown formatting like code fences (\`\`\`).${instructionsText}

Content to translate:
${sourceText}`;

  responseContainer.innerHTML = '<div class="loader"></div>';
  button.disabled = true;
  input.disabled = true;
  instructionsInput.disabled = true;
  languageSelect.disabled = true;
  copyButton.style.display = 'none';

  try {
    const response = await ai.models.generateContentStream({
      model: 'gemini-2.5-flash',
      contents: prompt,
    });

    // Clear loader and set up code block
    responseContainer.innerHTML = '';
    const pre = document.createElement('pre');
    const code = document.createElement('code');
    pre.appendChild(code);
    responseContainer.appendChild(pre);

    let fullResponse = '';

    for await (const chunk of response) {
      fullResponse += chunk.text;
      code.textContent = fullResponse;
    }
  } catch (error) {
    responseContainer.innerHTML = `<p class="error">Error: ${error.message}</p>`;
  } finally {
    button.disabled = false;
    input.disabled = false;
    instructionsInput.disabled = false;
    languageSelect.disabled = false;
    if (responseContainer.querySelector('code')?.textContent?.trim()) {
        copyButton.style.display = 'flex';
    }
  }
});

copyButton.addEventListener('click', () => {
    const codeElement = responseContainer.querySelector('code');
    if (codeElement?.textContent) {
        navigator.clipboard.writeText(codeElement.textContent).then(() => {
            copyButton.innerHTML = checkIconSVG;
            copyButton.title = 'Copied!';
            setTimeout(() => {
                copyButton.innerHTML = copyIconSVG;
                copyButton.title = 'Copy to clipboard';
            }, 2000);
        }).catch(err => {
            console.error('Failed to copy: ', err);
            copyButton.title = 'Copy failed!';
        });
    }
});

// Initial render of instructions on load
renderInstructions();