/* ===== Certificate render — landscape A4-ish, CSS-drawn ===== */
/* Base canvas 1000 x 707 (A4 landscape ratio), scaled by `scale` prop. */

const CERT_W = 1000, CERT_H = 707;

/* ฟอนต์ชื่อที่เลือกได้ (ต้องโหลดใน index.html ด้วย) */
const NAME_FONTS = [
  { id: "pridi", label: "Pridi (ทางการ)", css: '"Pridi", serif' },
  { id: "sarabun", label: "Sarabun (อ่านง่าย)", css: '"Sarabun", sans-serif' },
  { id: "kanit", label: "Kanit (โมเดิร์น)", css: '"Kanit", sans-serif' },
  { id: "mitr", label: "Mitr (หนา)", css: '"Mitr", sans-serif' },
  { id: "prompt", label: "Prompt (เรียบ)", css: '"Prompt", sans-serif' },
  { id: "charmonman", label: "Charmonman (ลายมือ)", css: '"Charmonman", cursive' },
];
const NAME_FONT_CSS = Object.fromEntries(NAME_FONTS.map(f => [f.id, f.css]));

/* ค่าเริ่มต้น (hex) ของแต่ละสไตล์สำเร็จรูป — ใช้ตั้งต้นในตัวปรับแต่ง */
const STYLE_PRESETS = {
  "classic-gold": { accent: "#b8860b", bg: "#fffdf5", border: "double" },
  "modern-blue": { accent: "#3b4fb0", bg: "#fbfcff", border: "modern" },
  "ornate-cream": { accent: "#8c6d2b", bg: "#fdfbf2", border: "ornate" },
};
const BORDER_OPTIONS = [
  { id: "double", label: "กรอบคู่" },
  { id: "modern", label: "แถบข้าง" },
  { id: "ornate", label: "วิจิตร" },
  { id: "plain", label: "เส้นเดียว" },
];

const TEMPLATES = {
  "classic-gold":  { bg: "oklch(0.995 0.006 90)",  ink: "oklch(0.30 0.04 70)",  accent: "var(--c-gold-deep)", border: "double", seal: "gold" },
  "modern-blue":   { bg: "oklch(0.995 0.004 264)", ink: "oklch(0.30 0.04 264)", accent: "var(--c-primary)",   border: "modern", seal: "blue" },
  "ornate-cream":  { bg: "oklch(0.99 0.012 85)",   ink: "oklch(0.32 0.05 60)",  accent: "oklch(0.55 0.10 50)", border: "ornate", seal: "gold" },
};

const Seal = ({ tone = "gold", size = 96 }) => {
  const col = tone === "blue" ? "var(--c-primary)" : "var(--c-gold-deep)";
  const col2 = tone === "blue" ? "var(--c-primary-soft)" : "var(--c-gold-soft)";
  return (
    <div style={{ width: size, height: size, position: "relative", display: "grid", placeItems: "center" }}>
      <svg width={size} height={size} viewBox="0 0 100 100" style={{ position: "absolute" }}>
        <g fill={col}>
          {Array.from({ length: 24 }).map((_, i) => (
            <rect key={i} x="48.5" y="2" width="3" height="11"
              transform={`rotate(${i * 15} 50 50)`} opacity={i % 2 ? 0.55 : 1} rx="1" />
          ))}
        </g>
        <circle cx="50" cy="50" r="34" fill={col} />
        <circle cx="50" cy="50" r="29" fill="none" stroke={col2} strokeWidth="1.4" />
      </svg>
      <div style={{ position: "relative", textAlign: "center", color: "#fff", lineHeight: 1.15 }}>
        <div style={{ fontFamily: "var(--font-display)", fontSize: size * 0.2, fontWeight: 600 }}>บด.2</div>
        <div style={{ fontSize: size * 0.085, letterSpacing: 0.5, opacity: 0.9 }}>CERTIFIED</div>
      </div>
    </div>
  );
};

/* Border frame per template */
function Frame({ t, children }) {
  if (t.border === "modern") {
    return (
      <div style={{ position: "absolute", inset: 0, padding: 22 }}>
        <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 14, background: t.accent }} />
        <div style={{ position: "absolute", inset: 22, border: `1.5px solid ${t.accent}`, borderRadius: 2, opacity: 0.4 }} />
        {children}
      </div>
    );
  }
  if (t.border === "plain") {
    return (
      <div style={{ position: "absolute", inset: 0 }}>
        <div style={{ position: "absolute", inset: 22, border: `2px solid ${t.accent}`, borderRadius: 2 }} />
        {children}
      </div>
    );
  }
  // classic / ornate: double gold border with corner flourishes
  return (
    <div style={{ position: "absolute", inset: 0 }}>
      <div style={{ position: "absolute", inset: 20, border: `3px solid ${t.accent}` }} />
      <div style={{ position: "absolute", inset: 27, border: `1px solid ${t.accent}`, opacity: 0.6 }} />
      {[["top","left"],["top","right"],["bottom","left"],["bottom","right"]].map(([v,h],i)=>(
        <div key={i} style={{ position: "absolute", [v]: 14, [h]: 14, width: 30, height: 30,
          [`border${v[0].toUpperCase()+v.slice(1)}`]: `4px solid ${t.accent}`,
          [`border${h[0].toUpperCase()+h.slice(1)}`]: `4px solid ${t.accent}` }} />
      ))}
      {children}
    </div>
  );
}

/* รายละเอียดใต้ชื่อ (มาจาก CSV ต่อคน, ถ้าไม่มีใช้ข้อมูลกิจกรรม) */
function detailLines(rec) {
  const L = [];
  if (rec?.school) L.push({ t: rec.school, s: 23 });
  if (rec?.role) L.push({ t: rec.role, s: 23, accent: true, bold: true });
  if (rec?.activity) L.push({ t: rec.activity, s: 22 });
  return L;
}

/* บล็อกเนื้อหา: ชื่อ + รายละเอียด (วางตามตำแหน่งที่ลากได้) */
function ContentBlock({ pos, name, nFontCss, nSize, lines, ink, lineAccent, highlight, highlightColor }) {
  return (
    <div style={{ position: "absolute", left: `${pos.x}%`, top: `${pos.y}%`, transform: "translate(-50%,0)",
      width: "86%", textAlign: "center",
      ...(highlight ? { border: `2px dashed ${highlightColor}`, background: "oklch(0.74 0.11 78 / 0.10)", padding: "8px 14px", borderRadius: 6 } : {}) }}>
      <div style={{ fontFamily: nFontCss, fontSize: nSize, fontWeight: 600, color: ink, lineHeight: 1.12 }}>{name}</div>
      {lines.map((l, i) => (
        <div key={i} style={{ fontFamily: "var(--font-ui)", fontSize: l.s, fontWeight: l.bold ? 600 : 400,
          color: l.accent ? lineAccent : ink, marginTop: i === 0 ? 11 : 5, lineHeight: 1.3 }}>{l.t}</div>
      ))}
    </div>
  );
}

/* The full certificate. nameOverlay lets admin position-setter draw a box. */
function Certificate({ event, rec, template, scale = 1, namePos, noPos, highlightName = false, highlightNo = false, imageUrl, nameFont, nameSize, accent, bg, border }) {
  const baseT = TEMPLATES[template || event?.template || "classic-gold"];
  const t = {
    ...baseT,
    accent: accent || event?.accent || baseT.accent,
    bg: bg || event?.bg || baseT.bg,
    border: border || event?.border || baseT.border,
  };
  const name = rec?.name || "ชื่อ–นามสกุล ผู้รับเกียรติบัตร";
  const role = rec?.role || "เข้าร่วมกิจกรรม";
  const pos = namePos || event?.namePos || { x: 50, y: 46 };
  const nPos = noPos || event?.noPos || { x: 14, y: 8 };
  const img = imageUrl || event?.templateUrl;
  const nFontCss = NAME_FONT_CSS[nameFont || event?.nameFont] || NAME_FONT_CSS.pridi;
  const nSize = nameSize || event?.nameSize || 52;

  // ---------- โหมดรูปภาพ: ใช้ไฟล์เทมเพลตที่อัปโหลด เป็นพื้นหลัง + พิมพ์เนื้อหาทับ ----------
  if (img) {
    return (
      <div style={{ width: CERT_W * scale, height: CERT_H * scale, flex: "none" }}>
        <div style={{ width: CERT_W, height: CERT_H, transform: `scale(${scale})`, transformOrigin: "top left",
          position: "relative", overflow: "hidden", background: "#fff", fontFamily: "var(--font-display)" }}>
          <img src={img} alt="เทมเพลต" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "fill" }} />
          <ContentBlock pos={pos} name={name} nFontCss={nFontCss} nSize={nSize} lines={detailLines(rec)}
            ink="#1a1a1a" lineAccent="#1a1a1a" highlight={highlightName} highlightColor="var(--c-gold-deep)" />
          {/* เลขที่ */}
          <div style={{ position: "absolute", left: `${nPos.x}%`, top: `${nPos.y}%`, transform: "translate(-50%,-50%)",
            fontFamily: "var(--font-ui)", fontSize: 16, color: "#1a1a1a", whiteSpace: "nowrap",
            ...(highlightNo ? { border: `2px dashed var(--c-gold-deep)`, background: "oklch(0.74 0.11 78 / 0.12)", padding: "3px 10px", borderRadius: 4 } : {}) }}>
            เลขที่{rec?.no ? ` ${rec.no}` : ""}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ width: CERT_W * scale, height: CERT_H * scale, flex: "none" }}>
      <div style={{ width: CERT_W, height: CERT_H, transform: `scale(${scale})`, transformOrigin: "top left",
        background: t.bg, position: "relative", color: t.ink, overflow: "hidden",
        boxShadow: "0 1px 0 oklch(0.5 0 0 / .04)", fontFamily: "var(--font-display)" }}>

        {/* subtle watermark */}
        <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", opacity: 0.04 }}>
          <svg width="420" height="420" viewBox="0 0 24 24" fill="none" stroke={t.accent} strokeWidth="0.5">
            <path d="M12 3 2.5 7.5 12 12l9.5-4.5L12 3Z"/>
            <path d="M6.5 9.8V15c0 1.3 2.5 2.8 5.5 2.8s5.5-1.5 5.5-2.8V9.8"/>
          </svg>
        </div>

        <Frame t={t}>
          <div style={{ position: "absolute", inset: 0, padding: "58px 80px",
            display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center" }}>

            {/* header */}
            <div style={{ fontFamily: "var(--font-ui)", fontSize: 19, letterSpacing: 1, color: t.accent, fontWeight: 600 }}>
              กลุ่มโรงเรียนบ้านด่าน 2
            </div>
            <div style={{ fontFamily: "var(--font-ui)", fontSize: 13.5, color: t.ink, opacity: 0.7, marginTop: 2 }}>
              สำนักงานเขตพื้นที่การศึกษาประถมศึกษาบุรีรัมย์ เขต 1
            </div>

            {/* title */}
            <div style={{ marginTop: 18, fontSize: 62, fontWeight: 600, letterSpacing: 2, color: t.accent, lineHeight: 1 }}>
              เกียรติบัตร
            </div>
            <div style={{ fontFamily: "var(--font-ui)", fontSize: 15, color: t.ink, opacity: 0.7, marginTop: 6 }}>
              ฉบับนี้มอบให้เพื่อแสดงว่า
            </div>
          </div>
        </Frame>

        {/* เนื้อหา: ชื่อ + รายละเอียด (วางตามตำแหน่งที่ลากได้) */}
        <ContentBlock pos={pos} name={name} nFontCss={nFontCss} nSize={nSize} lines={detailLines(rec)}
          ink={t.ink} lineAccent={t.accent} highlight={highlightName} highlightColor={t.accent} />

        {/* signatures + seal */}
        <div style={{ position: "absolute", left: 0, right: 0, bottom: 56, padding: "0 100px",
          display: "flex", justifyContent: "space-between", alignItems: "flex-end", fontFamily: "var(--font-ui)" }}>
          <div style={{ textAlign: "center", width: 190 }}>
            <div style={{ borderBottom: `1px solid ${t.ink}`, opacity: 0.5, marginBottom: 7 }} />
            <div style={{ fontSize: 14, fontWeight: 600, color: t.ink }}>ประธานกลุ่มโรงเรียน</div>
            <div style={{ fontSize: 12.5, color: t.ink, opacity: 0.6 }}>บ้านด่าน 2</div>
          </div>
          <div style={{ marginBottom: -6 }}><Seal tone={t.seal} size={92} /></div>
          <div style={{ textAlign: "center", width: 190 }}>
            <div style={{ borderBottom: `1px solid ${t.ink}`, opacity: 0.5, marginBottom: 7 }} />
            <div style={{ fontSize: 14, fontWeight: 600, color: t.ink }}>ผู้อำนวยการ</div>
            <div style={{ fontSize: 12.5, color: t.ink, opacity: 0.6 }}>กลุ่มโรงเรียนบ้านด่าน 2</div>
          </div>
        </div>

        {/* cert no — positioned (admin can drag) */}
        <div style={{ position: "absolute", left: `${nPos.x}%`, top: `${nPos.y}%`, transform: "translate(-50%,-50%)",
          fontFamily: "var(--font-ui)", fontSize: 16, color: t.ink, whiteSpace: "nowrap",
          ...(highlightNo
            ? { border: `2px dashed ${t.accent}`, background: "oklch(0.74 0.11 78 / 0.12)", padding: "3px 10px", borderRadius: 4 }
            : { opacity: 0.6 }) }}>
          เลขที่{rec?.no ? ` ${rec.no}` : ""}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Certificate, Seal, TEMPLATES, CERT_W, CERT_H, NAME_FONTS, NAME_FONT_CSS, STYLE_PRESETS, BORDER_OPTIONS });
