<%
const defaults = { x: 50, y: 70, width: 80, height: 14, fontSize: 36, color: '#ffffff', fontWeight: 700, textAlign: 'center', fontFamily: 'serif' };
let saved = item.namaLabelPosition;
if (typeof saved === 'string') { try { saved = JSON.parse(saved); } catch { saved = null; } }
const pos = Object.assign({}, defaults, saved || {});
%>
<div class="flex justify-between items-center mb-8">
  <h1>Setting undangan.</h1>
  <div class="flex gap-2">
    <a href="/undangan/preview/angkatan/<%= item.id %>" target="_blank" class="btn-secondary btn-sm">Preview</a>
    <a href="/angkatan" class="btn-secondary btn-sm">Kembali</a>
  </div>
</div>

<p class="mono-label mb-6">Angkatan <%= item.nomor %></p>

<form id="settingForm" action="/angkatan/<%= item.id %>/setting" method="POST" enctype="multipart/form-data" class="space-y-6">

  <div class="card">
    <h4 class="mb-1">Background & box nama.</h4>
    <p class="text-sm text-body mb-4">
      Drag tengah box untuk pindah posisi, drag bola kuning untuk ubah ukuran.
    </p>

    <div class="flex flex-col md:flex-row gap-6">
      <div class="flex-1">
        <div id="canvas" class="relative mx-auto bg-canvas-soft-2 rounded-lg overflow-hidden select-none touch-none" style="max-width:360px; aspect-ratio: 9/16; box-shadow: inset 0 0 0 1px rgba(0,0,0,0.08);">
          <img id="bgImage" src="<%= item.backgroundUrl || '' %>" class="absolute inset-0 w-full h-full object-cover <%= item.backgroundUrl ? '' : 'hidden' %>" />
          <div id="bgFallback" class="absolute inset-0 bg-ink <%= item.backgroundUrl ? 'hidden' : '' %>"></div>

          <div id="nameBox" class="absolute border-2 border-dashed border-warning cursor-move flex items-center justify-center overflow-hidden">
            <div id="nameText" class="w-full text-center leading-tight px-1" style="white-space:nowrap; min-width:0;">Ananda Wali Santri NFBS Bogor</div>
            <div id="resizeHandle" class="absolute -bottom-1 -right-1 w-4 h-4 bg-warning border-2 border-white rounded-full cursor-nwse-resize"></div>
          </div>
        </div>

        <p class="text-sm text-body text-center mt-3">
          Font aktual: <span id="actualFs" class="font-mono">—</span>px
          <span class="text-mute">(maks <span id="maxFsLabel" class="font-mono">—</span>px)</span>
        </p>

        <div class="mt-4">
          <label class="label">Background image</label>
          <input type="file" name="background" accept="image/*" id="bgFile" class="input py-2" />
          <p class="text-xs text-mute mt-1">Maks 10MB. Dikompres ke WebP.</p>
        </div>
      </div>

      <div class="flex-1 space-y-3">
        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="label">Posisi X (%)</label>
            <input type="number" min="0" max="100" step="0.01" id="posX" class="input" value="<%= Number(pos.x).toFixed(2) %>" />
          </div>
          <div>
            <label class="label">Posisi Y (%)</label>
            <input type="number" min="0" max="100" step="0.01" id="posY" class="input" value="<%= Number(pos.y).toFixed(2) %>" />
          </div>
          <div>
            <label class="label">Lebar Box (%)</label>
            <input type="number" min="10" max="100" step="0.01" id="boxW" class="input" value="<%= Number(pos.width).toFixed(2) %>" />
          </div>
          <div>
            <label class="label">Tinggi Box (%)</label>
            <input type="number" min="3" max="60" step="0.01" id="boxH" class="input" value="<%= Number(pos.height).toFixed(2) %>" />
          </div>
          <div>
            <label class="label">Ukuran Font Maks (px)</label>
            <input type="number" min="8" max="200" id="fontSize" class="input" value="<%= pos.fontSize %>" />
          </div>
          <div>
            <label class="label">Bobot Font</label>
            <select id="fontWeight" class="input">
              <option value="400" <%= pos.fontWeight == 400 ? 'selected' : '' %>>Normal</option>
              <option value="600" <%= pos.fontWeight == 600 ? 'selected' : '' %>>Semibold</option>
              <option value="700" <%= pos.fontWeight == 700 ? 'selected' : '' %>>Bold</option>
              <option value="800" <%= pos.fontWeight == 800 ? 'selected' : '' %>>Extra Bold</option>
            </select>
          </div>
          <div>
            <label class="label">Warna</label>
            <input type="color" id="color" class="input h-10" value="<%= pos.color %>" />
          </div>
          <div>
            <label class="label">Align</label>
            <select id="textAlign" class="input">
              <option value="center" <%= pos.textAlign === 'center' ? 'selected' : '' %>>Center</option>
              <option value="left" <%= pos.textAlign === 'left' ? 'selected' : '' %>>Left</option>
              <option value="right" <%= pos.textAlign === 'right' ? 'selected' : '' %>>Right</option>
            </select>
          </div>
          <div class="col-span-2">
            <label class="label">Font Family</label>
            <select id="fontFamily" class="input">
              <% const fonts = [
                { v: 'serif', l: 'Serif' },
                { v: 'sans-serif', l: 'Sans-serif' },
                { v: 'cursive', l: 'Cursive' },
                { v: "'Times New Roman', serif", l: 'Times New Roman' },
                { v: 'Georgia, serif', l: 'Georgia' }
              ]; %>
              <% fonts.forEach(f => { %>
                <option value="<%= f.v %>" <%= pos.fontFamily === f.v ? 'selected' : '' %>><%= f.l %></option>
              <% }) %>
            </select>
          </div>
        </div>
        <input type="hidden" name="namaLabelPosition" id="posJSON" />
      </div>
    </div>
  </div>

  <div class="card">
    <h4 class="mb-3">Backsound.</h4>
    <p class="text-sm text-body mb-3">Opsional. Looping di halaman undangan (perlu interaksi user untuk play).</p>
    <% if (item.backsoundUrl) { %>
      <audio controls src="<%= item.backsoundUrl %>" class="w-full mb-3"></audio>
      <label class="text-sm flex items-center gap-2 text-body"><input type="checkbox" name="removeBacksound" value="1" /> Hapus backsound</label>
    <% } %>
    <input type="file" name="backsound" accept="audio/*" class="input py-2 mt-2" />
    <p class="text-xs text-mute mt-1">Maks 10MB.</p>
  </div>

  <div class="card">
    <h4 class="mb-3">Template pesan WhatsApp.</h4>
    <p class="text-sm text-body mb-3">Placeholder: <code class="font-mono text-xs bg-canvas-soft-2 px-1 py-0.5 rounded">{nama}</code> <code class="font-mono text-xs bg-canvas-soft-2 px-1 py-0.5 rounded">{kelas}</code> <code class="font-mono text-xs bg-canvas-soft-2 px-1 py-0.5 rounded">{nis}</code> <code class="font-mono text-xs bg-canvas-soft-2 px-1 py-0.5 rounded">{link}</code></p>
    <textarea name="waTemplate" rows="8" class="input"><%= item.waTemplate || '' %></textarea>
  </div>

  <div class="flex gap-2">
    <button class="btn-primary btn-sm">Simpan setting</button>
    <a href="/undangan/preview/angkatan/<%= item.id %>" target="_blank" class="btn-secondary btn-sm">Preview undangan</a>
  </div>
</form>

<script>
(function() {
  // Inisialisasi state pakai JSON.stringify supaya aman dari karakter tanda kutip dalam fontFamily.
  const state = <%- JSON.stringify(pos) %>;

  const canvas = document.getElementById('canvas');
  const box = document.getElementById('nameBox');
  const text = document.getElementById('nameText');
  const handle = document.getElementById('resizeHandle');
  const bgImage = document.getElementById('bgImage');
  const bgFallback = document.getElementById('bgFallback');
  const bgFile = document.getElementById('bgFile');
  const posJSON = document.getElementById('posJSON');
  const actualFsEl = document.getElementById('actualFs');
  const maxFsLabel = document.getElementById('maxFsLabel');

  const inputs = {
    x: document.getElementById('posX'),
    y: document.getElementById('posY'),
    width: document.getElementById('boxW'),
    height: document.getElementById('boxH'),
    fontSize: document.getElementById('fontSize'),
    fontWeight: document.getElementById('fontWeight'),
    color: document.getElementById('color'),
    textAlign: document.getElementById('textAlign'),
    fontFamily: document.getElementById('fontFamily'),
  };

  function render() {
    box.style.left = state.x + '%';
    box.style.top = state.y + '%';
    box.style.width = state.width + '%';
    box.style.height = state.height + '%';
    box.style.transform = 'translate(-50%, -50%)';
    text.style.color = state.color;
    text.style.fontWeight = state.fontWeight;
    text.style.textAlign = state.textAlign;
    text.style.fontFamily = state.fontFamily;
    text.style.textShadow = '0 2px 6px rgba(0,0,0,0.5)';
    fitText();
    posJSON.value = JSON.stringify(state);
    maxFsLabel.textContent = state.fontSize;
  }

  function fitText() {
    const boxW = box.clientWidth - 8;
    const boxH = box.clientHeight;
    if (boxW <= 0 || boxH <= 0) {
      requestAnimationFrame(fitText);
      return;
    }
    const maxFs = Number(state.fontSize) || 36;

    // Ukur teks di font referensi (100px) tanpa wrap
    text.style.whiteSpace = 'nowrap';
    text.style.fontSize = '100px';
    const refW = text.scrollWidth;
    const refH = text.scrollHeight;

    if (refW <= 0 || refH <= 0) {
      text.style.fontSize = maxFs + 'px';
      if (actualFsEl) actualFsEl.textContent = maxFs;
      return;
    }

    // Skala proporsional: cari font size dimana teks pas dengan boxW & boxH
    const byW = Math.floor((boxW / refW) * 100);
    const byH = Math.floor((boxH / refH) * 100);
    let fitted = Math.min(maxFs, byW, byH);

    // Kalau bahkan di font 8px masih melebihi width, coba wrap
    if (fitted < 8) {
      text.style.whiteSpace = 'normal';
      text.style.fontSize = maxFs + 'px';
      const wrapH = text.scrollHeight;
      // Asumsi wrap: width sudah pas, cek tinggi
      if (wrapH > 0) {
        fitted = Math.min(maxFs, Math.floor((boxH / wrapH) * 100));
      }
      fitted = Math.max(6, fitted);
    } else {
      text.style.whiteSpace = 'nowrap';
    }

    fitted = Math.max(6, Math.min(maxFs, fitted));
    text.style.fontSize = fitted + 'px';
    if (actualFsEl) actualFsEl.textContent = fitted;
  }

  Object.keys(inputs).forEach(key => {
    inputs[key].addEventListener('input', () => {
      let v = inputs[key].value;
      if (['x', 'y', 'width', 'height', 'fontSize', 'fontWeight'].includes(key)) v = Number(v);
      state[key] = v;
      render();
    });
  });

  let drag = null;
  function onPointerDown(e, mode) {
    e.preventDefault();
    const rect = canvas.getBoundingClientRect();
    const evt = e.touches ? e.touches[0] : e;
    drag = {
      mode,
      startX: evt.clientX,
      startY: evt.clientY,
      origX: state.x,
      origY: state.y,
      origW: state.width,
      origH: state.height,
      rect,
    };
  }
  function onPointerMove(e) {
    if (!drag) return;
    const evt = e.touches ? e.touches[0] : e;
    const dxPct = ((evt.clientX - drag.startX) / drag.rect.width) * 100;
    const dyPct = ((evt.clientY - drag.startY) / drag.rect.height) * 100;
    const round2 = (n) => Math.round(n * 100) / 100;
    if (drag.mode === 'move') {
      state.x = round2(Math.max(0, Math.min(100, drag.origX + dxPct)));
      state.y = round2(Math.max(0, Math.min(100, drag.origY + dyPct)));
      inputs.x.value = state.x.toFixed(2);
      inputs.y.value = state.y.toFixed(2);
    } else if (drag.mode === 'resize') {
      state.width = round2(Math.max(10, Math.min(100, drag.origW + dxPct * 2)));
      state.height = round2(Math.max(3, Math.min(60, drag.origH + dyPct * 2)));
      inputs.width.value = state.width.toFixed(2);
      inputs.height.value = state.height.toFixed(2);
    }
    render();
  }
  function onPointerUp() { drag = null; }

  box.addEventListener('mousedown', (e) => {
    if (e.target === handle) return;
    onPointerDown(e, 'move');
  });
  box.addEventListener('touchstart', (e) => {
    if (e.target === handle) return;
    onPointerDown(e, 'move');
  }, { passive: false });

  handle.addEventListener('mousedown', (e) => { e.stopPropagation(); onPointerDown(e, 'resize'); });
  handle.addEventListener('touchstart', (e) => { e.stopPropagation(); onPointerDown(e, 'resize'); }, { passive: false });

  document.addEventListener('mousemove', onPointerMove);
  document.addEventListener('touchmove', onPointerMove, { passive: false });
  document.addEventListener('mouseup', onPointerUp);
  document.addEventListener('touchend', onPointerUp);

  bgFile.addEventListener('change', (e) => {
    if (e.target.files[0]) {
      bgImage.src = URL.createObjectURL(e.target.files[0]);
      bgImage.classList.remove('hidden');
      bgFallback.classList.add('hidden');
      bgImage.onload = fitText;
    }
  });

  window.addEventListener('resize', fitText);

  render();
  if (bgImage.complete) fitText();
  else bgImage.addEventListener('load', fitText);
})();
</script>
