const path = require("path");
const fs = require("fs");
const { createCanvas, registerFont, loadImage } = require("canvas");

// =======================
// Register Roboto-Bold
// =======================
registerFont(
  path.join(__dirname, "../assets/Roboto/static/Roboto-Bold.ttf"),
  { family: "Roboto" }
);

async function generateSubjectThumbnail(subject) {
  const { title, teacherName } = subject;

  const width = 1280;
  const height = 720;
  const canvas = createCanvas(width, height);
  const ctx = canvas.getContext("2d");

  // =======================
  // Gradient background
  // =======================
  const gradient = ctx.createLinearGradient(0, 0, width, height);
  gradient.addColorStop(0, "#4071a5");
  gradient.addColorStop(1, "#2a77c4");
  ctx.fillStyle = gradient;
  ctx.fillRect(0, 0, width, height);

  // =======================
  // Subtle geometric shapes
  // =======================
  ctx.globalAlpha = 0.08;
  ctx.fillStyle = "#ffffff";
  for (let i = 0; i < 6; i++) {
    const x = Math.random() * width;
    const y = Math.random() * height;
    const r = 60 + Math.random() * 120;
    ctx.beginPath();
    ctx.arc(x, y, r, 0, Math.PI * 2);
    ctx.fill();
  }
  ctx.globalAlpha = 1;

  // =======================
  // Subject Icon PNG
  // =======================
  const iconMap = {
    "math": path.join(__dirname, "../assets/emojis/books.png"),    // ∑ placeholder
    "science": path.join(__dirname, "../assets/emojis/books.png"), // 🔬
    "english": path.join(__dirname, "../assets/emojis/books.png"),  // ✍️
    "default": path.join(__dirname, "../assets/emojis/book.png")     // 📘 / 📚
  };

  let iconFile = iconMap["default"];
  const lower = title.toLowerCase();
  if (lower.includes("math")) iconFile = iconMap["math"];
  else if (lower.includes("science")) iconFile = iconMap["science"];
  else if (lower.includes("english")) iconFile = iconMap["english"];

  const iconImg = await loadImage(iconFile);
  const iconSize = 140;
  ctx.drawImage(iconImg, width - 220, 90, iconSize, iconSize);

  // =======================
  // Course label
  // =======================
  ctx.fillStyle = "rgba(0,0,0,0.6)";
  ctx.font = "bold 28px Roboto";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("COURSE", 80, 80);

  // =======================
  // Subject Title (center, 3D + glow)
  // =======================
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";

  let fontSize = 96;
  ctx.font = `bold ${fontSize}px Roboto`;
  let textWidth = ctx.measureText(title).width;
  while (textWidth > width - 200 && fontSize > 40) {
    fontSize -= 5;
    ctx.font = `bold ${fontSize}px Roboto`;
    textWidth = ctx.measureText(title).width;
  }

  // Glow behind text
  ctx.shadowColor = "rgba(113, 130, 135, 0.5)";
  ctx.shadowBlur = 25;
  ctx.fillStyle = "#ecf1ee";
  ctx.fillText(title, width / 2, height / 2);

  // 3D shadow effect
  ctx.shadowColor = "rgba(0,0,0,0.4)";
  ctx.shadowOffsetX = 2;
  ctx.shadowOffsetY = 2;
  ctx.shadowBlur = 4;
  ctx.fillText(title, width / 2, height / 2);

  // Reset shadow
  ctx.shadowColor = "transparent";
  ctx.shadowOffsetX = 0;
  ctx.shadowOffsetY = 0;
  ctx.shadowBlur = 0;

  // =======================
  // Extra emojis scattered as PNGs
  // =======================
  const emojiMap = {
    "🖍️": path.join(__dirname, "../assets/emojis/crayon.png"),
    "📚": path.join(__dirname, "../assets/emojis/books.png"),
    "🎓": path.join(__dirname, "../assets/emojis/graduation.png"),
    "🧪": path.join(__dirname, "../assets/emojis/testtube.png"),
    "📐": path.join(__dirname, "../assets/emojis/ruler.png"),
    "💻": path.join(__dirname, "../assets/emojis/laptop.png"),
    "🎨": path.join(__dirname, "../assets/emojis/palette.png")
  };

  const extraEmojis = ["🖍️", "📚", "🎓", "🧪", "📐", "💻", "🎨"];
  for (let i = 0; i < 15; i++) {
    const emoji = extraEmojis[Math.floor(Math.random() * extraEmojis.length)];
    const x = Math.random() * width;
    const y = Math.random() * height;
    const img = await loadImage(emojiMap[emoji]);
    const size = 60;
    ctx.globalAlpha = 0.15;
    ctx.drawImage(img, x, y, size, size);
  }
  ctx.globalAlpha = 1;

  // =======================
  // Glass panel (teacher)
  // =======================
  const panelWidth = 500;
  const panelHeight = 100;
  const panelX = width - panelWidth - 60;
  const panelY = height - panelHeight - 40;

  ctx.fillStyle = "rgba(255, 255, 255, 0.15)";
  ctx.fillRect(panelX, panelY, panelWidth, panelHeight);

  ctx.strokeStyle = "rgba(255,255,255,0.25)";
  ctx.lineWidth = 2;
  ctx.strokeRect(panelX, panelY, panelWidth, panelHeight);

  ctx.fillStyle = "#000000";
  ctx.font = "28px Roboto";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillText(`Teacher: ${teacherName}`, panelX + panelWidth / 2, panelY + panelHeight / 2);

  // =======================
  // Save file
  // =======================
  const dir = path.join(__dirname, "../uploads/subject-thumbnails");
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });

  const fileName = `subject_${Date.now()}.png`;
  const filePath = path.join(dir, fileName);
  fs.writeFileSync(filePath, canvas.toBuffer("image/png"));

  return `/uploads/subject-thumbnails/${fileName}`;
}

module.exports = generateSubjectThumbnail;
