<%
const defaults = { x: 50, y: 70, width: 80, height: 14, fontSize: 36, color: '#ffffff', fontWeight: 700, textAlign: 'center', fontFamily: 'serif' };
let saved = angkatanItem.namaLabelPosition;
if (typeof saved === 'string') { try { saved = JSON.parse(saved); } catch { saved = null; } }
const pos = Object.assign({}, defaults, saved || {});
const pageTitle = `Undangan Tasyakuran - ${santriItem.nama}`;
const pageDesc = `Undangan Tasyakuran Kelulusan NFBS Bogor Angkatan ${angkatanItem.nomor} untuk Ananda ${santriItem.nama}. Kami mengundang Bapak/Ibu untuk hadir.`;
const ogImage = angkatanItem.backgroundUrl ? (locals.baseUrl || '') + angkatanItem.backgroundUrl : (locals.baseUrl || '') + '/apple-touch-icon.svg';
const bgUrl = angkatanItem.backgroundUrl || '';
%>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title><%= pageTitle %></title>
  <meta name="description" content="<%= pageDesc %>" />
  <meta name="robots" content="noindex, nofollow" />
  <meta name="theme-color" content="#171717" media="(prefers-color-scheme: dark)" />
  <meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)" />
  <meta property="og:type" content="website" />
  <meta property="og:title" content="<%= pageTitle %>" />
  <meta property="og:description" content="<%= pageDesc %>" />
  <meta property="og:image" content="<%= ogImage %>" />
  <meta property="og:site_name" content="Tasyakuran NFBS Bogor" />
  <meta name="twitter:card" content="summary_large_image" />
  <meta name="twitter:title" content="<%= pageTitle %>" />
  <meta name="twitter:description" content="<%= pageDesc %>" />
  <meta name="twitter:image" content="<%= ogImage %>" />
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
  <link rel="apple-touch-icon" href="/apple-touch-icon.svg" />
  <style>
    *, *::before, *::after { box-sizing: border-box; }
    html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }

    :root {
      --bg: #f4f1ec;
      --env-body: #c9a96e;
      --env-body-dark: #a8884a;
      --env-flap: #dfc088;
      --env-inner: #f5e6c8;
      --env-shadow: 0 10px 40px rgba(0,0,0,0.15);
      --card-bg: linear-gradient(145deg, #fffdf8 0%, #f8f0e3 100%);
      --card-shadow: 0 4px 20px rgba(0,0,0,0.08), inset 0 0 0 1px rgba(180,140,60,0.15);
      --card-label: #a8884a;
      --card-sub: #7a6552;
      --card-nama: #2c1810;
    }
    @media (prefers-color-scheme: dark) {
      :root {
        --bg: #0c0a08;
        --env-body: #5c4520;
        --env-body-dark: #3d2e14;
        --env-flap: #7a5c2e;
        --env-inner: #2a2010;
        --env-shadow: 0 10px 40px rgba(0,0,0,0.5);
        --card-bg: linear-gradient(145deg, #1e1a12 0%, #15120c 100%);
        --card-shadow: 0 4px 20px rgba(0,0,0,0.3), inset 0 0 0 1px rgba(180,140,60,0.2);
        --card-label: #c9a96e;
        --card-sub: #a89580;
        --card-nama: #f5efe6;
      }
    }

    body {
      background: var(--bg);
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      font-family: system-ui, sans-serif;
    }

    .scene {
      position: fixed; inset: 0; z-index: 100;
      display: flex; justify-content: center; align-items: center;
      background: var(--bg);
    }
    .scene.hidden { display: none; }

    /* ===== ENVELOPE ===== */
    .envelope {
      position: absolute;
      width: 300px; height: 200px;
      z-index: 10;
      transition: transform 1.2s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.8s ease;
    }
    .envelope.fall { transform: translateY(110vh) rotate(3deg); opacity: 0; }
    .env-back { position: absolute; inset: 0; background: var(--env-body-dark); border-radius: 8px; box-shadow: var(--env-shadow); }
    .env-inside { position: absolute; top: 0; left: 0; right: 0; height: 100px; background: var(--env-inner); border-radius: 8px 8px 0 0; }
    .env-front { position: absolute; bottom: 0; left: 0; width: 100%; height: 130px; z-index: 3; }
    .env-front::before { content: ''; position: absolute; top: 0; left: 0; width: 0; height: 0; border-bottom: 130px solid var(--env-body); border-left: 150px solid transparent; border-right: 150px solid transparent; }
    .env-front::after { content: ''; position: absolute; bottom: 0; left: 0; right: 0; height: 80px; background: var(--env-body); border-radius: 0 0 8px 8px; }
    .env-flap { position: absolute; top: 0; left: 0; width: 100%; height: 120px; z-index: 4; transform-origin: top center; transform-style: preserve-3d; transition: transform 1.4s cubic-bezier(0.4, 0, 0.2, 1); }
    .env-flap::before { content: ''; position: absolute; top: 0; left: 0; width: 0; height: 0; border-top: 120px solid var(--env-flap); border-left: 150px solid transparent; border-right: 150px solid transparent; backface-visibility: hidden; }
    .env-flap::after { content: ''; position: absolute; bottom: 0; left: 0; width: 0; height: 0; border-bottom: 120px solid var(--env-inner); border-left: 150px solid transparent; border-right: 150px solid transparent; transform: rotateX(180deg); backface-visibility: hidden; }
    .envelope.opened .env-flap { transform: rotateX(-180deg); }

    /* ===== CARD (text card) ===== */
    .card {
      position: absolute;
      width: 250px; height: 160px;
      z-index: 5;
      border-radius: 8px;
      overflow: hidden;
      opacity: 0;
      transform: translateY(0);
      transition: none;
      background: var(--card-bg);
      display: flex; flex-direction: column; align-items: center; justify-content: center;
      padding: 20px; text-align: center;
      box-shadow: var(--card-shadow);
    }
    .card::before { content: ''; position: absolute; top: 12px; left: 50%; transform: translateX(-50%); width: 40px; height: 2px; background: linear-gradient(90deg, transparent, rgba(180,140,60,0.6), transparent); border-radius: 2px; }
    .card::after { content: ''; position: absolute; bottom: 12px; left: 50%; transform: translateX(-50%); width: 30px; height: 2px; background: linear-gradient(90deg, transparent, rgba(180,140,60,0.4), transparent); border-radius: 2px; }
    .card-label { font-size: 9px; font-weight: 500; color: var(--card-label); letter-spacing: 2.5px; text-transform: uppercase; margin-bottom: 8px; }
    .card-subtitle { font-size: 12px; font-weight: 400; color: var(--card-sub); margin-bottom: 10px; line-height: 1.4; }
    .card-nama { font-size: 19px; font-weight: 700; color: var(--card-nama); line-height: 1.3; letter-spacing: -0.3px; }

    /* Step: card rises */
    .card.rise {
      opacity: 1; z-index: 15;
      transform: translateY(-120px);
      transition: opacity 0.5s ease, transform 1.2s cubic-bezier(0.16, 1, 0.3, 1);
    }
    /* Step: card moves to center */
    .card.center {
      transform: translateY(0);
      transition: transform 1s cubic-bezier(0.16, 1, 0.3, 1);
    }
    /* Step: card fades out */
    .card.fade-out {
      opacity: 0;
      transition: opacity 0.6s ease;
    }

    /* ===== UNFOLD CARD (paper opening from bottom to top) ===== */
    .unfold {
      position: absolute;
      width: 250px;
      height: 160px;
      z-index: 20;
      perspective: 800px;
      opacity: 0;
      transition: opacity 0.6s ease;
    }
    .unfold.show { opacity: 1; }

    /* Bottom half stays */
    .unfold-bottom {
      position: absolute;
      bottom: 0; left: 0;
      width: 100%; height: 50%;
      overflow: hidden;
      border-radius: 0 0 8px 8px;
    }
    .unfold-bottom img, .unfold-bottom .fb {
      position: absolute;
      width: 100%; height: 200%;
      bottom: 0; left: 0;
      object-fit: cover;
      object-position: center bottom;
    }
    .unfold-bottom .fb { background: #171717; }

    /* Top half flips open from bottom edge upward */
    .unfold-top {
      position: absolute;
      bottom: 50%; left: 0;
      width: 100%; height: 50%;
      transform-origin: bottom center;
      transform: rotateX(180deg);
      transition: transform 1.4s cubic-bezier(0.4, 0, 0.2, 1);
      overflow: hidden;
      border-radius: 8px 8px 0 0;
    }
    .unfold-top img, .unfold-top .fb {
      position: absolute;
      width: 100%; height: 200%;
      top: 0; left: 0;
      object-fit: cover;
      object-position: center top;
    }
    .unfold-top .fb { background: #171717; }

    .unfold.open .unfold-top {
      transform: rotateX(0deg);
    }

    /* Nama overlay on unfold */
    .unfold-nama {
      position: absolute;
      z-index: 3;
      transform: translate(-50%, -50%);
      display: flex; align-items: center; justify-content: center;
      overflow: hidden; pointer-events: none;
      opacity: 0;
      transition: opacity 1s 0.8s;
    }
    .unfold.open .unfold-nama { opacity: 1; }
    .unfold-nama-text {
      width: 100%; line-height: 1.15; padding: 0 4px;
      text-shadow: 0 2px 6px rgba(0,0,0,0.5);
      white-space: nowrap; min-width: 0;
    }

    /* Zoom to fullscreen */
    .unfold.zoom {
      width: 100vw; max-width: 420px;
      height: calc(100vw * 16 / 9); max-height: 100vh;
      border-radius: 0;
      transition: width 1.2s cubic-bezier(0.16, 1, 0.3, 1),
                  height 1.2s cubic-bezier(0.16, 1, 0.3, 1),
                  max-width 1.2s cubic-bezier(0.16, 1, 0.3, 1),
                  max-height 1.2s cubic-bezier(0.16, 1, 0.3, 1),
                  border-radius 0.8s ease;
    }
    .unfold.zoom .unfold-top,
    .unfold.zoom .unfold-bottom { border-radius: 0; }

    /* ===== FINAL CONTENT ===== */
    .final {
      position: fixed; inset: 0;
      display: flex; justify-content: center; align-items: center;
      z-index: 1; opacity: 0; transition: opacity 0.8s ease;
    }
    .final.visible { opacity: 1; }
    .container { width: 100%; max-width: 420px; aspect-ratio: 9/16; max-height: 100vh; background: #000; position: relative; overflow: hidden; }
    .bg { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
    .bg-fallback { position: absolute; inset: 0; background: #171717; }
    .nama-box { position: absolute; transform: translate(-50%, -50%); display: flex; align-items: center; justify-content: center; overflow: hidden; pointer-events: none; opacity: 0; transition: opacity 1s 0.3s; }
    .nama-box.visible { opacity: 1; }
    .nama-text { width: 100%; line-height: 1.15; padding: 0 4px; text-shadow: 0 2px 6px rgba(0,0,0,0.5); white-space: nowrap; min-width: 0; }
    .audio-control { position: absolute; bottom: 16px; right: 16px; background: rgba(0,0,0,0.45); color: white; border: none; width: 44px; height: 44px; border-radius: 50%; cursor: pointer; z-index: 10; font-size: 16px; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(10px); opacity: 0; transition: opacity 0.5s; }
    .audio-control.visible { opacity: 1; }
    .preview-banner { position: absolute; top: 0; left: 0; right: 0; background: rgba(254,243,199,0.95); color: #92400e; padding: 6px; text-align: center; font-size: 11px; font-weight: 600; z-index: 5; }
    .particles { position: absolute; inset: 0; pointer-events: none; overflow: hidden; z-index: 2; opacity: 0; transition: opacity 1s; }
    .particles.visible { opacity: 1; }
    .particle { position: absolute; background: rgba(212,175,55,0.4); border-radius: 50%; animation: sparkle 5s ease-in-out infinite; }
    @keyframes sparkle { 0%, 100% { transform: translateY(0); opacity: 0; } 10% { opacity: 0.7; } 50% { transform: translateY(-35px); opacity: 0.2; } 90% { opacity: 0; } }
  </style>
</head>
<body>

  <div class="scene" id="scene">
    <div class="envelope" id="envelope">
      <div class="env-back"></div>
      <div class="env-inside"></div>
      <div class="env-flap"></div>
      <div class="env-front"></div>
    </div>

    <div class="card" id="card">
      <div class="card-label">Undangan Tasyakuran</div>
      <div class="card-subtitle">untuk Ayah/Bunda/Wali dari Ananda</div>
      <div class="card-nama"><%= santriItem.nama %></div>
    </div>

    <div class="unfold" id="unfold">
      <div class="unfold-top">
        <% if (bgUrl) { %><img src="<%= bgUrl %>" alt="" /><% } else { %><div class="fb"></div><% } %>
      </div>
      <div class="unfold-bottom">
        <% if (bgUrl) { %><img src="<%= bgUrl %>" alt="" /><% } else { %><div class="fb"></div><% } %>
      </div>
      <div class="unfold-nama" id="unfoldNama">
        <div class="unfold-nama-text" id="unfoldNamaText"></div>
      </div>
    </div>
  </div>

  <div class="final" id="final">
    <div class="container" id="container">
      <% if (bgUrl) { %><img src="<%= bgUrl %>" class="bg" alt="" id="bgImage" /><% } else { %><div class="bg-fallback"></div><% } %>
      <div class="particles" id="particles"></div>
      <div id="namaBox" class="nama-box"></div>
      <% if (locals.isPreview) { %><div class="preview-banner">MODE PREVIEW</div><% } %>
      <% if (angkatanItem.backsoundUrl) { %>
        <audio id="bgaudio" loop preload="auto" src="<%= angkatanItem.backsoundUrl %>"></audio>
        <button id="audioToggle" class="audio-control" aria-label="Toggle audio">🔇</button>
      <% } %>
    </div>
  </div>

  <script>
    (function() {
      var pos = <%- JSON.stringify(pos) %>;
      var namaSantri = <%- JSON.stringify(santriItem.nama) %>;

      var scene = document.getElementById('scene');
      var envelope = document.getElementById('envelope');
      var card = document.getElementById('card');
      var unfold = document.getElementById('unfold');
      var unfoldNama = document.getElementById('unfoldNama');
      var unfoldNamaText = document.getElementById('unfoldNamaText');
      var final = document.getElementById('final');
      var namaBox = document.getElementById('namaBox');
      var particles = document.getElementById('particles');

      // Setup unfold nama position
      unfoldNama.style.left = pos.x + '%';
      unfoldNama.style.top = pos.y + '%';
      unfoldNama.style.width = pos.width + '%';
      unfoldNama.style.height = pos.height + '%';
      unfoldNamaText.textContent = namaSantri;
      unfoldNamaText.style.color = pos.color;
      unfoldNamaText.style.fontWeight = pos.fontWeight;
      unfoldNamaText.style.textAlign = pos.textAlign;
      unfoldNamaText.style.fontFamily = pos.fontFamily;
      unfoldNamaText.style.fontSize = pos.fontSize + 'px';

      /*
        TIMELINE (smoother, more overlap):
        1.2s  - flap opens
        2.0s  - card rises out
        3.2s  - envelope falls
        3.8s  - card moves to center
        4.6s  - card fades, unfold appears (folded)
        5.0s  - unfold opens (top half flips up)
        6.5s  - unfold zooms to fullscreen
        7.8s  - scene hidden, final visible
      */

      setTimeout(function(){ envelope.classList.add('opened'); }, 1200);
      setTimeout(function(){ card.classList.add('rise'); }, 2000);
      setTimeout(function(){ envelope.classList.add('fall'); }, 3200);
      setTimeout(function(){ card.classList.add('center'); }, 3800);
      setTimeout(function(){
        card.classList.add('fade-out');
        unfold.classList.add('show');
      }, 4600);
      setTimeout(function(){ unfold.classList.add('open'); }, 5000);
      setTimeout(function(){ unfold.classList.add('zoom'); }, 6500);
      setTimeout(function(){
        scene.classList.add('hidden');
        final.classList.add('visible');
        namaBox.classList.add('visible');
        particles.classList.add('visible');
        document.body.style.overflow = 'auto';
      }, 7800);

      <% if (angkatanItem.backsoundUrl) { %>
      setTimeout(function(){
        var a = document.getElementById('bgaudio');
        var btn = document.getElementById('audioToggle');
        btn.classList.add('visible');
        a.play().then(function(){ btn.textContent = '🔊'; }).catch(function(){ btn.textContent = '🔇'; });
      }, 7000);
      <% } %>

      // === FINAL NAME BOX ===
      var text = document.createElement('div');
      text.className = 'nama-text';
      text.textContent = namaSantri;
      text.style.color = pos.color;
      text.style.fontWeight = pos.fontWeight;
      text.style.textAlign = pos.textAlign;
      text.style.fontFamily = pos.fontFamily;
      namaBox.appendChild(text);
      namaBox.style.left = pos.x + '%';
      namaBox.style.top = pos.y + '%';
      namaBox.style.width = pos.width + '%';
      namaBox.style.height = pos.height + '%';

      var maxFs = Number(pos.fontSize) || 36;
      function fitText() {
        var boxW = namaBox.clientWidth - 8;
        var boxH = namaBox.clientHeight;
        if (boxW <= 0 || boxH <= 0) { requestAnimationFrame(fitText); return; }
        text.style.whiteSpace = 'nowrap';
        text.style.fontSize = '100px';
        var refW = text.scrollWidth;
        var refH = text.scrollHeight;
        if (refW <= 0 || refH <= 0) { text.style.fontSize = maxFs + 'px'; return; }
        var byW = Math.floor((boxW / refW) * 100);
        var byH = Math.floor((boxH / refH) * 100);
        var fitted = Math.min(maxFs, byW, byH);
        if (fitted < 8) {
          text.style.whiteSpace = 'normal';
          text.style.fontSize = maxFs + 'px';
          var wrapH = text.scrollHeight;
          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';
      }
      var bgImg = document.getElementById('bgImage');
      if (bgImg && !bgImg.complete) bgImg.addEventListener('load', fitText);
      window.addEventListener('resize', fitText);
      requestAnimationFrame(fitText);

      // Particles
      for (var i = 0; i < 15; i++) {
        var p = document.createElement('div');
        p.className = 'particle';
        p.style.left = Math.random() * 100 + '%';
        p.style.top = (20 + Math.random() * 70) + '%';
        p.style.animationDelay = (Math.random() * 5) + 's';
        p.style.animationDuration = (4 + Math.random() * 4) + 's';
        var size = (2 + Math.random() * 4) + 'px';
        p.style.width = size; p.style.height = size;
        particles.appendChild(p);
      }

      // Audio toggle
      <% if (angkatanItem.backsoundUrl) { %>
      (function(){
        var a = document.getElementById('bgaudio');
        var btn = document.getElementById('audioToggle');
        btn.addEventListener('click', function() {
          if (a.paused) { a.play().then(function(){ btn.textContent = '🔊'; }).catch(function(){}); }
          else { a.pause(); btn.textContent = '🔇'; }
        });
      })();
      <% } %>
    })();
  </script>
</body>
</html>
