document.addEventListener('DOMContentLoaded', () => {
  const paletteButton = document.getElementById('color-palette-btn');
  const paletteModal = document.getElementById('color-palette-modal');
  const closeButton = document.getElementById('color-palette-close-btn');
  const paletteContainer = document.getElementById('palette-container');
  const paletteNewColor = document.getElementById('palette-new-color');
  const profileNameDisplay = document.getElementById('palette-current-profile-name');

  if (!paletteButton || !paletteModal || !paletteContainer) {
    return;
  }

  let currentProfileId = null;
  let currentPaletteId = null;
  let currentPalette = [];
  let currentProfileName = null;

  const renderPalette = () => {
    paletteContainer.innerHTML = '';
    if (!currentPalette.length) {
      const empty = document.createElement('p');
      empty.className = 'muted-text';
      empty.textContent = 'No colors in palette.';
      paletteContainer.appendChild(empty);
      return;
    }
    currentPalette.forEach((color, index) => {
      const row = document.createElement('div');
      row.className = 'profiles-row';
      row.dataset.color = color;
      row.style.cssText = 'display: flex; align-items: center; gap: 1rem;';
      // Ensure no text content
      row.textContent = '';

      const swatch = document.createElement('div');
      swatch.style.cssText = `
        width: 64px;
        height: 64px;
        border-radius: 8px;
        background-color: ${color};
        border: 2px solid #4a4a4a;
        cursor: pointer;
        flex-shrink: 0;
        box-shadow: 0 2px 4px rgba(0,0,0,0.3);
      `;
      swatch.title = color; // Show hex code on hover only
      swatch.setAttribute('aria-label', `Color ${color}`);

      const removeButton = document.createElement('button');
      removeButton.className = 'btn btn-danger btn-small';
      removeButton.textContent = 'Remove';
      removeButton.style.fontSize = '0.8rem'; // Restore font size for button
      removeButton.addEventListener('click', async (e) => {
        e.stopPropagation();
        const updated = currentPalette.filter((_, i) => i !== index);
        await savePalette(updated);
      });

      row.appendChild(swatch);
      row.appendChild(removeButton);
      paletteContainer.appendChild(row);
    });
  };

  const loadPalette = async () => {
    try {
      const currentResponse = await fetch('/profiles/current', {
        headers: { Accept: 'application/json' },
      });
      if (!currentResponse.ok) {
        throw new Error('Failed to load current profile');
      }
      const currentData = await currentResponse.json();
      currentProfileId = currentData.id || null;
      const profile = currentData.profile || null;
      currentProfileName = profile ? profile.name : null;
      if (profileNameDisplay) {
        profileNameDisplay.textContent = currentProfileName || currentProfileId || 'None';
      }

      if (!currentProfileId || !profile) {
        currentPalette = [];
        renderPalette();
        return;
      }

      // Prefer palette_id-based storage; fall back to legacy inline palette.
      currentPaletteId = profile.palette_id || profile.paletteId || null;
      if (currentPaletteId) {
        try {
          const palResponse = await fetch(`/palettes/${currentPaletteId}`, {
            headers: { Accept: 'application/json' },
          });
          if (palResponse.ok) {
            const palData = await palResponse.json();
            currentPalette = (palData.colors) || [];
          } else {
            currentPalette = [];
          }
        } catch (e) {
          console.error('Failed to load palette by id:', e);
          currentPalette = [];
        }
      } else {
        // Legacy: palette stored directly on profile
        currentPalette = profile.palette || profile.color_palette || [];
      }
      renderPalette();
    } catch (error) {
      console.error('Failed to load palette:', error);
      currentPalette = [];
      renderPalette();
    }
  };

  const savePalette = async (newPalette) => {
    if (!currentProfileId) {
      alert('No profile selected.');
      return;
    }
    try {
      // Ensure we have a palette ID for this profile.
      if (!currentPaletteId) {
        const createResponse = await fetch('/palettes', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ colors: newPalette }),
        });
        if (!createResponse.ok) {
          throw new Error('Failed to create palette');
        }
        const pal = await createResponse.json();
        currentPaletteId = pal.id || Object.keys(pal)[0];

        // Link the new palette to the current profile.
        const linkResponse = await fetch('/profiles/current', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            palette_id: currentPaletteId,
          }),
        });
        if (!linkResponse.ok) {
          throw new Error('Failed to link palette to profile');
        }
      } else {
        // Update existing palette colors
        const updateResponse = await fetch(`/palettes/${currentPaletteId}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ colors: newPalette }),
        });
        if (!updateResponse.ok) {
          throw new Error('Failed to save palette');
        }
      }

      currentPalette = newPalette;
      renderPalette();
    } catch (error) {
      console.error('Failed to save palette:', error);
      alert('Failed to save palette.');
    }
  };

  const openModal = () => {
    paletteModal.classList.add('active');
    loadPalette();
  };

  const closeModal = () => {
    paletteModal.classList.remove('active');
  };

  paletteButton.addEventListener('click', openModal);
  if (closeButton) {
    closeButton.addEventListener('click', closeModal);
  }
  if (paletteNewColor) {
    const addSelectedColor = async () => {
      const color = paletteNewColor.value;
      if (!color) {
        return;
      }
      if (currentPalette.includes(color)) {
        alert('Color already in palette.');
        return;
      }
      await savePalette([...currentPalette, color]);
    };
    // Add when the picker closes (user confirms selection).
    paletteNewColor.addEventListener('change', addSelectedColor);
  }
});
