const apiKey = "f6e674f3eeacb47f6673f57c1c422d17";
const mediaTypeSel = document.getElementById('mediaType');
const queryInput = document.getElementById('query');
const btnSearch = document.getElementById('btnSearch');
const resultsList = document.getElementById('results');
const resolutionSel = document.getElementById('resolution');
const bgUpload = document.getElementById('bgUpload');
const logoUpload = document.getElementById('logoUpload');
const btnGenerate = document.getElementById('btnGenerate');
const previewCanvas = document.getElementById('previewCanvas');
const btnDownload = document.getElementById('btnDownload');
const customTitle = document.getElementById('customTitle');
const showTitle = document.getElementById('showCustomTitle');
const pCtx = previewCanvas.getContext('2d');
let selectedItem = null;

const dispositivosURL = "img/dispo12.png";

btnSearch.onclick = async () => {
  const type = mediaTypeSel.value;
  const q = encodeURIComponent(queryInput.value.trim());
  if (!apiKey || !q) return alert('API key e busca obrigatórios');

  const res = await fetch(`https://api.themoviedb.org/3/search/${type}?api_key=${apiKey}&language=pt-BR&query=${q}`);
  const data = await res.json();
  resultsList.innerHTML = '';

  const titulosUnicos = new Set();

  data.results.forEach(item => {
    const nome = (item.title || item.name || "").toLowerCase();
    const ano = (item.release_date || item.first_air_date || "").slice(0, 4);

    // IGNORA duplicados e filmes sem poster
    if (titulosUnicos.has(nome) || !item.poster_path) return;
    titulosUnicos.add(nome);

    const li = document.createElement('li');
    li.className = 'list-group-item d-flex flex-column align-items-center p-2';
    li.style.background = "#1e1e1e";
    li.style.borderRadius = "8px";
    li.style.cursor = "pointer";
    li.style.width = "140px";
    li.style.flex = "0 0 auto";

    const img = document.createElement('img');
    img.src = `https://image.tmdb.org/t/p/w200${item.poster_path}`;
    img.alt = 'Poster';
    img.style.width = "100%";
    img.style.height = "190px";
    img.style.objectFit = "cover";
    img.style.borderRadius = "6px";

    const span = document.createElement('span');
    span.textContent = `${item.title || item.name}`;
    span.style.color = "#fff";
    span.style.fontSize = "12px";
    span.style.marginTop = "6px";
    span.style.textAlign = "center";

    li.onclick = () => {
      selectedItem = item;
      [...resultsList.children].forEach(c => c.classList.remove('active'));
      li.classList.add('active');
    };

    li.appendChild(img);
    li.appendChild(span);
    resultsList.appendChild(li);
  });
};


// (continua o restante do código normalmente...)

btnGenerate.onclick = async () => {
  if (!selectedItem) return alert("Selecione um item primeiro.");

  const [w, h] = resolutionSel.value.split('x').map(Number);
  previewCanvas.width = w;
  previewCanvas.height = h;

  const details = await fetch(`https://api.themoviedb.org/3/${mediaTypeSel.value}/${selectedItem.id}?api_key=${apiKey}&language=pt-BR`)
    .then(r => r.json());

  const bgURL = bgUpload.files[0]
    ? URL.createObjectURL(bgUpload.files[0])
    : `https://image.tmdb.org/t/p/original${details.backdrop_path || details.poster_path}`;
  const posterURL = `https://image.tmdb.org/t/p/w500${details.poster_path}`;

  function loadImages(urls, callback) {
    let loaded = 0;
    const imgs = [];
    urls.forEach((url, i) => {
      imgs[i] = new Image();
      imgs[i].crossOrigin = "anonymous";
      imgs[i].onload = () => {
        loaded++;
        if (loaded === urls.length) callback(imgs);
      };
      imgs[i].src = url;
    });
  }

  const includeDevices = document.getElementById("showDevices")?.checked;
const urlsToLoad = includeDevices ? [bgURL, posterURL, dispositivosURL] : [bgURL, posterURL];

loadImages(urlsToLoad, (imgs) => {
  const bg = imgs[0];
  const poster = imgs[1];
  const dispositivos = includeDevices ? imgs[2] : null;

    pCtx.clearRect(0, 0, w, h);
    pCtx.drawImage(bg, 0, 0, w, h);
    pCtx.fillStyle = "rgba(0,0,0,0.4)";
    pCtx.fillRect(0, 0, w, h);

    const boxW = Math.round(w * 0.80);
    const boxH = Math.round(h * 0.40);
    const boxX = Math.round((w - boxW) / 2);
    const boxY = Math.round((h - boxH) / 2);

    const posterH = boxH * 0.88;
    const posterW = poster.width * (posterH / poster.height);
    const posterX = boxX + Math.round(boxH * 0.04);
    const posterY = boxY + Math.round((boxH - posterH) / 2);

    pCtx.fillStyle = "rgba(0,0,0,0.82)";
    pCtx.fillRect(boxX, boxY, boxW, boxH);
    pCtx.drawImage(poster, posterX, posterY, posterW, posterH);

    const textPadX = Math.round(boxH * 0.06);
    const textPadY = Math.round(boxH * 0.11);
    const textX = posterX + posterW + textPadX;
    const textY = boxY + textPadY;
    const textW = boxW - (posterW + textPadX * 2 + (posterX - boxX));
    const textH = boxH - textPadY * 2;

    // Título ajustável
    pCtx.fillStyle = "#fff";
    let movieTitle = `${details.title || details.name} (${(details.release_date || details.first_air_date || "").slice(0, 4)})`;
    let fontSizeTitle = Math.round(w * 0.019);
    pCtx.font = `bold ${fontSizeTitle}px sans-serif`;
    while (pCtx.measureText(movieTitle).width > textW && fontSizeTitle > 10) {
      fontSizeTitle -= 1;
      pCtx.font = `bold ${fontSizeTitle}px sans-serif`;
    }
    pCtx.fillText(movieTitle, textX, textY);

    // Duração
    pCtx.font = `normal ${Math.round(w * 0.013)}px sans-serif`;
    let runtime = details.runtime || details.episode_run_time?.[0] || "-";
    pCtx.fillText(`Duração: ${runtime} min`, textX, textY + 26);

    // Sinopse
    pCtx.font = `normal ${Math.round(w * 0.018)}px sans-serif`;
    pCtx.textBaseline = "top";
    const overview = details.overview || "Sinopse não disponível.";
    const maxLineWidth = textW;
    const lineHeight = Math.round(h * 0.035);
    const paddingTop = 55;
    let y = textY + paddingTop;
    const reservedHeight = Math.round(lineHeight * 2);
    const availableTextHeight = textH - paddingTop - reservedHeight;
    const maxLines = Math.floor(availableTextHeight / lineHeight);

    let words = overview.split(" ");
    let lines = [];
    let currentLine = "";

    for (let i = 0; i < words.length; i++) {
      let testLine = currentLine + words[i] + " ";
      if (pCtx.measureText(testLine).width > maxLineWidth) {
        lines.push(currentLine.trim());
        currentLine = words[i] + " ";
        if (lines.length >= maxLines) break;
      } else {
        currentLine = testLine;
      }
    }
    if (lines.length < maxLines && currentLine) {
      lines.push(currentLine.trim());
    }

    for (let i = 0; i < lines.length; i++) {
      pCtx.fillText(lines[i], textX, y);
      y += lineHeight;
    }

    // Gênero
    pCtx.font = `italic ${Math.round(w * 0.016)}px sans-serif`;
    pCtx.fillStyle = "#cccccc";
    const genres = details.genres.slice(0, 2).map(g => g.name).join(", ");
    pCtx.fillText(`Gênero: ${genres}`, textX, y + 10);

    if (showTitle.checked && customTitle.value.trim()) {
      pCtx.save();
      const fontSize = Math.round(w * 0.037);
      const text = customTitle.value.toUpperCase();
      pCtx.font = `bold ${fontSize}px sans-serif`;
      pCtx.textAlign = "center";
      pCtx.fillStyle = document.getElementById("titleColor").value;
      pCtx.shadowColor = "rgba(0,0,0,0.95)";
      pCtx.shadowBlur = 10;
      const topMargin = Math.round(h * 0.05);
      let centerTextY = topMargin + fontSize;
      const metrics = pCtx.measureText(text);
      if (metrics.actualBoundingBoxAscent) {
        centerTextY = topMargin + fontSize - (metrics.actualBoundingBoxAscent / 2);
      }
      pCtx.fillText(text, w / 2, centerTextY);
      pCtx.shadowBlur = 0;
      pCtx.restore();
    }

    if (logoUpload.files[0]) {
      const imgLogo = new Image();
      imgLogo.onload = () => {
        const logoW = w * 0.13;
        const logoH = logoW * imgLogo.height / imgLogo.width;
        pCtx.drawImage(imgLogo, 45, 45, logoW, logoH);
      };
      imgLogo.src = URL.createObjectURL(logoUpload.files[0]);
    }

   if (includeDevices && dispositivos instanceof Image) {
  const dispW = w * 0.30;
  const dispH = dispW * dispositivos.height / dispositivos.width;
  const dispX = (w - dispW) / 2;
  const dispY = h - dispH - 35;
  pCtx.drawImage(dispositivos, dispX, dispY, dispW, dispH);
}

    btnDownload.style.display = "block";
  });
};

btnDownload.onclick = () => {
  html2canvas(previewCanvas, { backgroundColor: null, scale: 1 }).then(c => {
    c.toBlob(b => {
      const a = document.createElement('a');
      a.download = 'banner.png';
      a.href = URL.createObjectURL(b);
      a.click();
    });
  });
};
// Salvar Preferências
document.getElementById("btnSalvarPrefs").onclick = () => {
  const prefs = {
    customTitle: customTitle.value,
    titleColor: document.getElementById("titleColor").value,
    showTitle: showTitle.checked
    // Você pode adicionar mais preferências aqui
  };
  localStorage.setItem("bannerPrefs", JSON.stringify(prefs));
  alert("Preferências salvas com sucesso!");
};

// Carregar Preferências ao abrir
window.addEventListener("DOMContentLoaded", () => {
  const saved = localStorage.getItem("bannerPrefs");
  if (saved) {
    const prefs = JSON.parse(saved);
    customTitle.value = prefs.customTitle || "";
    document.getElementById("titleColor").value = prefs.titleColor || "#FFD700";
    showTitle.checked = prefs.showTitle || false;
  }
});

console.log("✅ banner.js carregado e funcional");