/* =========================================================
   Champion's RPG - scripts.js (CLEAN + WORKING)
   Fixes:
   - Calendar day modal renders quest images (not raw URLs)
   - Tooltip + modal stability improvements
   - Proper escaping (correct for real JS, not HTML-escaped)
   ========================================================= */

// -------------------------
// Tooltip
// -------------------------
function showTooltip(event, item) {
  const tooltip = document.getElementById('itemTooltip');
  if (!tooltip) return;

  const rarityColors = {
    common: '#9e9e9e',
    uncommon: '#4caf50',
    rare: '#2196f3',
    epic: '#9c27b0',
    legendary: '#ff9800'
  };

  const titleEl = document.getElementById('tooltipTitle');
  const subtitleEl = document.getElementById('tooltipSubtitle');
  const statsEl = document.getElementById('tooltipStats');
  const descEl = document.getElementById('tooltipDesc');
  const imgEl = document.getElementById('tooltipImg');

  if (titleEl) {
    titleEl.textContent = item?.name || '';
    titleEl.style.color = rarityColors[item?.rarity] || '#fff';
  }
  if (subtitleEl) subtitleEl.textContent = item?.subtitle || '';
  if (statsEl) statsEl.innerHTML = item?.stat_effect ? `<div class="tooltip-stat">${escapeHtml(item.stat_effect)}</div>` : '';
  if (descEl) descEl.textContent = item?.description || '';

  if (imgEl) {
    if (item?.image_path) {
      imgEl.src = item.image_path;
      imgEl.style.display = 'block';
    } else {
      imgEl.style.display = 'none';
    }
  }

  tooltip.style.display = 'block';
  tooltip.style.left = (event.clientX + 12) + 'px';
  tooltip.style.top = (event.clientY + 12) + 'px';
}

function hideTooltip() {
  const tooltip = document.getElementById('itemTooltip');
  if (tooltip) tooltip.style.display = 'none';
}

// -------------------------
// Modal
// -------------------------
function showModal(title, contentHtml) {
  const modal = document.getElementById('modal');
  const titleEl = document.getElementById('modalTitle');
  const bodyEl = document.getElementById('modalBody');

  if (!modal || !titleEl || !bodyEl) return;

  titleEl.textContent = title || '';
  bodyEl.innerHTML = contentHtml || '';
  modal.style.display = 'flex';
}

function closeModal(event) {
  // Click outside modal-content closes modal
  if (!event || (event.target && event.target.id === 'modal')) {
    const modal = document.getElementById('modal');
    if (modal) modal.style.display = 'none';
  }
}

// -------------------------
// Image preview (forms)
// -------------------------
function previewImage(input, previewId) {
  const preview = document.getElementById(previewId);
  if (!preview) return;

  if (input.files && input.files[0]) {
    const reader = new FileReader();
    reader.onload = function (e) {
      preview.src = e.target.result;
      preview.style.display = 'block';
    };
    reader.readAsDataURL(input.files[0]);
  }
}

// -------------------------
// AJAX helper
// -------------------------
function ajaxRequest(url, method, data, callback) {
  const xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

  if (method === 'POST' && !(data instanceof FormData)) {
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  }

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        callback(xhr.responseText);
      } else {
        console.error('AJAX error', xhr.status, xhr.responseText);
        alert('Network/server error. Please try again.');
      }
    }
  };

  xhr.send(data);
}

// -------------------------
// Actions
// -------------------------
function completeHabit(habitId) {
  const formData = new FormData();
  formData.append('action', 'complete_habit');
  formData.append('habit_id', habitId);

  ajaxRequest('ajax.php', 'POST', formData, function (response) {
    let data;
    try {
      data = JSON.parse(response);
    } catch (e) {
      console.error('Invalid JSON', response);
      alert('Server returned an invalid response.');
      return;
    }

    if (!data.success) {
      alert('Error: ' + (data.message || 'Unknown error'));
      return;
    }

    // Partial consumption warnings (optional)
    if (Array.isArray(data.warnings) && data.warnings.length > 0) {
      const lines = data.warnings.map(w =>
        `• ${w.name} — used ${w.used}/${w.needed} (short by ${w.short})`
      );
      alert(
        "✅ Habit completed!\n\n" +
        "⚠️ You're short on:\n" +
        lines.join("\n") +
        "\n\n(Inventory never goes below 0.)"
      );
    }

    location.reload();
  });
}

function completeBounty(bountyId) {
  const formData = new FormData();
  formData.append('action', 'complete_bounty');
  formData.append('bounty_id', bountyId);

  ajaxRequest('ajax.php', 'POST', formData, function (response) {
    let data;
    try {
      data = JSON.parse(response);
    } catch (e) {
      console.error('Invalid JSON', response);
      alert('Server returned an invalid response.');
      return;
    }

    if (data.success) {
      location.reload();
    } else {
      alert('Error: ' + (data.message || 'Unknown error'));
    }
  });
}

function useItem(itemId) {
  ajaxRequest('ajax.php?action=get_item&item_id=' + encodeURIComponent(itemId), 'GET', null, function (response) {
    let payload;
    try {
      payload = JSON.parse(response);
    } catch (e) {
      console.error('Invalid JSON', response);
      alert('Server returned an invalid response.');
      return;
    }

    if (!payload.success) {
      alert('Error: ' + (payload.message || 'Item not found'));
      return;
    }

    const item = payload.data;

    const imgHtml = item.image_path
      ? `<img src="${escapeAttr(item.image_path)}" alt="" style="width:100%;max-height:180px;object-fit:cover;border-radius:8px;border:1px solid rgba(255,215,0,0.25);margin-bottom:10px;">`
      : '';

    const statHtml = item.stat_effect
      ? `<div style="color:#4caf50;font-weight:800;margin:8px 0;">${escapeHtml(item.stat_effect)}</div>`
      : '';

    const content = `
      ${imgHtml}
      ${item.subtitle ? `<div style="color:#888;font-style:italic;margin-bottom:10px;">${escapeHtml(item.subtitle)}</div>` : ''}
      ${statHtml}
      ${item.description ? `<div style="color:#ccc;line-height:1.4;">${escapeHtml(item.description)}</div>` : ''}
      <div style="margin-top:12px;color:#fff;font-weight:800;">Quantity: ${Number(item.quantity || 0)}</div>
    `;

    showModal(item.name || 'Item', content);
  });
}

/**
 * Calendar day details modal
 * - Renders images as <img> thumbnails instead of printing the URL
 */
function showDayDetails(year, month, day) {
  const date = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;

  ajaxRequest('ajax.php?action=get_day_details&date=' + encodeURIComponent(date), 'GET', null, function (response) {
    let payload;
    try {
      payload = JSON.parse(response);
    } catch (e) {
      console.error('Invalid JSON', response);
      alert('Server returned an invalid response.');
      return;
    }

    if (!payload.success) {
      alert('Error: ' + (payload.message || 'Could not load day details'));
      return;
    }

    const champ = payload.champion || null;
    const completions = Array.isArray(payload.completions) ? payload.completions : [];

    let content = `
      <div style="margin-bottom:10px;">
        <div style="color:#ffd700;font-weight:900;font-size:1.1rem;">
          ${champ && champ.name ? escapeHtml(champ.name) + "'s Day" : "Quest Log"}
        </div>
        <div style="color:#888;">${escapeHtml(date)}</div>
      </div>
    `;

    if (completions.length === 0) {
      content += `<div style="color:#ccc;">No quests completed this day.</div>`;
    } else {
      content += `<div style="color:#ffd700;font-weight:900;margin:10px 0 8px;">Completed Quests:</div>`;
      content += `<div style="display:flex;flex-direction:column;gap:10px;">`;

      completions.forEach(c => {
        const name = escapeHtml(c.name || '');
        const img = c.image_path
          ? `<img src="${escapeAttr(c.image_path)}" alt="" style="width:42px;height:42px;object-fit:cover;border-radius:8px;border:1px solid rgba(255,215,0,0.25);flex:0 0 auto;">`
          : `<div style="width:42px;height:42px;border-radius:8px;background:#111;border:1px solid rgba(255,215,0,0.25);display:flex;align-items:center;justify-content:center;color:#ffd700;font-weight:900;">✓</div>`;

        content += `
          <div style="display:flex;align-items:center;gap:10px;background:rgba(255,255,255,0.05);padding:10px;border-radius:10px;border:1px solid #333;">
            ${img}
            <div style="color:#fff;font-weight:800;">✓ ${name}</div>
          </div>
        `;
      });

      content += `</div>`;
    }

    showModal('Quest Log', content);
  });
}

// -------------------------
// Utilities
// -------------------------
function escapeHtml(str) {
  return String(str).replace(/[&<>"']/g, function (m) {
    return ({
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#39;'
    })[m];
  });
}

function escapeAttr(str) {
  // Good enough for URLs in attributes
  return escapeHtml(str).replace(/`/g, '');
}