Skip to content
VibeCodeBench
Back to the app

The code

Love Letter by Gemini 4 Argon

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

index.html

works · auto-checked (Checked by an automated pass. Not hand-played yet.)83.1 KB · 2,411 lines · no libraries
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Purr-fect Post — Love Letter Delivery</title>
<style>
  :root {
    --crimson-deep: #2b070c;
    --crimson-mid: #4d0f18;
    --crimson-warm: #7a1824;
    --crimson-bright: #a82433;
    --rose-accent: #c93b4b;
    --cream-light: #fffdf8;
    --cream-warm: #faf0dc;
    --cream-antique: #f2e0be;
    --gold-bright: #f5d77f;
    --gold-mid: #d4af37;
    --gold-deep: #9e7818;
    --postal-blue: #295896;
    --postal-blue-light: #3c75bd;
    --postal-blue-dark: #18365e;
    --ink-color: #541018;
  }

  * {
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
  }

  html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    min-height: 100%;
    background: radial-gradient(circle at 50% 25%, #63131e 0%, #3a0910 55%, #1f0408 100%);
    color: var(--cream-light);
    font-family: 'Palatino Linotype', 'Book Antiqua', 'Georgia', serif;
    overflow-x: hidden;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
  }

  /* Ambient Canvas for Floating Gold Motes & Hearts */
  #ambient-canvas {
    position: fixed;
    inset: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 0;
  }

  /* Decorative Corner Filigree Frame */
  .page-frame {
    position: fixed;
    inset: 8px;
    border: 1px solid rgba(212, 175, 55, 0.28);
    border-radius: 16px;
    pointer-events: none;
    z-index: 1;
    box-shadow: inset 0 0 25px rgba(0, 0, 0, 0.45);
  }
  .page-frame::before {
    content: '';
    position: absolute;
    inset: 4px;
    border: 1px dashed rgba(245, 215, 127, 0.18);
    border-radius: 12px;
  }

  /* Main App Container */
  .app-shell {
    position: relative;
    z-index: 2;
    max-width: 500px;
    margin: 0 auto;
    min-height: 100vh;
    min-height: 100dvh;
    padding: 16px 16px 26px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  /* Top Bar */
  .top-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 4px 4px 10px;
    gap: 8px;
  }

  .brand-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 1.05rem;
    font-weight: 700;
    color: var(--gold-bright);
    letter-spacing: 0.04em;
    text-shadow: 0 2px 6px rgba(0,0,0,0.5);
  }

  .brand-seal {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background: radial-gradient(circle at 35% 35%, #d63c4a, #851520);
    border: 1.5px solid var(--gold-bright);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 6px rgba(0,0,0,0.4);
    font-size: 0.85rem;
  }

  .top-controls {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .icon-btn {
    min-height: 44px;
    padding: 0 14px;
    border-radius: 22px;
    border: 1.5px solid rgba(212, 175, 55, 0.55);
    background: rgba(58, 9, 16, 0.78);
    color: var(--cream-warm);
    font-family: inherit;
    font-size: 0.88rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    cursor: pointer;
    box-shadow: 0 3px 10px rgba(0,0,0,0.35);
    transition: transform 0.15s ease, background 0.2s ease, border-color 0.2s ease;
  }
  .icon-btn:active {
    transform: scale(0.95);
  }

  /* Demo Banner */
  #demo-banner {
    display: none;
    align-items: center;
    justify-content: center;
    gap: 8px;
    background: linear-gradient(90deg, rgba(168, 36, 51, 0.92), rgba(114, 20, 32, 0.92));
    border: 1.5px solid var(--gold-bright);
    color: var(--cream-light);
    padding: 8px 14px;
    border-radius: 999px;
    font-size: 0.85rem;
    font-weight: 600;
    margin: 0 auto 10px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.45);
    animation: gentlePulse 2s infinite ease-in-out;
    cursor: pointer;
  }
  #demo-banner.visible {
    display: inline-flex;
  }

  @keyframes gentlePulse {
    0%, 100% { transform: scale(1); box-shadow: 0 4px 15px rgba(0,0,0,0.45); }
    50% { transform: scale(1.02); box-shadow: 0 4px 20px rgba(245, 215, 127, 0.35); }
  }

  /* Stage Views */
  .stage-view {
    display: none;
    flex: 1;
    flex-direction: column;
    justify-content: center;
    animation: fadeInStage 0.4s ease forwards;
  }
  .stage-view.active {
    display: flex;
  }

  @keyframes fadeInStage {
    from { opacity: 0; transform: translateY(8px); }
    to { opacity: 1; transform: translateY(0); }
  }

  /*Paper Theme Variables applied dynamically*/
  .paper-sheet {
    position: relative;
    border-radius: 16px;
    padding: 20px 18px;
    color: var(--ink-color);
    transition: background 0.35s ease, border-color 0.35s ease, box-shadow 0.35s ease;
    box-shadow:
      0 14px 36px rgba(0, 0, 0, 0.55),
      0 2px 6px rgba(0, 0, 0, 0.3),
      inset 0 0 0 2px rgba(212, 175, 55, 0.45);
  }

  /* Style 1: Royal Cream & Gold */
  .paper-style-royal {
    --ink-color: #5a1219;
    --accent-rule: #c89d32;
    --sub-text: #84353d;
    background:
      radial-gradient(circle at 15% 15%, rgba(255, 255, 255, 0.8), transparent 60%),
      linear-gradient(145deg, #fffdf8 0%, #faf0dc 55%, #f1dfc0 100%);
    border: 2.5px solid #d4af37;
  }
  .paper-style-royal::before {
    content: '';
    position: absolute;
    inset: 6px;
    border: 1px solid rgba(190, 142, 35, 0.45);
    border-radius: 10px;
    pointer-events: none;
  }

  /* Style 2: Velvet Rose Damask */
  .paper-style-rose {
    --ink-color: #540d17;
    --accent-rule: #b82939;
    --sub-text: #8c2633;
    background:
      radial-gradient(circle at 80% 15%, rgba(255, 240, 240, 0.9), transparent 55%),
      repeating-linear-gradient(45deg, rgba(184, 41, 57, 0.03) 0px, rgba(184, 41, 57, 0.03) 8px, transparent 8px, transparent 16px),
      linear-gradient(145deg, #fff7f5 0%, #fce8e4 55%, #f3d2cc 100%);
    border: 2.5px solid #c94c5b;
    box-shadow:
      0 14px 36px rgba(0, 0, 0, 0.55),
      inset 0 0 0 2px rgba(201, 76, 91, 0.35);
  }
  .paper-style-rose::before {
    content: '';
    position: absolute;
    inset: 6px;
    border: 1.5px dotted rgba(168, 36, 51, 0.45);
    border-radius: 10px;
    pointer-events: none;
  }

  /* Style 3: Starlit Gilded Vellum */
  .paper-style-gilded {
    --ink-color: #461116;
    --accent-rule: #a87914;
    --sub-text: #733422;
    background:
      radial-gradient(circle at 50% 10%, rgba(255, 248, 224, 0.85), transparent 65%),
      repeating-radial-gradient(circle at 20% 30%, rgba(212, 175, 55, 0.06) 0, rgba(212, 175, 55, 0.06) 2px, transparent 3px, transparent 18px),
      linear-gradient(145deg, #fbf1dc 0%, #f1ddb4 52%, #e3c489 100%);
    border: 2.5px solid #e0b84c;
    box-shadow:
      0 14px 36px rgba(0, 0, 0, 0.6),
      inset 0 0 18px rgba(180, 125, 20, 0.22);
  }
  .paper-style-gilded::before {
    content: '';
    position: absolute;
    inset: 6px;
    border: 1.5px double rgba(158, 112, 18, 0.55);
    border-radius: 10px;
    pointer-events: none;
  }

  /* Corner SVG Ornaments inside Paper */
  .corner-ornament {
    position: absolute;
    width: 24px;
    height: 24px;
    pointer-events: none;
    opacity: 0.75;
  }
  .corner-tl { top: 9px; left: 9px; }
  .corner-tr { top: 9px; right: 9px; transform: scaleX(-1); }
  .corner-bl { bottom: 9px; left: 9px; transform: scaleY(-1); }
  .corner-br { bottom: 9px; right: 9px; transform: scale(-1, -1); }

  /* COMPOSE VIEW */
  .compose-header {
    text-align: center;
    margin-bottom: 14px;
  }
  .compose-header h1 {
    margin: 0;
    font-size: 1.45rem;
    color: var(--ink-color);
    letter-spacing: 0.02em;
  }
  .compose-header p {
    margin: 4px 0 0;
    font-size: 0.88rem;
    color: var(--sub-text);
    font-style: italic;
  }

  .form-row-duo {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
    margin-bottom: 12px;
  }

  .field-group {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .field-label {
    font-size: 0.82rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: var(--sub-text);
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .text-input, .text-area {
    width: 100%;
    border-radius: 10px;
    border: 1.5px solid rgba(150, 90, 40, 0.35);
    background: rgba(255, 255, 255, 0.68);
    color: var(--ink-color);
    font-family: 'Segoe Script', 'Bradley Hand', 'Apple Chancery', 'Palatino Linotype', cursive, serif;
    font-size: 1.05rem;
    padding: 10px 12px;
    outline: none;
    transition: border-color 0.2s, background 0.2s, box-shadow 0.2s;
    user-select: text;
    -webkit-user-select: text;
  }
  .text-input:focus, .text-area:focus {
    border-color: var(--crimson-bright);
    background: rgba(255, 255, 255, 0.92);
    box-shadow: 0 0 0 3px rgba(168, 36, 51, 0.15);
  }

  .text-area {
    min-height: 92px;
    resize: none;
    line-height: 1.45;
  }

  /* One-finger Quick Inspiration Chips */
  .quick-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 6px;
    margin: 6px 0 12px;
    flex-wrap: wrap;
  }
  .quick-chip {
    min-height: 38px;
    padding: 6px 11px;
    border-radius: 999px;
    border: 1px solid rgba(138, 38, 51, 0.35);
    background: rgba(168, 36, 51, 0.09);
    color: var(--ink-color);
    font-family: inherit;
    font-size: 0.8rem;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    transition: transform 0.12s ease, background 0.2s ease;
  }
  .quick-chip:active {
    transform: scale(0.95);
    background: rgba(168, 36, 51, 0.2);
  }

  /* Paper Style Selector (Big One-Finger Buttons) */
  .style-picker-section {
    margin-bottom: 14px;
  }
  .style-picker-title {
    font-size: 0.8rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: var(--sub-text);
    margin-bottom: 6px;
    text-align: center;
  }

  .style-buttons-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
  }

  .style-btn {
    min-height: 52px;
    border-radius: 12px;
    border: 2px solid rgba(140, 95, 30, 0.35);
    padding: 6px 6px;
    font-family: inherit;
    font-size: 0.82rem;
    font-weight: 700;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 4px;
    transition: transform 0.14s ease, border-color 0.2s ease, box-shadow 0.2s ease;
    position: relative;
  }
  .style-btn:active {
    transform: scale(0.95);
  }
  .style-btn[data-style="royal"] {
    background: linear-gradient(135deg, #fffdf8, #f3e2c3);
    color: #5a1219;
  }
  .style-btn[data-style="rose"] {
    background: linear-gradient(135deg, #fff5f3, #f5d0c9);
    color: #590d16;
  }
  .style-btn[data-style="gilded"] {
    background: linear-gradient(135deg, #fbf0d8, #e2c283);
    color: #461116;
  }

  .style-btn.selected {
    border-color: #9e1b28;
    box-shadow: 0 0 0 2.5px var(--gold-bright), 0 4px 10px rgba(0,0,0,0.25);
    transform: translateY(-1px);
  }

  .style-swatch-dot {
    width: 18px;
    height: 18px;
    border-radius: 50%;
    border: 1.5px solid rgba(0,0,0,0.25);
    display: inline-block;
  }
  .swatch-royal { background: radial-gradient(circle at 30% 30%, #fff, #d4af37); }
  .swatch-rose { background: radial-gradient(circle at 30% 30%, #ffd6d6, #b82939); }
  .swatch-gilded { background: radial-gradient(circle at 30% 30%, #fff0b8, #9e7312); }

  /* Primary Send Button */
  .primary-send-btn {
    width: 100%;
    min-height: 56px;
    border-radius: 14px;
    border: 2px solid var(--gold-bright);
    background: linear-gradient(180deg, #b82535 0%, #821320 100%);
    color: var(--cream-light);
    font-family: inherit;
    font-size: 1.15rem;
    font-weight: 700;
    letter-spacing: 0.04em;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    box-shadow:
      0 8px 20px rgba(90, 10, 20, 0.5),
      inset 0 1px 1px rgba(255, 255, 255, 0.35);
    transition: transform 0.14s ease, box-shadow 0.2s ease, filter 0.2s ease;
  }
  .primary-send-btn:active, .primary-send-btn.pressed {
    transform: scale(0.97) translateY(2px);
    filter: brightness(1.08);
  }

  /* =====================================================
     STAGE 2: CAT POSTMAN DELIVERY & ENVELOPE
     ===================================================== */
  .delivery-arena {
    position: relative;
    width: 100%;
    min-height: 440px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    border-radius: 18px;
    background: radial-gradient(ellipse at 50% 75%, rgba(212, 175, 55, 0.16) 0%, rgba(58, 10, 18, 0.4) 65%, transparent 100%);
    padding: 14px;
  }

  /* Soft Tabletop / Stage Floor Horizon */
  .stage-floor {
    position: absolute;
    bottom: 36px;
    left: 6%;
    right: 6%;
    height: 42px;
    border-radius: 50%;
    background: radial-gradient(ellipse at center, rgba(212, 175, 55, 0.22) 0%, rgba(120, 20, 30, 0.18) 55%, transparent 80%);
    pointer-events: none;
  }

  /* Trail of Paw Prints */
  .paw-trail {
    position: absolute;
    bottom: 62px;
    left: 10%;
    width: 45%;
    height: 24px;
    pointer-events: none;
  }
  .paw-print {
    position: absolute;
    font-size: 0.9rem;
    color: rgba(245, 215, 127, 0.45);
    opacity: 0;
    transform: scale(0.5);
    transition: opacity 0.3s ease, transform 0.3s ease;
  }
  .paw-print.visible {
    opacity: 1;
    transform: scale(1);
  }

  /* Cat Postman Wrapper */
  .cat-postman-actor {
    position: relative;
    width: 190px;
    height: 200px;
    z-index: 4;
    transform: translateX(-290px);
    will-change: transform;
  }

  /* Walking Bob & Leg Cycle when class .walking is active */
  .cat-postman-actor.walking .cat-svg-body {
    animation: catBob 0.32s infinite alternate ease-in-out;
  }
  .cat-postman-actor.walking .cat-leg-left {
    animation: legSwingA 0.32s infinite alternate ease-in-out;
    transform-origin: 85px 152px;
  }
  .cat-postman-actor.walking .cat-leg-right {
    animation: legSwingB 0.32s infinite alternate ease-in-out;
    transform-origin: 108px 152px;
  }
  .cat-postman-actor.walking .cat-tail {
    animation: tailWag 0.45s infinite alternate ease-in-out;
    transform-origin: 58px 135px;
  }

  /* Tipping Cap / Bow when arrived */
  .cat-postman-actor.bowing .cat-head-group {
    animation: headBow 0.7s ease-in-out;
    transform-origin: 96px 86px;
  }
  .cat-postman-actor.bowing .cat-arm-salute {
    animation: armTipCap 0.7s ease-in-out;
    transform-origin: 118px 108px;
  }

  /* Sitting on side watching user tap envelope */
  .cat-postman-actor.parked {
    transition: transform 0.65s cubic-bezier(0.34, 1.3, 0.64, 1);
    transform: translate(-115px, -95px) scale(0.68) !important;
  }

  @keyframes catBob {
    0% { transform: translateY(0px) rotate(-1.5deg); }
    100% { transform: translateY(-7px) rotate(1.5deg); }
  }
  @keyframes legSwingA {
    0% { transform: rotate(-20deg); }
    100% { transform: rotate(20deg); }
  }
  @keyframes legSwingB {
    0% { transform: rotate(20deg); }
    100% { transform: rotate(-20deg); }
  }
  @keyframes tailWag {
    0% { transform: rotate(-12deg); }
    100% { transform: rotate(14deg); }
  }
  @keyframes headBow {
    0%, 100% { transform: rotate(0deg) translateY(0); }
    50% { transform: rotate(10deg) translateY(4px); }
  }
  @keyframes armTipCap {
    0%, 100% { transform: rotate(0deg); }
    45%, 65% { transform: rotate(-42deg) translateY(-10px); }
  }

  /* Cat Speech Bubble */
  .cat-speech {
    position: absolute;
    top: -16px;
    left: 50%;
    transform: translateX(-50%) scale(0.7);
    background: var(--cream-light);
    color: var(--crimson-warm);
    border: 2px solid var(--gold-mid);
    padding: 5px 12px;
    border-radius: 999px;
    font-size: 0.84rem;
    font-weight: 700;
    white-space: nowrap;
    box-shadow: 0 4px 12px rgba(0,0,0,0.35);
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.25s ease, transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
  }
  .cat-speech.visible {
    opacity: 1;
    transform: translateX(-50%) scale(1);
  }
  .cat-speech::after {
    content: '';
    position: absolute;
    bottom: -7px;
    left: 50%;
    transform: translateX(-50%);
    border-width: 7px 6px 0;
    border-style: solid;
    border-color: var(--gold-mid) transparent transparent;
  }

  /* Delivered Interactive Envelope in Front of User */
  .delivered-envelope-wrap {
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    z-index: 6;
    opacity: 0;
    pointer-events: none;
    transform: translateY(30px) scale(0.55);
    transition: opacity 0.5s ease, transform 0.6s cubic-bezier(0.34, 1.45, 0.64, 1);
  }
  .delivered-envelope-wrap.presented {
    opacity: 1;
    pointer-events: auto;
    transform: translateY(18px) scale(1);
  }

  .envelope-touch-button {
    position: relative;
    width: 286px;
    height: 194px;
    background: none;
    border: none;
    padding: 0;
    cursor: pointer;
    perspective: 900px;
    outline: none;
    animation: envelopeFloat 2.8s infinite ease-in-out;
  }
  .envelope-touch-button:active {
    transform: scale(0.96);
  }

  @keyframes envelopeFloat {
    0%, 100% { transform: translateY(0px); }
    50% { transform: translateY(-6px); }
  }

  .envelope-box {
    position: relative;
    width: 100%;
    height: 100%;
    border-radius: 12px;
    background: linear-gradient(160deg, #fffaf0 0%, #f5e4c3 100%);
    border: 2.5px solid var(--gold-mid);
    box-shadow:
      0 18px 40px rgba(0, 0, 0, 0.6),
      0 0 25px rgba(245, 215, 127, 0.25);
    overflow: visible;
  }

  /* Rising Letter Card inside Envelope when Opening */
  .envelope-rising-card {
    position: absolute;
    left: 14px;
    right: 14px;
    top: 16px;
    bottom: 16px;
    background: linear-gradient(180deg, #fffdf9, #f7e6c4);
    border: 1.5px solid var(--gold-mid);
    border-radius: 8px;
    z-index: 2;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    color: var(--crimson-bright);
    transition: transform 0.65s cubic-bezier(0.34, 1.4, 0.64, 1);
  }
  .envelope-touch-button.opening .envelope-rising-card {
    transform: translateY(-76px) scale(1.03);
  }

  /* Envelope Front Pocket Flaps */
  .envelope-pocket-svg {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    z-index: 3;
    border-radius: 10px;
    overflow: hidden;
    pointer-events: none;
  }

  /* Addressing on the Envelope */
  .envelope-address-plate {
    position: absolute;
    bottom: 16px;
    left: 20px;
    right: 20px;
    z-index: 4;
    text-align: center;
    pointer-events: none;
  }
  .env-for-line {
    font-family: 'Segoe Script', 'Bradley Hand', 'Apple Chancery', cursive, serif;
    font-size: 1.18rem;
    font-weight: 700;
    color: var(--crimson-warm);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .env-from-line {
    font-size: 0.78rem;
    color: #7c4832;
    letter-spacing: 0.04em;
    margin-top: 2px;
  }

  /* Top Flap that Folds Open */
  .envelope-top-flap {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 112px;
    z-index: 5;
    transform-origin: top center;
    transition: transform 0.6s cubic-bezier(0.4, 0, 0.2, 1), z-index 0s 0.3s;
    pointer-events: none;
  }
  .envelope-touch-button.opening .envelope-top-flap {
    transform: rotateX(180deg);
    z-index: 1;
  }

  /* Wax Seal in Center of Envelope */
  .wax-seal-badge {
    position: absolute;
    top: 86px;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 54px;
    height: 54px;
    border-radius: 50%;
    background: radial-gradient(circle at 35% 30%, #e03c4c 0%, #9e1623 65%, #660b14 100%);
    border: 2px solid var(--gold-bright);
    box-shadow:
      0 4px 12px rgba(0, 0, 0, 0.45),
      inset 0 0 8px rgba(255, 215, 130, 0.4);
    z-index: 6;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--gold-bright);
    font-size: 1.35rem;
    transition: transform 0.35s ease, opacity 0.35s ease;
  }
  .envelope-touch-button.opening .wax-seal-badge {
    transform: translate(-50%, -50%) scale(1.35);
    opacity: 0;
  }

  .tap-prompt-pill {
    margin-top: 18px;
    background: rgba(43, 7, 12, 0.85);
    border: 1.5px solid var(--gold-bright);
    color: var(--gold-bright);
    padding: 10px 20px;
    border-radius: 999px;
    font-size: 0.98rem;
    font-weight: 700;
    letter-spacing: 0.03em;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5);
    animation: promptPulse 1.6s infinite ease-in-out;
    cursor: pointer;
  }

  @keyframes promptPulse {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.05); background: rgba(122, 24, 36, 0.92); }
  }

  /* =====================================================
     STAGE 3: UNFOLDED PAPER POP-UP SCENE & LETTER
     ===================================================== */
  .opened-letter-card {
    width: 100%;
    padding: 14px 14px 18px;
    perspective: 1100px;
  }

  /* 3D Paper Pop-Up Diorama Stage */
  .popup-diorama-stage {
    position: relative;
    width: 100%;
    height: 235px;
    border-radius: 12px;
    overflow: hidden;
    background:
      radial-gradient(circle at 50% 28%, rgba(245, 215, 127, 0.25) 0%, transparent 55%),
      linear-gradient(180deg, #380912 0%, #5e1320 62%, #7d1c2a 100%);
    border: 2px solid var(--accent-rule, #d4af37);
    box-shadow:
      inset 0 10px 28px rgba(0, 0, 0, 0.55),
      0 6px 16px rgba(0, 0, 0, 0.22);
    margin-bottom: 14px;
    cursor: pointer;
    transform-style: preserve-3d;
  }

  /* Center Vertical Paper Fold Crease of a Pop-up Card */
  .popup-crease-vertical {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 50%;
    width: 2px;
    background: linear-gradient(180deg, rgba(255,255,255,0.12), rgba(0,0,0,0.45), rgba(255,255,255,0.2));
    z-index: 10;
    pointer-events: none;
  }

  /* Paper Floor Fold of the Pop-Up Card */
  .popup-paper-floor {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 44px;
    background: linear-gradient(180deg, rgba(238, 214, 174, 0.92) 0%, rgba(250, 238, 215, 0.98) 100%);
    border-top: 2px solid var(--gold-mid);
    z-index: 2;
  }

  /* Unfolding Paper Layers */
  .popup-layer {
    position: absolute;
    inset: 0;
    transform-origin: 50% 88%;
    transform: rotateX(-86deg) scale(0.92);
    opacity: 0;
    transition:
      transform 0.85s cubic-bezier(0.34, 1.48, 0.64, 1),
      opacity 0.45s ease;
    pointer-events: none;
  }

  .popup-diorama-stage.unfolded .popup-layer {
    transform: rotateX(0deg) scale(1);
    opacity: 1;
  }
  .popup-diorama-stage.unfolded .layer-arch { transition-delay: 0.06s; }
  .popup-diorama-stage.unfolded .layer-moon { transition-delay: 0.18s; }
  .popup-diorama-stage.unfolded .layer-flowers { transition-delay: 0.30s; }
  .popup-diorama-stage.unfolded .layer-cats { transition-delay: 0.42s; }
  .popup-diorama-stage.unfolded .layer-hearts { transition-delay: 0.55s; }

  /* Floating Animation for Pop-Up Elements once unfolded */
  .popup-diorama-stage.unfolded .bob-gentle {
    animation: paperBob 3.2s infinite ease-in-out;
  }
  .popup-diorama-stage.unfolded .bob-hearts {
    animation: heartSpring 2.4s infinite ease-in-out;
  }

  @keyframes paperBob {
    0%, 100% { transform: translateY(0px); }
    50% { transform: translateY(-4px); }
  }
  @keyframes heartSpring {
    0%, 100% { transform: translateY(0px) scale(1); }
    50% { transform: translateY(-6px) scale(1.05); }
  }

  .popup-tap-hint {
    position: absolute;
    top: 8px;
    right: 10px;
    background: rgba(43, 7, 12, 0.65);
    border: 1px solid rgba(245, 215, 127, 0.5);
    color: var(--gold-bright);
    font-size: 0.7rem;
    padding: 3px 8px;
    border-radius: 999px;
    z-index: 12;
    pointer-events: none;
  }

  /* Interactive Burst Hearts on Tap */
  .pop-burst-heart {
    position: absolute;
    pointer-events: none;
    z-index: 15;
    font-size: 1.25rem;
    animation: riseAndFade 1.1s ease-out forwards;
  }
  @keyframes riseAndFade {
    0% { opacity: 1; transform: translate(-50%, 0) scale(0.6) rotate(0deg); }
    100% { opacity: 0; transform: translate(-50%, -75px) scale(1.35) rotate(18deg); }
  }

  /* Handwritten Message Section */
  .letter-writing-sheet {
    position: relative;
    padding: 8px 10px 6px;
    min-height: 155px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .salutation-line {
    font-family: 'Segoe Script', 'Bradley Hand', 'Apple Chancery', 'Snell Roundhand', cursive, serif;
    font-size: 1.18rem;
    font-weight: 700;
    color: var(--ink-color);
    margin-bottom: 8px;
    border-bottom: 1px solid rgba(180, 130, 50, 0.25);
    padding-bottom: 4px;
  }

  .handwriting-body-wrap {
    position: relative;
    min-height: 78px;
    padding: 4px 2px 10px;
  }

  .handwriting-text {
    font-family: 'Segoe Script', 'Bradley Hand', 'Apple Chancery', 'Snell Roundhand', 'Brush Script MT', cursive, serif;
    font-size: 1.16rem;
    line-height: 1.58;
    color: var(--ink-color);
    word-wrap: break-word;
    white-space: pre-wrap;
  }

  /* Individual Handwritten Letter Span */
  .ink-char {
    display: inline-block;
    opacity: 0;
    transform: translateY(4px) scale(0.75) rotate(var(--rot, 0deg));
    transition: opacity 0.14s ease, transform 0.18s cubic-bezier(0.34, 1.56, 0.64, 1);
  }
  .ink-char.space-char {
    display: inline;
  }
  .ink-char.inked {
    opacity: 1;
    transform: translateY(var(--jy, 0px)) scale(1) rotate(var(--rot, 0deg));
  }

  /* Animated Fountain Pen Nib following the active character */
  #fountain-pen-nib {
    position: absolute;
    width: 34px;
    height: 34px;
    pointer-events: none;
    z-index: 10;
    opacity: 0;
    transition: top 0.05s linear, left 0.05s linear, opacity 0.25s ease;
    filter: drop-shadow(2px 4px 4px rgba(0,0,0,0.28));
  }
  #fountain-pen-nib.writing {
    opacity: 1;
    animation: penScratch 0.16s infinite alternate ease-in-out;
  }

  @keyframes penScratch {
    0% { transform: translate(0, 0) rotate(-3deg); }
    100% { transform: translate(1px, -2px) rotate(3deg); }
  }

  /* Sign-off & Flourish */
  .signoff-block {
    text-align: right;
    margin-top: 4px;
    opacity: 0;
    transform: translateY(6px);
    transition: opacity 0.45s ease, transform 0.45s ease;
  }
  .signoff-block.visible {
    opacity: 1;
    transform: translateY(0);
  }
  .signoff-label {
    font-size: 0.85rem;
    font-style: italic;
    color: var(--sub-text);
  }
  .signoff-name {
    font-family: 'Segoe Script', 'Bradley Hand', 'Apple Chancery', cursive, serif;
    font-size: 1.22rem;
    font-weight: 700;
    color: var(--ink-color);
  }
  .flourish-svg {
    width: 130px;
    height: 18px;
    margin-left: auto;
    display: block;
  }
  .flourish-path {
    stroke-dasharray: 200;
    stroke-dashoffset: 200;
    transition: stroke-dashoffset 0.9s ease-out;
  }
  .signoff-block.visible .flourish-path {
    stroke-dashoffset: 0;
  }

  /* Bottom Controls on Opened Letter */
  .opened-controls-panel {
    margin-top: 12px;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .action-buttons-row {
    display: grid;
    grid-template-columns: 1.35fr 1fr;
    gap: 10px;
  }

  .replay-btn {
    min-height: 52px;
    border-radius: 14px;
    border: 2px solid var(--gold-bright);
    background: linear-gradient(180deg, #b82535 0%, #7d121e 100%);
    color: var(--cream-light);
    font-family: inherit;
    font-size: 1rem;
    font-weight: 700;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.45);
    transition: transform 0.14s ease;
  }
  .replay-btn:active {
    transform: scale(0.96);
  }

  .secondary-btn {
    min-height: 52px;
    border-radius: 14px;
    border: 1.5px solid var(--gold-mid);
    background: rgba(43, 7, 12, 0.82);
    color: var(--cream-warm);
    font-family: inherit;
    font-size: 0.95rem;
    font-weight: 700;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.35);
    transition: transform 0.14s ease;
  }
  .secondary-btn:active {
    transform: scale(0.96);
  }

  /* Responsive adjustments for smaller phone screens */
  @media (max-height: 700px) {
    .app-shell { padding: 10px 12px 18px; }
    .popup-diorama-stage { height: 205px; }
    .text-area { min-height: 76px; }
  }
</style>
</head>
<body>

<canvas id="ambient-canvas"></canvas>
<div class="page-frame"></div>

<div class="app-shell">
  <!-- Top Header & Sound Toggle -->
  <header class="top-bar">
    <div class="brand-title">
      <span class="brand-seal">🐾</span>
      <span>Purr-fect Love Post</span>
    </div>
    <div class="top-controls">
      <button type="button" id="sound-toggle-btn" class="icon-btn" aria-label="Toggle Sound">
        <span id="sound-icon">♪</span>
        <span id="sound-label">Sound On</span>
      </button>
    </div>
  </header>

  <!-- Demo Mode Indicator -->
  <div id="demo-banner" role="button" tabindex="0">
    <span>✦ Hands-Free Demo — Tap anywhere to write yours</span>
  </div>

  <!-- =========================================================
       VIEW 1: WRITE A LOVE LETTER
       ========================================================= -->
  <main id="view-compose" class="stage-view active">
    <div id="compose-paper" class="paper-sheet paper-style-royal">
      <!-- Corner Ornaments -->
      <svg class="corner-ornament corner-tl" viewBox="0 0 32 32"><path d="M2 30 C2 14 14 2 30 2 M2 20 C8 20 20 8 20 2" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="7" cy="7" r="2.2" fill="currentColor"/></svg>
      <svg class="corner-ornament corner-tr" viewBox="0 0 32 32"><path d="M2 30 C2 14 14 2 30 2 M2 20 C8 20 20 8 20 2" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="7" cy="7" r="2.2" fill="currentColor"/></svg>
      <svg class="corner-ornament corner-bl" viewBox="0 0 32 32"><path d="M2 30 C2 14 14 2 30 2 M2 20 C8 20 20 8 20 2" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="7" cy="7" r="2.2" fill="currentColor"/></svg>
      <svg class="corner-ornament corner-br" viewBox="0 0 32 32"><path d="M2 30 C2 14 14 2 30 2 M2 20 C8 20 20 8 20 2" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="7" cy="7" r="2.2" fill="currentColor"/></svg>

      <div class="compose-header">
        <h1>Write a Love Letter</h1>
        <p>Delivered by our little cat postman in his blue cap</p>
      </div>

      <div class="form-row-duo">
        <div class="field-group">
          <label class="field-label" for="input-from">From</label>
          <input type="text" id="input-from" class="text-input" maxlength="28" value="Oliver" placeholder="Your name">
        </div>
        <div class="field-group">
          <label class="field-label" for="input-for">For</label>
          <input type="text" id="input-for" class="text-input" maxlength="28" value="Luna" placeholder="Their name">
        </div>
      </div>

      <div class="field-group">
        <div class="field-label">
          <label for="input-message">Your Message</label>
        </div>
        <textarea id="input-message" class="text-area" maxlength="200" placeholder="Write something sweet...">Every moment with you feels like moonlight and warm tea. You are my favorite person in the whole world.</textarea>
      </div>

      <!-- One-Finger Sweet Message Presets (no keyboard needed) -->
      <div class="quick-bar">
        <button type="button" class="quick-chip" data-preset="0">🌙 Moonlight &amp; tea</button>
        <button type="button" class="quick-chip" data-preset="1">🐾 Two cats &amp; stars</button>
        <button type="button" class="quick-chip" data-preset="2">🌹 My whole heart</button>
      </div>

      <!-- Choose 1 of 3 Paper Styles -->
      <div class="style-picker-section">
        <div class="style-picker-title">Choose Paper Style</div>
        <div class="style-buttons-grid" id="compose-style-grid">
          <button type="button" class="style-btn selected" data-style="royal">
            <span class="style-swatch-dot swatch-royal"></span>
            <span>Cream &amp; Gold</span>
          </button>
          <button type="button" class="style-btn" data-style="rose">
            <span class="style-swatch-dot swatch-rose"></span>
            <span>Velvet Rose</span>
          </button>
          <button type="button" class="style-btn" data-style="gilded">
            <span class="style-swatch-dot swatch-gilded"></span>
            <span>Starlit Gold</span>
          </button>
        </div>
      </div>

      <button type="button" id="btn-send-letter" class="primary-send-btn">
        <span>🐾</span>
        <span>Send Love Letter</span>
      </button>
    </div>
  </main>

  <!-- =========================================================
       VIEW 2: CAT POSTMAN DELIVERY & ENVELOPE
       ========================================================= -->
  <section id="view-delivery" class="stage-view">
    <div class="delivery-arena" id="delivery-arena">
      <div class="stage-floor"></div>

      <!-- Paw Prints Trail -->
      <div class="paw-trail" id="paw-trail">
        <span class="paw-print" style="left: 5%; top: 8px;">🐾</span>
        <span class="paw-print" style="left: 30%; top: -2px;">🐾</span>
        <span class="paw-print" style="left: 58%; top: 7px;">🐾</span>
        <span class="paw-print" style="left: 85%; top: -1px;">🐾</span>
      </div>

      <!-- Small Cat Postman in a Blue Cap -->
      <div class="cat-postman-actor" id="cat-postman">
        <div class="cat-speech" id="cat-speech">Special delivery! ♪</div>

        <svg viewBox="0 0 200 200" width="100%" height="100%" overflow="visible">
          <!-- Soft ground shadow under cat -->
          <ellipse cx="100" cy="182" rx="44" ry="10" fill="rgba(0,0,0,0.35)"/>

          <g class="cat-svg-body">
            <!-- Swishing Tail -->
            <g class="cat-tail">
              <path d="M62 140 C30 135 22 102 38 92 C48 86 54 98 46 108 C40 116 48 126 64 130" fill="none" stroke="#f3c678" stroke-width="13" stroke-linecap="round"/>
              <path d="M35 97 C40 93 46 96 45 102" fill="none" stroke="#d99b43" stroke-width="4" stroke-linecap="round"/>
            </g>

            <!-- Back Legs -->
            <g class="cat-leg-left">
              <rect x="76" y="148" width="16" height="28" rx="8" fill="#eab869" stroke="#6e2219" stroke-width="2"/>
              <ellipse cx="84" cy="176" rx="10" ry="6" fill="#fff8ea" stroke="#6e2219" stroke-width="2"/>
            </g>
            <g class="cat-leg-right">
              <rect x="102" y="148" width="16" height="28" rx="8" fill="#f3c678" stroke="#6e2219" stroke-width="2"/>
              <ellipse cx="110" cy="176" rx="10" ry="6" fill="#fff8ea" stroke="#6e2219" stroke-width="2"/>
            </g>

            <!-- Plump Cat Torso & Cream Belly -->
            <path d="M66 105 C62 132 66 156 98 156 C128 156 132 132 126 105 Z" fill="#f3c678" stroke="#6e2219" stroke-width="2.2"/>
            <ellipse cx="98" cy="130" rx="20" ry="21" fill="#fff8ea"/>

            <!-- Postal Blue Uniform Vest Collar & Satchel Strap -->
            <path d="M74 104 L98 122 L122 104" fill="none" stroke="#295896" stroke-width="6" stroke-linecap="round"/>
            <!-- Cross-body Mail Satchel Strap -->
            <path d="M75 104 L122 146" fill="none" stroke="#1e4475" stroke-width="6" stroke-linecap="round"/>
            <circle cx="98" cy="116" r="4.5" fill="#f5d77f" stroke="#7a5310" stroke-width="1.5"/>

            <!-- Postal Blue Mailbag at Cat's Hip -->
            <g transform="translate(52, 126) rotate(-8)">
              <rect x="0" y="0" width="26" height="22" rx="5" fill="#295896" stroke="#142d4f" stroke-width="2"/>
              <path d="M0 7 L13 14 L26 7" fill="#3c75bd" stroke="#142d4f" stroke-width="1.5"/>
              <circle cx="13" cy="12" r="2.5" fill="#f5d77f"/>
            </g>

            <!-- Envelope Carried in Cat's Paws (hidden once placed in front of user) -->
            <g id="cat-held-envelope" transform="translate(75, 110) rotate(4)">
              <rect x="0" y="0" width="54" height="36" rx="4" fill="#fff9ec" stroke="#d4af37" stroke-width="2"/>
              <path d="M2 2 L27 20 L52 2" fill="#f5e1bc" stroke="#d4af37" stroke-width="1.5"/>
              <circle cx="27" cy="19" r="6.5" fill="#b82535" stroke="#f5d77f" stroke-width="1.2"/>
              <path d="M27 16.5 C25.5 15 23.5 16.5 27 20.5 C30.5 16.5 28.5 15 27 16.5 Z" fill="#f5d77f"/>
            </g>

            <!-- Cat Front Paws / Arms -->
            <path d="M68 112 C62 122 68 132 80 128" fill="#f3c678" stroke="#6e2219" stroke-width="2.2" stroke-linecap="round"/>
            <circle cx="80" cy="128" r="6" fill="#fff8ea" stroke="#6e2219" stroke-width="2"/>

            <g class="cat-arm-salute">
              <path d="M124 112 C132 120 128 132 116 128" fill="#f3c678" stroke="#6e2219" stroke-width="2.2" stroke-linecap="round"/>
              <circle cx="116" cy="128" r="6" fill="#fff8ea" stroke="#6e2219" stroke-width="2"/>
            </g>

            <!-- Cat Head & Postman Blue Cap -->
            <g class="cat-head-group">
              <!-- Left & Right Cat Ears -->
              <polygon points="62,74 54,40 84,56" fill="#f3c678" stroke="#6e2219" stroke-width="2.2" stroke-linejoin="round"/>
              <polygon points="64,70 59,47 79,57" fill="#f29b9b"/>
              <polygon points="132,74 140,40 110,56" fill="#f3c678" stroke="#6e2219" stroke-width="2.2" stroke-linejoin="round"/>
              <polygon points="130,70 135,47 115,57" fill="#f29b9b"/>

              <!-- Round Cat Head -->
              <ellipse cx="97" cy="80" rx="36" ry="30" fill="#f3c678" stroke="#6e2219" stroke-width="2.2"/>

              <!-- Cream Muzzle & Rosy Cheeks -->
              <ellipse cx="97" cy="88" rx="22" ry="15" fill="#fff8ea"/>
              <ellipse cx="72" cy="86" rx="6.5" ry="4" fill="#f08080" opacity="0.65"/>
              <ellipse cx="122" cy="86" rx="6.5" ry="4" fill="#f08080" opacity="0.65"/>

              <!-- Expressive Eyes (Open while walking, Happy Arcs when bowing) -->
              <g id="cat-eyes-open">
                <circle cx="82" cy="77" r="5.5" fill="#361512"/>
                <circle cx="80.2" cy="75" r="2" fill="#ffffff"/>
                <circle cx="112" cy="77" r="5.5" fill="#361512"/>
                <circle cx="110.2" cy="75" r="2" fill="#ffffff"/>
              </g>
              <g id="cat-eyes-happy" style="display:none;">
                <path d="M76 78 Q82 71 88 78" fill="none" stroke="#361512" stroke-width="2.8" stroke-linecap="round"/>
                <path d="M106 78 Q112 71 118 78" fill="none" stroke="#361512" stroke-width="2.8" stroke-linecap="round"/>
              </g>

              <!-- Pink Nose & Cute Mouth -->
              <polygon points="94,83 100,83 97,87" fill="#e06377"/>
              <path d="M91 90 Q94 94 97 89 Q100 94 103 90" fill="none" stroke="#6e2219" stroke-width="2" stroke-linecap="round"/>

              <!-- Whiskers -->
              <line x1="64" y1="82" x2="48" y2="79" stroke="#6e2219" stroke-width="1.6" stroke-linecap="round"/>
              <line x1="64" y1="87" x2="46" y2="88" stroke="#6e2219" stroke-width="1.6" stroke-linecap="round"/>
              <line x1="130" y1="82" x2="146" y2="79" stroke="#6e2219" stroke-width="1.6" stroke-linecap="round"/>
              <line x1="130" y1="87" x2="148" y2="88" stroke="#6e2219" stroke-width="1.6" stroke-linecap="round"/>

              <!-- BLUE POSTMAN CAP -->
              <g transform="translate(0, -3)">
                <!-- Cap Visor / Peak -->
                <path d="M68 56 Q99 66 134 55 Q128 46 98 48 Q72 48 68 56 Z" fill="#18365e" stroke="#0f2340" stroke-width="1.8"/>
                <!-- Blue Cap Crown -->
                <path d="M67 52 C64 32 82 24 98 24 C116 24 131 33 128 52 Z" fill="#3c75bd" stroke="#18365e" stroke-width="2"/>
                <!-- Mid Blue Cap Band -->
                <path d="M67 47 Q97 53 128 47 L127 54 Q97 60 68 54 Z" fill="#254f85" stroke="#18365e" stroke-width="1.5"/>
                <!-- Gold Postman Cord & Winged Heart Emblem -->
                <path d="M68 52 Q97 58 127 52" fill="none" stroke="#f5d77f" stroke-width="2.5"/>
                <circle cx="98" cy="41" r="6.5" fill="#f5d77f" stroke="#8c6512" stroke-width="1.5"/>
                <path d="M98 39 C97 37.8 95.2 39 98 42.2 C100.8 39 99 37.8 98 39 Z" fill="#b82535"/>
              </g>
            </g>
          </g>
        </svg>
      </div>

      <!-- Envelope Placed in Front of User -->
      <div class="delivered-envelope-wrap" id="delivered-envelope-wrap">
        <button type="button" class="envelope-touch-button" id="btn-open-envelope" aria-label="Tap the envelope to open">
          <div class="envelope-box" id="envelope-box">
            <!-- Rising Inner Card -->
            <div class="envelope-rising-card">♥</div>

            <!-- Envelope Pocket Flaps -->
            <svg class="envelope-pocket-svg" viewBox="0 0 286 194" preserveAspectRatio="none">
              <polygon points="0,0 143,102 0,194" fill="#f3dfc0" stroke="#d4af37" stroke-width="1.5"/>
              <polygon points="286,0 143,102 286,194" fill="#eed6b1" stroke="#d4af37" stroke-width="1.5"/>
              <polygon points="0,194 143,96 286,194" fill="#faecd2" stroke="#d4af37" stroke-width="2"/>
            </svg>

            <!-- Top Folding Flap -->
            <svg class="envelope-top-flap" viewBox="0 0 286 112" preserveAspectRatio="none">
              <polygon points="0,0 143,106 286,0" fill="#fff6e5" stroke="#d4af37" stroke-width="2.5"/>
              <polygon points="14,4 143,96 272,4" fill="none" stroke="rgba(184, 37, 53, 0.3)" stroke-width="1.2" stroke-dasharray="4 3"/>
            </svg>

            <!-- Gold & Crimson Wax Seal -->
            <div class="wax-seal-badge">♥</div>

            <!-- Envelope Recipient & Sender -->
            <div class="envelope-address-plate">
              <div class="env-for-line" id="env-for-display">For: Luna</div>
              <div class="env-from-line" id="env-from-display">From: Oliver • Special Cat Post</div>
            </div>
          </div>
        </button>

        <div class="tap-prompt-pill" id="tap-envelope-prompt">
          ✦ Tap the envelope to open ✦
        </div>
      </div>
    </div>
  </section>

  <!-- =========================================================
       VIEW 3: UNFOLDED POP-UP SCENE & HANDWRITTEN LETTER
       ========================================================= -->
  <section id="view-letter" class="stage-view">
    <div id="opened-letter-sheet" class="paper-sheet paper-style-royal opened-letter-card">
      <!-- 3D Paper Pop-Up Diorama: Hearts, Flowers & Two Cats Sitting Together Under the Moon -->
      <div class="popup-diorama-stage" id="popup-diorama" title="Tap the pop-up scene for extra hearts">
        <div class="popup-crease-vertical"></div>
        <div class="popup-paper-floor"></div>
        <div class="popup-tap-hint">Tap scene ♥</div>

        <!-- LAYER 1: Cut-Paper Scalloped Theater Arch & Starlit Sky -->
        <div class="popup-layer layer-arch">
          <svg viewBox="0 0 400 235" width="100%" height="100%" preserveAspectRatio="xMidYMid slice">
            <!-- Twinkling Paper Stars -->
            <g fill="#f5d77f" opacity="0.85">
              <circle cx="65" cy="45" r="1.8"/>
              <circle cx="115" cy="28" r="2.2"/>
              <circle cx="285" cy="34" r="2"/>
              <circle cx="335" cy="52" r="1.6"/>
              <circle cx="155" cy="60" r="1.5"/>
              <circle cx="250" cy="68" r="1.7"/>
              <path d="M90 52 L92 58 L98 60 L92 62 L90 68 L88 62 L82 60 L88 58 Z" fill="#fff3c4"/>
              <path d="M312 38 L313.5 43 L318.5 44.5 L313.5 46 L312 51 L310.5 46 L305.5 44.5 L310.5 43 Z" fill="#fff3c4"/>
            </g>
            <!-- Outer Cut-Paper Scalloped Arch Wings -->
            <path d="M0 0 L400 0 L400 210 L355 210 C362 125 320 22 200 22 C80 22 38 125 45 210 L0 210 Z"
                  fill="#871926" stroke="#f5d77f" stroke-width="2"
                  style="filter: drop-shadow(0 4px 8px rgba(0,0,0,0.45));"/>
            <path d="M18 205 C14 112 72 12 200 12 C328 12 386 112 382 205"
                  fill="none" stroke="#d4af37" stroke-width="1.5" stroke-dasharray="5 4"/>
          </svg>
        </div>

        <!-- LAYER 2: Glowing Cut-Paper Crescent & Full Halo Moon -->
        <div class="popup-layer layer-moon">
          <svg class="bob-gentle" viewBox="0 0 400 235" width="100%" height="100%">
            <defs>
              <radialGradient id="moonGlow" cx="50%" cy="50%" r="50%">
                <stop offset="0%" stop-color="#fff8d6" stop-opacity="0.95"/>
                <stop offset="55%" stop-color="#f5d77f" stop-opacity="0.35"/>
                <stop offset="100%" stop-color="#f5d77f" stop-opacity="0"/>
              </radialGradient>
            </defs>
            <!-- Paper suspension thread -->
            <line x1="200" y1="0" x2="200" y2="42" stroke="#d4af37" stroke-width="1.2"/>
            <!-- Soft Golden Halo -->
            <circle cx="200" cy="70" r="52" fill="url(#moonGlow)"/>
            <!-- Paper Full Moon Disc -->
            <circle cx="200" cy="70" r="29" fill="#fff6d6" stroke="#e2b849" stroke-width="1.8"
                    style="filter: drop-shadow(0 3px 6px rgba(0,0,0,0.35));"/>
            <!-- Cut-Paper Embossed Crescent Relief -->
            <path d="M192 44 A25 25 0 1 0 222 84 A21 21 0 1 1 192 44 Z" fill="#f5d273" opacity="0.65"/>
          </svg>
        </div>

        <!-- LAYER 3: Pop-Up Paper Flowers & Golden Foliage (Left & Right Bouquets) -->
        <div class="popup-layer layer-flowers">
          <svg viewBox="0 0 400 235" width="100%" height="100%">
            <!-- Left Bouquet of Paper Roses & Blossoms -->
            <g style="filter: drop-shadow(2px 3px 4px rgba(0,0,0,0.35));">
              <!-- Gold & Green Paper Leaves -->
              <path d="M56 196 Q25 162 42 136 Q65 154 62 194 Z" fill="#d4af37" stroke="#fff5d6" stroke-width="1.2"/>
              <path d="M72 198 Q45 148 75 124 Q94 152 78 196 Z" fill="#a82433" stroke="#f5d77f" stroke-width="1.2"/>
              <path d="M88 198 Q96 155 118 148 Q112 178 92 198 Z" fill="#e5c158" stroke="#7a5411" stroke-width="1"/>
              <!-- Large Paper Rose Left -->
              <circle cx="52" cy="146" r="18" fill="#c92a3b" stroke="#fff5e4" stroke-width="1.8"/>
              <circle cx="52" cy="146" r="11" fill="#e34c5c" stroke="#fff5e4" stroke-width="1.4"/>
              <circle cx="52" cy="146" r="5" fill="#f5d77f"/>
              <!-- Cream Paper Blossom Left -->
              <circle cx="82" cy="136" r="14" fill="#fff5e0" stroke="#d4af37" stroke-width="1.6"/>
              <circle cx="82" cy="136" r="7.5" fill="#f29b9b"/>
              <circle cx="82" cy="136" r="3.5" fill="#b82535"/>
              <!-- Small Bud -->
              <circle cx="104" cy="164" r="10" fill="#d93848" stroke="#fff5e0" stroke-width="1.4"/>
              <circle cx="104" cy="164" r="4" fill="#f5d77f"/>
            </g>

            <!-- Right Bouquet of Paper Roses & Blossoms -->
            <g style="filter: drop-shadow(-2px 3px 4px rgba(0,0,0,0.35));">
              <path d="M344 196 Q375 162 358 136 Q335 154 338 194 Z" fill="#d4af37" stroke="#fff5d6" stroke-width="1.2"/>
              <path d="M328 198 Q355 148 325 124 Q306 152 322 196 Z" fill="#a82433" stroke="#f5d77f" stroke-width="1.2"/>
              <path d="M312 198 Q304 155 282 148 Q288 178 308 198 Z" fill="#e5c158" stroke="#7a5411" stroke-width="1"/>
              <!-- Large Paper Rose Right -->
              <circle cx="348" cy="146" r="18" fill="#c92a3b" stroke="#fff5e4" stroke-width="1.8"/>
              <circle cx="348" cy="146" r="11" fill="#e34c5c" stroke="#fff5e4" stroke-width="1.4"/>
              <circle cx="348" cy="146" r="5" fill="#f5d77f"/>
              <!-- Cream Paper Blossom Right -->
              <circle cx="318" cy="136" r="14" fill="#fff5e0" stroke="#d4af37" stroke-width="1.6"/>
              <circle cx="318" cy="136" r="7.5" fill="#f29b9b"/>
              <circle cx="318" cy="136" r="3.5" fill="#b82535"/>
              <!-- Small Bud -->
              <circle cx="296" cy="164" r="10" fill="#d93848" stroke="#fff5e0" stroke-width="1.4"/>
              <circle cx="296" cy="164" r="4" fill="#f5d77f"/>
            </g>
          </svg>
        </div>

        <!-- LAYER 4: Two Cats Sitting Together Under the Moon -->
        <div class="popup-layer layer-cats">
          <svg viewBox="0 0 400 235" width="100%" height="100%">
            <g style="filter: drop-shadow(0 4px 6px rgba(0,0,0,0.45));">
              <!-- Cut-Paper Garden Hill / Pedestal Bench with V-Fold Tab -->
              <path d="M116 205 Q200 176 284 205 L296 216 L104 216 Z" fill="#fff5e0" stroke="#d4af37" stroke-width="2"/>
              <!-- Little Paper Fold Tabs at the base -->
              <rect x="148" y="204" width="22" height="10" fill="#f2dfc0" stroke="#c99e32" stroke-width="1.2"/>
              <rect x="230" y="204" width="22" height="10" fill="#f2dfc0" stroke="#c99e32" stroke-width="1.2"/>

              <!-- LEFT CAT (Warm Cream & Gold Kitty leaning right) -->
              <g>
                <!-- Body -->
                <path d="M152 196 C148 164 160 144 178 144 C194 144 198 166 196 196 Z"
                      fill="#fff6e3" stroke="#85581A" stroke-width="2"/>
                <!-- Head tilted lovingly toward right cat -->
                <circle cx="180" cy="128" r="17" fill="#fff6e3" stroke="#85581A" stroke-width="2"/>
                <!-- Ears -->
                <polygon points="164,120 161,102 176,112" fill="#fff6e3" stroke="#85581A" stroke-width="1.8" stroke-linejoin="round"/>
                <polygon points="166,118 164,106 174,113" fill="#f29b9b"/>
                <polygon points="183,114 193,100 196,118" fill="#fff6e3" stroke="#85581A" stroke-width="1.8" stroke-linejoin="round"/>
                <!-- Crimson Ribbon Collar -->
                <path d="M167 142 Q180 147 193 142" fill="none" stroke="#c92a3b" stroke-width="3.5" stroke-linecap="round"/>
                <circle cx="180" cy="145" r="3" fill="#f5d77f"/>
              </g>

              <!-- RIGHT CAT (Warm Ginger-Russet Kitty leaning left) -->
              <g>
                <!-- Body -->
                <path d="M198 196 C198 166 204 146 220 146 C238 146 248 166 244 196 Z"
                      fill="#edb268" stroke="#6e2219" stroke-width="2"/>
                <!-- Head tilted lovingly against left cat -->
                <circle cx="215" cy="131" r="16.5" fill="#edb268" stroke="#6e2219" stroke-width="2"/>
                <!-- Ears -->
                <polygon points="201,120 204,103 216,116" fill="#edb268" stroke="#6e2219" stroke-width="1.8" stroke-linejoin="round"/>
                <polygon points="219,116 233,104 231,123" fill="#edb268" stroke="#6e2219" stroke-width="1.8" stroke-linejoin="round"/>
                <polygon points="221,116 230,108 229,121" fill="#f29b9b"/>
                <!-- Gold Bow Collar -->
                <path d="M203 145 Q216 150 229 145" fill="none" stroke="#295896" stroke-width="3.5" stroke-linecap="round"/>
                <circle cx="216" cy="148" r="3" fill="#f5d77f"/>
              </g>

              <!-- INTERTWINED TAILS FORMING A HEART SHAPE -->
              <path d="M156 192 C136 184 134 156 154 152 C168 149 182 162 198 178"
                    fill="none" stroke="#fff6e3" stroke-width="7" stroke-linecap="round"/>
              <path d="M156 192 C136 184 134 156 154 152 C168 149 182 162 198 178"
                    fill="none" stroke="#85581A" stroke-width="1.6" stroke-linecap="round"/>

              <path d="M240 192 C260 184 262 156 242 152 C228 149 214 162 198 178"
                    fill="none" stroke="#edb268" stroke-width="7" stroke-linecap="round"/>
              <path d="M240 192 C260 184 262 156 242 152 C228 149 214 162 198 178"
                    fill="none" stroke="#6e2219" stroke-width="1.6" stroke-linecap="round"/>

              <!-- Tiny Flowers on the Hill -->
              <circle cx="140" cy="202" r="4" fill="#e34c5c"/>
              <circle cx="140" cy="202" r="1.8" fill="#f5d77f"/>
              <circle cx="260" cy="202" r="4" fill="#e34c5c"/>
              <circle cx="260" cy="202" r="1.8" fill="#f5d77f"/>
            </g>
          </svg>
        </div>

        <!-- LAYER 5: Pop-Up Paper Hearts on Accordion Springs -->
        <div class="popup-layer layer-hearts">
          <svg class="bob-hearts" viewBox="0 0 400 235" width="100%" height="100%">
            <!-- Center Heart between the Two Cats under the Moon -->
            <g transform="translate(198, 102)" style="filter: drop-shadow(0 2px 4px rgba(0,0,0,0.35));">
              <path d="M0 -4 C-6 -12 -16 -6 0 8 C16 -6 6 -12 0 -4 Z" fill="#e03143" stroke="#fff6e3" stroke-width="1.5"/>
            </g>
            <!-- Left Floating Cut-Paper Heart -->
            <g transform="translate(126, 86) rotate(-14)" style="filter: drop-shadow(0 3px 5px rgba(0,0,0,0.35));">
              <line x1="0" y1="10" x2="8" y2="38" stroke="#f5d77f" stroke-width="1" stroke-dasharray="2 2"/>
              <path d="M0 -6 C-9 -16 -22 -8 0 12 C22 -8 9 -16 0 -6 Z" fill="#c92a3b" stroke="#f5d77f" stroke-width="1.6"/>
            </g>
            <!-- Right Floating Cut-Paper Heart -->
            <g transform="translate(274, 84) rotate(14)" style="filter: drop-shadow(0 3px 5px rgba(0,0,0,0.35));">
              <line x1="0" y1="10" x2="-8" y2="38" stroke="#f5d77f" stroke-width="1" stroke-dasharray="2 2"/>
              <path d="M0 -6 C-9 -16 -22 -8 0 12 C22 -8 9 -16 0 -6 Z" fill="#e34c5c" stroke="#fff6e3" stroke-width="1.6"/>
            </g>
            <!-- High Small Gold Heart -->
            <g transform="translate(154, 48) rotate(-8)">
              <path d="M0 -4 C-5 -10 -12 -5 0 6 C12 -5 5 -10 0 -4 Z" fill="#f5d77f" stroke="#fff" stroke-width="1"/>
            </g>
            <g transform="translate(248, 50) rotate(10)">
              <path d="M0 -4 C-5 -10 -12 -5 0 6 C12 -5 5 -10 0 -4 Z" fill="#f5d77f" stroke="#fff" stroke-width="1"/>
            </g>
          </svg>
        </div>
      </div>

      <!-- Handwritten Letter Sheet Area -->
      <div class="letter-writing-sheet">
        <div>
          <div class="salutation-line" id="letter-salutation">Dearest Luna,</div>

          <div class="handwriting-body-wrap" id="handwriting-wrap">
            <div class="handwriting-text" id="handwriting-text"></div>

            <!-- Animated Fountain Pen Nib -->
            <svg id="fountain-pen-nib" viewBox="0 0 40 40">
              <g transform="rotate(-35 20 20)">
                <path d="M18 38 L13 22 L20 2 L27 22 Z" fill="#f5d77f" stroke="#6e4d0b" stroke-width="1.5"/>
                <line x1="20" y1="38" x2="20" y2="20" stroke="#6e4d0b" stroke-width="1.3"/>
                <circle cx="20" cy="20" r="2" fill="#821320"/>
                <rect x="14" y="0" width="12" height="7" rx="2" fill="#9e1b28" stroke="#f5d77f" stroke-width="1"/>
              </g>
            </svg>
          </div>
        </div>

        <div class="signoff-block" id="letter-signoff">
          <div class="signoff-label">With all my love,</div>
          <div class="signoff-name" id="letter-from-name">Oliver</div>
          <svg class="flourish-svg" viewBox="0 0 140 22">
            <path class="flourish-path" d="M6 12 Q45 2 85 12 T134 9 Q115 19 88 14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- Bottom Controls: Live Paper Style Switcher + Replay Delivery + Edit -->
    <div class="opened-controls-panel">
      <div class="style-buttons-grid" id="letter-style-grid">
        <button type="button" class="style-btn selected" data-style="royal">
          <span class="style-swatch-dot swatch-royal"></span>
          <span>Cream &amp; Gold</span>
        </button>
        <button type="button" class="style-btn" data-style="rose">
          <span class="style-swatch-dot swatch-rose"></span>
          <span>Velvet Rose</span>
        </button>
        <button type="button" class="style-btn" data-style="gilded">
          <span class="style-swatch-dot swatch-gilded"></span>
          <span>Starlit Gold</span>
        </button>
      </div>

      <div class="action-buttons-row">
        <button type="button" id="btn-replay-delivery" class="replay-btn">
          <span>🐾</span>
          <span>Replay Delivery</span>
        </button>
        <button type="button" id="btn-edit-letter" class="secondary-btn">
          <span>✎</span>
          <span>Edit Letter</span>
        </button>
      </div>
    </div>
  </section>
</div>

<script>
(function() {
  'use strict';

  /* =========================================================
     1. SOFT SOUNDS SYNTHESIZED IN CODE (Web Audio API)
     ========================================================= */
  const SoundEngine = {
    ctx: null,
    muted: false,

    init() {
      if (this.ctx) {
        if (this.ctx.state === 'suspended') {
          this.ctx.resume().catch(() => {});
        }
        return;
      }
      try {
        const AudioCtx = window.AudioContext || window.webkitAudioContext;
        if (AudioCtx) {
          this.ctx = new AudioCtx();
        }
      } catch (e) {}
    },

    canPlay() {
      if (this.muted) return false;
      this.init();
      return !!(this.ctx && this.ctx.state === 'running');
    },

    /* Soft harp / music-box pluck */
    playNote(freq, duration = 0.45, volume = 0.08, type = 'sine', delay = 0) {
      if (!this.canPlay()) return;
      try {
        const now = this.ctx.currentTime + delay;
        const osc = this.ctx.createOscillator();
        const gain = this.ctx.createGain();
        osc.type = type;
        osc.frequency.setValueAtTime(freq, now);

        gain.gain.setValueAtTime(0.0001, now);
        gain.gain.linearRampToValueAtTime(volume, now + 0.02);
        gain.gain.exponentialRampToValueAtTime(0.0001, now + duration);

        osc.connect(gain);
        gain.connect(this.ctx.destination);
        osc.start(now);
        osc.stop(now + duration + 0.02);
      } catch (e) {}
    },

    /* Soft tap on buttons or style cards */
    playTap() {
      this.playNote(523.25, 0.18, 0.055, 'triangle', 0);
      this.playNote(659.25, 0.22, 0.04, 'sine', 0.03);
    },

    /* Romantic ascending chime when pressing Send */
    playSend() {
      const notes = [392.00, 493.88, 587.33, 783.99];
      notes.forEach((n, idx) => {
        this.playNote(n, 0.5, 0.06, 'sine', idx * 0.07);
      });
    },

    /* Soft padded paw step + tiny collar bell */
    playPawStep(stepIndex) {
      if (!this.canPlay()) return;
      try {
        const now = this.ctx.currentTime;
        const osc = this.ctx.createOscillator();
        const gain = this.ctx.createGain();
        osc.type = 'sine';
        const baseFreq = stepIndex % 2 === 0 ? 150 : 175;
        osc.frequency.setValueAtTime(baseFreq, now);
        osc.frequency.exponentialRampToValueAtTime(65, now + 0.07);

        gain.gain.setValueAtTime(0.04, now);
        gain.gain.exponentialRampToValueAtTime(0.001, now + 0.08);
        osc.connect(gain);
        gain.connect(this.ctx.destination);
        osc.start(now);
        osc.stop(now + 0.09);

        // Soft tiny bell overtone
        this.playNote(stepIndex % 2 === 0 ? 1318.5 : 1567.98, 0.14, 0.015, 'sine', 0.01);
      } catch (e) {}
    },

    /* Sweet synthesized cat postman "Meow~ ♪" */
    playCatMeow() {
      if (!this.canPlay()) return;
      try {
        const now = this.ctx.currentTime;
        const osc = this.ctx.createOscillator();
        const filter = this.ctx.createBiquadFilter();
        const gain = this.ctx.createGain();

        osc.type = 'triangle';
        osc.frequency.setValueAtTime(480, now);
        osc.frequency.linearRampToValueAtTime(740, now + 0.14);
        osc.frequency.exponentialRampToValueAtTime(430, now + 0.45);

        filter.type = 'bandpass';
        filter.frequency.setValueAtTime(1100, now);
        filter.Q.setValueAtTime(2.5, now);

        gain.gain.setValueAtTime(0.001, now);
        gain.gain.linearRampToValueAtTime(0.075, now + 0.05);
        gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.48);

        osc.connect(filter);
        filter.connect(gain);
        gain.connect(this.ctx.destination);

        osc.start(now);
        osc.stop(now + 0.5);
      } catch (e) {}
    },

    /* Paper rustle + warm music-box chord when envelope opens and pop-up unfolds */
    playEnvelopeOpen() {
      if (!this.canPlay()) return;
      try {
        const now = this.ctx.currentTime;
        // Soft paper rustle via filtered noise buffer
        const bufferSize = this.ctx.sampleRate * 0.28;
        const buffer = this.ctx.createBuffer(1, bufferSize, this.ctx.sampleRate);
        const data = buffer.getChannelData(0);
        for (let i = 0; i < bufferSize; i++) {
          data[i] = (Math.random() * 2 - 1) * Math.sin((i / bufferSize) * Math.PI);
        }
        const noise = this.ctx.createBufferSource();
        noise.buffer = buffer;

        const filter = this.ctx.createBiquadFilter();
        filter.type = 'bandpass';
        filter.frequency.setValueAtTime(1200, now);
        filter.Q.setValueAtTime(1.5, now);

        const gain = this.ctx.createGain();
        gain.gain.setValueAtTime(0.05, now);
        gain.gain.exponentialRampToValueAtTime(0.001, now + 0.28);

        noise.connect(filter);
        filter.connect(gain);
        gain.connect(this.ctx.destination);
        noise.start(now);

        // Warm music-box chord as pop-up unfolds
        const chord = [349.23, 440.00, 523.25, 659.25, 783.99];
        chord.forEach((freq, i) => {
          this.playNote(freq, 0.9, 0.045, 'sine', 0.12 + i * 0.08);
        });
      } catch (e) {}
    },

    /* Ultra-gentle pen stroke & music-box note while writing letter by letter */
    playPenTick(charIndex) {
      if (!this.canPlay()) return;
      const scale = [523.25, 587.33, 659.25, 783.99, 880.00, 1046.50];
      if (charIndex % 3 === 0) {
        const note = scale[(charIndex / 3) % scale.length];
        this.playNote(note, 0.22, 0.022, 'sine', 0);
      }
    },

    /* Warm cadence when signature flourish completes */
    playFlourishComplete() {
      const notes = [523.25, 659.25, 783.99, 1046.50];
      notes.forEach((n, idx) => {
        this.playNote(n, 0.75, 0.045, 'sine', idx * 0.09);
      });
    }
  };

  /* =========================================================
     2. STATE & STORAGE (Wrapped in try/catch for sandboxed iframe)
     ========================================================= */
  const PRESET_MESSAGES = [
    "Every moment with you feels like moonlight and warm tea. You are my favorite person in the whole world.",
    "Like two cosy cats sitting together under a golden moon, my happiest place will always be right next to you.",
    "I folded all my love into this little envelope just to see you smile. Forever and always yours."
  ];

  const state = {
    from: 'Oliver',
    forWho: 'Luna',
    message: PRESET_MESSAGES[0],
    paperStyle: 'royal', // 'royal' | 'rose' | 'gilded'
    stage: 'compose',    // 'compose' | 'delivery' | 'letter'
    deliveryTimers: [],
    writingTimer: null,
    demoActive: false,
    demoTimers: []
  };

  function saveState() {
    try {
      localStorage.setItem('purrfect_love_letter_v1', JSON.stringify({
        from: state.from,
        forWho: state.forWho,
        message: state.message,
        paperStyle: state.paperStyle
      }));
    } catch (e) {}
  }

  function loadState() {
    try {
      const raw = localStorage.getItem('purrfect_love_letter_v1');
      if (raw) {
        const parsed = JSON.parse(raw);
        if (parsed.from) state.from = parsed.from;
        if (parsed.forWho) state.forWho = parsed.forWho;
        if (parsed.message) state.message = parsed.message;
        if (['royal', 'rose', 'gilded'].includes(parsed.paperStyle)) {
          state.paperStyle = parsed.paperStyle;
        }
      }
    } catch (e) {}
  }

  /* =========================================================
     3. DOM REFERENCES
     ========================================================= */
  const viewCompose = document.getElementById('view-compose');
  const viewDelivery = document.getElementById('view-delivery');
  const viewLetter = document.getElementById('view-letter');

  const composePaper = document.getElementById('compose-paper');
  const openedLetterSheet = document.getElementById('opened-letter-sheet');

  const inputFrom = document.getElementById('input-from');
  const inputFor = document.getElementById('input-for');
  const inputMessage = document.getElementById('input-message');

  const btnSendLetter = document.getElementById('btn-send-letter');
  const catPostman = document.getElementById('cat-postman');
  const catSpeech = document.getElementById('cat-speech');
  const catHeldEnvelope = document.getElementById('cat-held-envelope');
  const catEyesOpen = document.getElementById('cat-eyes-open');
  const catEyesHappy = document.getElementById('cat-eyes-happy');
  const pawPrints = document.querySelectorAll('#paw-trail .paw-print');

  const deliveredEnvelopeWrap = document.getElementById('delivered-envelope-wrap');
  const btnOpenEnvelope = document.getElementById('btn-open-envelope');
  const tapEnvelopePrompt = document.getElementById('tap-envelope-prompt');
  const envForDisplay = document.getElementById('env-for-display');
  const envFromDisplay = document.getElementById('env-from-display');

  const popupDiorama = document.getElementById('popup-diorama');
  const letterSalutation = document.getElementById('letter-salutation');
  const handwritingText = document.getElementById('handwriting-text');
  const fountainPenNib = document.getElementById('fountain-pen-nib');
  const letterSignoff = document.getElementById('letter-signoff');
  const letterFromName = document.getElementById('letter-from-name');

  const btnReplayDelivery = document.getElementById('btn-replay-delivery');
  const btnEditLetter = document.getElementById('btn-edit-letter');
  const soundToggleBtn = document.getElementById('sound-toggle-btn');
  const soundIcon = document.getElementById('sound-icon');
  const soundLabel = document.getElementById('sound-label');
  const demoBanner = document.getElementById('demo-banner');

  /* =========================================================
     4. PAPER STYLE SWITCHING & STAGE NAVIGATION
     ========================================================= */
  function applyPaperStyle(styleName, playSound = true) {
    if (!['royal', 'rose', 'gilded'].includes(styleName)) return;
    state.paperStyle = styleName;

    [composePaper, openedLetterSheet].forEach(sheet => {
      sheet.classList.remove('paper-style-royal', 'paper-style-rose', 'paper-style-gilded');
      sheet.classList.add('paper-style-' + styleName);
    });

    document.querySelectorAll('.style-btn').forEach(btn => {
      btn.classList.toggle('selected', btn.getAttribute('data-style') === styleName);
    });

    if (playSound) SoundEngine.playTap();
    saveState();
  }

  function showStage(stageName) {
    state.stage = stageName;
    viewCompose.classList.toggle('active', stageName === 'compose');
    viewDelivery.classList.toggle('active', stageName === 'delivery');
    viewLetter.classList.toggle('active', stageName === 'letter');
  }

  function clearDeliveryTimers() {
    state.deliveryTimers.forEach(id => clearTimeout(id));
    state.deliveryTimers = [];
  }

  function clearWritingTimer() {
    if (state.writingTimer) {
      clearTimeout(state.writingTimer);
      state.writingTimer = null;
    }
  }

  /* =========================================================
     5. CAT POSTMAN DELIVERY CHOREOGRAPHY
     ========================================================= */
  function startDeliverySequence() {
    clearDeliveryTimers();
    clearWritingTimer();

    // Sync current inputs
    state.from = (inputFrom.value || '').trim() || 'Oliver';
    state.forWho = (inputFor.value || '').trim() || 'Luna';
    state.message = (inputMessage.value || '').trim() || PRESET_MESSAGES[0];
    saveState();

    // Update envelope address labels
    envForDisplay.textContent = 'For: ' + state.forWho;
    envFromDisplay.textContent = 'From: ' + state.from + ' • Special Cat Post';

    // Reset Delivery Stage states
    deliveredEnvelopeWrap.classList.remove('presented');
    btnOpenEnvelope.classList.remove('opening');
    popupDiorama.classList.remove('unfolded');
    catSpeech.classList.remove('visible');
    catPostman.classList.remove('walking', 'bowing', 'parked');
    catHeldEnvelope.style.display = 'block';
    catEyesOpen.style.display = 'block';
    catEyesHappy.style.display = 'none';
    pawPrints.forEach(p => p.classList.remove('visible'));

    // Position Cat Postman off-screen left
    catPostman.style.transition = 'none';
    catPostman.style.transform = 'translateX(-280px)';

    showStage('delivery');
    SoundEngine.playSend();

    // Force reflow before walking animation
    void catPostman.offsetWidth;

    // Step 1: Cat Postman trots in from left to center (0.08s -> 2.3s)
    const tWalkStart = setTimeout(() => {
      catPostman.classList.add('walking');
      catPostman.style.transition = 'transform 2.2s cubic-bezier(0.25, 0.8, 0.35, 1)';
      catPostman.style.transform = 'translateX(0px)';
    }, 60);
    state.deliveryTimers.push(tWalkStart);

    // Reveal paw prints & play soft paw steps along the walk
    const stepTimes = [320, 720, 1120, 1520, 1900];
    stepTimes.forEach((ms, idx) => {
      const tid = setTimeout(() => {
        SoundEngine.playPawStep(idx);
        if (pawPrints[idx]) pawPrints[idx].classList.add('visible');
      }, ms);
      state.deliveryTimers.push(tid);
    });

    // Step 2: Cat arrives at center, tips blue cap, smiles & meows (2.3s)
    const tArrive = setTimeout(() => {
      catPostman.classList.remove('walking');
      catPostman.classList.add('bowing');
      catEyesOpen.style.display = 'none';
      catEyesHappy.style.display = 'block';
      catSpeech.textContent = 'For ' + state.forWho + '! ♪';
      catSpeech.classList.add('visible');
      SoundEngine.playCatMeow();
    }, 2280);
    state.deliveryTimers.push(tArrive);

    // Step 3: Cat leaves envelope in front of user & steps aside proudly (3.05s)
    const tPresent = setTimeout(() => {
      catHeldEnvelope.style.display = 'none';
      catPostman.classList.remove('bowing');
      catPostman.classList.add('parked');
      deliveredEnvelopeWrap.classList.add('presented');
      SoundEngine.playNote(659.25, 0.35, 0.05, 'sine', 0);
    }, 3050);
    state.deliveryTimers.push(tPresent);
  }

  /* =========================================================
     6. ENVELOPE OPENING, 3D POP-UP UNFOLD & HANDWRITING
     ========================================================= */
  let isOpeningEnvelope = false;

  function openEnvelopeAndUnfold() {
    if (isOpeningEnvelope) return;
    isOpeningEnvelope = true;
    clearDeliveryTimers();

    btnOpenEnvelope.classList.add('opening');
    SoundEngine.playEnvelopeOpen();

    const tOpen = setTimeout(() => {
      isOpeningEnvelope = false;
      showOpenedLetterScene();
    }, 680);
    state.deliveryTimers.push(tOpen);
  }

  function showOpenedLetterScene() {
    clearWritingTimer();

    // Populate salutation & sender
    letterSalutation.textContent = 'Dearest ' + state.forWho + ',';
    letterFromName.textContent = state.from;

    // Reset pop-up diorama & handwriting area
    popupDiorama.classList.remove('unfolded');
    letterSignoff.classList.remove('visible');
    handwritingText.innerHTML = '';
    fountainPenNib.classList.remove('writing');

    showStage('letter');

    // Trigger 3D Paper Pop-Up Unfold
    const tUnfold = setTimeout(() => {
      popupDiorama.classList.add('unfolded');
    }, 80);
    state.deliveryTimers.push(tUnfold);

    // Prepare handwritten characters
    const chars = Array.from(state.message);
    const charSpans = [];

    chars.forEach((ch) => {
      const span = document.createElement('span');
      if (ch === ' ') {
        span.className = 'ink-char space-char';
        span.textContent = ' ';
      } else if (ch === '\n') {
        const br = document.createElement('br');
        handwritingText.appendChild(br);
        return;
      } else {
        span.className = 'ink-char';
        // Subtle organic handwriting jitter
        const jitterY = ((Math.random() - 0.5) * 1.4).toFixed(2) + 'px';
        const rot = ((Math.random() - 0.5) * 3.2).toFixed(2) + 'deg';
        span.style.setProperty('--jy', jitterY);
        span.style.setProperty('--rot', rot);
        span.textContent = ch;
      }
      handwritingText.appendChild(span);
      charSpans.push({ span, ch });
    });

    // Start writing letter by letter as pop-up finishes unfolding
    let idx = 0;
    const startWritingDelay = setTimeout(() => {
      fountainPenNib.classList.add('writing');

      function writeNextChar() {
        if (idx >= charSpans.length) {
          fountainPenNib.classList.remove('writing');
          letterSignoff.classList.add('visible');
          SoundEngine.playFlourishComplete();
          return;
        }

        const item = charSpans[idx];
        item.span.classList.add('inked');

        // Position fountain pen nib right at the character being written
        if (item.ch !== ' ') {
          const wrapRect = document.getElementById('handwriting-wrap').getBoundingClientRect();
          const charRect = item.span.getBoundingClientRect();
          if (wrapRect.width > 0 && charRect.width > 0) {
            const leftPos = (charRect.right - wrapRect.left - 4);
            const topPos = (charRect.top - wrapRect.top - 22);
            fountainPenNib.style.left = Math.max(0, leftPos) + 'px';
            fountainPenNib.style.top = Math.max(-12, topPos) + 'px';
          }
          SoundEngine.playPenTick(idx);
        }

        idx++;
        let delay = 42;
        if (item.ch === '.' || item.ch === '!' || item.ch === '?') delay = 150;
        else if (item.ch === ',') delay = 95;
        else if (item.ch === ' ') delay = 28;

        state.writingTimer = setTimeout(writeNextChar, delay);
      }

      writeNextChar();
    }, 620);

    state.deliveryTimers.push(startWritingDelay);
  }

  /* Interactive Pop-Up Scene Tap: Spawn paper hearts & sweet chord */
  function spawnPopupHearts(clientX, clientY) {
    const rect = popupDiorama.getBoundingClientRect();
    const baseX = clientX ? (clientX - rect.left) : (rect.width / 2);
    const baseY = clientY ? (clientY - rect.top) : (rect.height * 0.55);

    const symbols = ['♥', '✦', '♥', '❀'];
    const colors = ['#ff4d63', '#f5d77f', '#fff0d4', '#e34c5c'];

    for (let i = 0; i < 4; i++) {
      const el = document.createElement('span');
      el.className = 'pop-burst-heart';
      el.textContent = symbols[i % symbols.length];
      el.style.color = colors[i % colors.length];
      el.style.left = (baseX + (Math.random() - 0.5) * 64) + 'px';
      el.style.top = (baseY + (Math.random() - 0.5) * 24) + 'px';
      popupDiorama.appendChild(el);
      setTimeout(() => el.remove(), 1150);
    }

    SoundEngine.playNote(587.33, 0.35, 0.045, 'sine', 0);
    SoundEngine.playNote(880.00, 0.45, 0.04, 'sine', 0.07);
  }

  /* =========================================================
     7. HANDS-FREE 20-SECOND #demo LOOP
     ========================================================= */
  function clearDemoTimers() {
    state.demoTimers.forEach(id => clearTimeout(id));
    state.demoTimers = [];
  }

  function stopDemoMode() {
    if (!state.demoActive) return;
    state.demoActive = false;
    clearDemoTimers();
    demoBanner.classList.remove('visible');
    btnSendLetter.classList.remove('pressed');
  }

  function scheduleDemoStep(ms, fn) {
    const id = setTimeout(() => {
      if (!state.demoActive) return;
      fn();
    }, ms);
    state.demoTimers.push(id);
  }

  function runDemoCycle() {
    if (!state.demoActive) return;
    clearDemoTimers();
    clearDeliveryTimers();
    clearWritingTimer();

    // 0.0s: Show Compose View & populate romantic demo text
    showStage('compose');
    applyPaperStyle('royal', false);
    inputFrom.value = 'Milo';
    inputFor.value = 'Cleo';
    const demoMsg = "Meet me under the golden moon tonight. You make my heart purr forever!";
    inputMessage.value = '';

    // Type message smoothly during first 1.6s
    const chars = Array.from(demoMsg);
    chars.forEach((ch, i) => {
      scheduleDemoStep(120 + i * 20, () => {
        inputMessage.value += ch;
      });
    });

    // 1.5s & 2.4s: Showcase paper styles on Compose Card
    scheduleDemoStep(1550, () => applyPaperStyle('rose', true));
    scheduleDemoStep(2450, () => applyPaperStyle('gilded', true));
    scheduleDemoStep(3150, () => applyPaperStyle('royal', true));

    // 3.5s: Press Send button -> Cat Postman Delivery starts
    scheduleDemoStep(3500, () => {
      btnSendLetter.classList.add('pressed');
    });
    scheduleDemoStep(3750, () => {
      btnSendLetter.classList.remove('pressed');
      startDeliverySequence();
    });

    // 8.2s: Tap the delivered envelope to open it & unfold the pop-up scene
    scheduleDemoStep(8200, () => {
      openEnvelopeAndUnfold();
    });

    // 13.8s: Tap the pop-up scene for extra floating paper hearts
    scheduleDemoStep(13800, () => {
      spawnPopupHearts();
    });

    // 15.6s & 17.6s: Showcase the 3 paper styles on the opened pop-up letter
    scheduleDemoStep(15600, () => {
      applyPaperStyle('rose', true);
      spawnPopupHearts();
    });
    scheduleDemoStep(17600, () => {
      applyPaperStyle('gilded', true);
    });

    // 20.0s: Loop seamlessly
    scheduleDemoStep(20000, () => {
      runDemoCycle();
    });
  }

  function checkAndStartDemoMode() {
    if (window.location.hash === '#demo' || window.location.href.endsWith('#demo')) {
      state.demoActive = true;
      demoBanner.classList.add('visible');
      runDemoCycle();
    }
  }

  /* Any real user touch / pointer / key ends #demo immediately */
  function onFirstRealUserInteraction(e) {
    if (e && e.isTrusted === false) return;
    SoundEngine.init();
    if (state.demoActive) {
      stopDemoMode();
    }
  }

  ['pointerdown', 'touchstart', 'mousedown', 'keydown'].forEach(evt => {
    window.addEventListener(evt, onFirstRealUserInteraction, { capture: true, passive: true });
  });

  window.addEventListener('hashchange', () => {
    if (window.location.hash === '#demo') {
      state.demoActive = true;
      demoBanner.classList.add('visible');
      runDemoCycle();
    }
  });

  /* =========================================================
     8. EVENT LISTENERS (One-Finger Friendly)
     ========================================================= */
  // Paper style buttons (both on Compose view and Opened Letter view)
  document.querySelectorAll('.style-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const style = btn.getAttribute('data-style');
      applyPaperStyle(style, true);
    });
  });

  // Quick one-finger message preset chips
  document.querySelectorAll('.quick-chip').forEach(chip => {
    chip.addEventListener('click', () => {
      const idx = parseInt(chip.getAttribute('data-preset'), 10) || 0;
      inputMessage.value = PRESET_MESSAGES[idx % PRESET_MESSAGES.length];
      state.message = inputMessage.value;
      SoundEngine.playTap();
      saveState();
    });
  });

  // Live input persistence
  [inputFrom, inputFor, inputMessage].forEach(el => {
    el.addEventListener('input', () => {
      state.from = inputFrom.value;
      state.forWho = inputFor.value;
      state.message = inputMessage.value;
      saveState();
    });
  });

  // Send button
  btnSendLetter.addEventListener('click', () => {
    startDeliverySequence();
  });

  // Tapping the delivered envelope or prompt pill opens it
  btnOpenEnvelope.addEventListener('click', () => {
    openEnvelopeAndUnfold();
  });
  tapEnvelopePrompt.addEventListener('click', () => {
    openEnvelopeAndUnfold();
  });

  // If user taps the delivery arena while cat is walking, fast-forward to envelope presentation
  document.getElementById('delivery-arena').addEventListener('click', (e) => {
    if (state.stage === 'delivery' && !deliveredEnvelopeWrap.classList.contains('presented')) {
      if (e.target.closest('#btn-open-envelope')) return;
      clearDeliveryTimers();
      catPostman.classList.remove('walking', 'bowing');
      catHeldEnvelope.style.display = 'none';
      catEyesOpen.style.display = 'none';
      catEyesHappy.style.display = 'block';
      catSpeech.textContent = 'For ' + state.forWho + '! ♪';
      catSpeech.classList.add('visible');
      catPostman.classList.add('parked');
      deliveredEnvelopeWrap.classList.add('presented');
      SoundEngine.playCatMeow();
    }
  });

  // Tap pop-up diorama for extra hearts & chime
  popupDiorama.addEventListener('click', (e) => {
    spawnPopupHearts(e.clientX, e.clientY);
  });

  // Replay Delivery button (so user can show it on their phone to the person it is for)
  btnReplayDelivery.addEventListener('click', () => {
    startDeliverySequence();
  });

  // Edit Letter button
  btnEditLetter.addEventListener('click', () => {
    clearDeliveryTimers();
    clearWritingTimer();
    SoundEngine.playTap();
    showStage('compose');
  });

  // Sound Mute / Unmute Toggle
  soundToggleBtn.addEventListener('click', () => {
    SoundEngine.init();
    SoundEngine.muted = !SoundEngine.muted;
    soundIcon.textContent = SoundEngine.muted ? '✕' : '♪';
    soundLabel.textContent = SoundEngine.muted ? 'Muted' : 'Sound On';
    if (!SoundEngine.muted) {
      SoundEngine.playTap();
    }
  });

  /* =========================================================
     9. AMBIENT BACKGROUND CANVAS (Warm Gold Dust & Tiny Hearts)
     ========================================================= */
  const canvas = document.getElementById('ambient-canvas');
  const ctx = canvas.getContext('2d');
  let particles = [];

  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  }

  function createParticles() {
    particles = [];
    const count = Math.min(28, Math.floor((window.innerWidth * window.innerHeight) / 22000) + 12);
    for (let i = 0; i < count; i++) {
      particles.push({
        x: Math.random() * canvas.width,
        y: Math.random() * canvas.height,
        r: 1.2 + Math.random() * 2.4,
        vy: -0.18 - Math.random() * 0.32,
        vx: (Math.random() - 0.5) * 0.25,
        alpha: 0.18 + Math.random() * 0.45,
        phase: Math.random() * Math.PI * 2,
        isHeart: i % 5 === 0
      });
    }
  }

  function drawAmbient() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (let i = 0; i < particles.length; i++) {
      const p = particles[i];
      p.phase += 0.02;
      p.x += p.vx + Math.sin(p.phase) * 0.15;
      p.y += p.vy;

      if (p.y < -15) {
        p.y = canvas.height + 15;
        p.x = Math.random() * canvas.width;
      }

      const glowAlpha = p.alpha * (0.7 + 0.3 * Math.sin(p.phase));
      ctx.save();
      ctx.translate(p.x, p.y);
      if (p.isHeart) {
        ctx.fillStyle = `rgba(235, 110, 125, ${glowAlpha * 0.75})`;
        ctx.font = `${Math.round(p.r * 5)}px serif`;
        ctx.fillText('♥', 0, 0);
      } else {
        ctx.fillStyle = `rgba(245, 215, 127, ${glowAlpha})`;
        ctx.beginPath();
        ctx.arc(0, 0, p.r, 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.restore();
    }
    requestAnimationFrame(drawAmbient);
  }

  window.addEventListener('resize', resizeCanvas);
  resizeCanvas();
  createParticles();
  requestAnimationFrame(drawAmbient);

  /* =========================================================
     10. INITIALIZE APP
     ========================================================= */
  loadState();
  inputFrom.value = state.from;
  inputFor.value = state.forWho;
  inputMessage.value = state.message;
  applyPaperStyle(state.paperStyle, false);
  checkAndStartDemoMode();
})();
</script>
</body>
</html>