Skip to content
VibeCodeBench
Back to the app

The code

Love Letter by Gemini 4 Hydrogen

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.)99.5 KB · 2,743 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=5.0, viewport-fit=cover">
  <title>A Little Love Letter</title>
  <style>
    :root {
      --bg-top: #fbf3e4;
      --bg-mid: #f4e4cb;
      --bg-bot: #e8cfa9;

      --red-deep: #6e1221;
      --red-velvet: #9b1d30;
      --red-warm: #ba2b3f;
      --red-soft: #dfa3a8;

      --cream-pure: #fffdf8;
      --cream-warm: #faf0dd;
      --cream-aged: #eedbb9;

      --gold-bright: #eccd7f;
      --gold-main: #ca9840;
      --gold-deep: #8f631d;

      --ink-main: #3d1d22;
      --ink-muted: #785255;

      /* Active paper style variables (defaults: ivory) */
      --paper-surface: #fffdf6;
      --paper-surface-2: #f7ecd6;
      --paper-frame: #fffdf6;
      --paper-border: #d5a654;
      --paper-rule: rgba(202, 152, 64, 0.25);
      --env-body: #fbf1de;
      --env-flap: #fff8ea;
      --env-pocket: #f2e1c3;
      --env-trim: #d5a654;
      --seal-color: #b8293d;
      --seal-rim: #8f1829;
      --seal-emblem: #f7dc94;
      --card-mat: #f7ebd4;
      --sky-top: #3c1421;
      --sky-bot: #692638;

      --font-serif: "Palatino Linotype", "Book Antiqua", Georgia, Cambria, serif;
      --font-script: "Palatino Linotype", "Book Antiqua", Georgia, serif;
      --font-ui: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;

      --shadow-soft: 0 12px 32px rgba(84, 28, 34, 0.14), 0 3px 10px rgba(84, 28, 34, 0.08);
      --shadow-card: 0 20px 48px rgba(72, 20, 27, 0.22), 0 4px 14px rgba(72, 20, 27, 0.12);
    }

    [data-paper="ivory"] {
      --paper-surface: #fffdf7;
      --paper-surface-2: #f8eed8;
      --paper-frame: #fffdf7;
      --paper-border: #d6a756;
      --paper-rule: rgba(202, 152, 64, 0.24);
      --env-body: #fcf3e1;
      --env-flap: #fff9ec;
      --env-pocket: #f2e2c4;
      --env-trim: #d4a351;
      --seal-color: #ba293d;
      --seal-rim: #8b1727;
      --seal-emblem: #f9df9a;
      --card-mat: #f7ebd4;
      --sky-top: #3e1422;
      --sky-bot: #6a2638;
    }

    [data-paper="crimson"] {
      --paper-surface: #fff9ee;
      --paper-surface-2: #f5e6cf;
      --paper-frame: #851829;
      --paper-border: #e5c174;
      --paper-rule: rgba(168, 42, 59, 0.18);
      --env-body: #8e1b2d;
      --env-flap: #9f2235;
      --env-pocket: #761323;
      --env-trim: #e7c67b;
      --seal-color: #d6a247;
      --seal-rim: #9f7021;
      --seal-emblem: #731322;
      --card-mat: #831728;
      --sky-top: #2c0b14;
      --sky-bot: #541928;
    }

    [data-paper="blush"] {
      --paper-surface: #fdf4f1;
      --paper-surface-2: #f5dfd8;
      --paper-frame: #f7e4de;
      --paper-border: #c98f61;
      --paper-rule: rgba(186, 98, 98, 0.2);
      --env-body: #f6dfd9;
      --env-flap: #fcece8;
      --env-pocket: #eccbc2;
      --env-trim: #cb9163;
      --seal-color: #a8253e;
      --seal-rim: #7c1529;
      --seal-emblem: #f5d89e;
      --card-mat: #efd2c9;
      --sky-top: #461927;
      --sky-bot: #762d40;
    }

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

    html, body {
      margin: 0;
      padding: 0;
      min-height: 100%;
      width: 100%;
      overflow-x: hidden;
      font-family: var(--font-ui);
      color: var(--ink-main);
      background: radial-gradient(circle at 50% 18%, var(--bg-top) 0%, var(--bg-mid) 56%, var(--bg-bot) 100%);
      background-attachment: fixed;
      touch-action: manipulation;
    }

    /* Subtle tactile paper grain overlay */
    body::before {
      content: "";
      position: fixed;
      inset: 0;
      pointer-events: none;
      opacity: 0.32;
      background-image:
        radial-gradient(rgba(143, 99, 29, 0.08) 1px, transparent 1px),
        radial-gradient(rgba(155, 29, 48, 0.05) 1px, transparent 1px);
      background-size: 26px 26px, 19px 19px;
      background-position: 0 0, 9px 11px;
      z-index: 0;
    }

    .app-shell {
      position: relative;
      z-index: 1;
      min-height: 100dvh;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: max(12px, env(safe-area-inset-top)) 14px max(20px, env(safe-area-inset-bottom));
    }

    /* Header */
    .topbar {
      width: 100%;
      max-width: 680px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
      margin-bottom: 10px;
    }

    .brand {
      display: flex;
      align-items: center;
      gap: 9px;
      min-width: 0;
    }

    .brand-seal {
      width: 34px;
      height: 34px;
      border-radius: 50%;
      background: radial-gradient(circle at 35% 30%, #d43e52, var(--red-velvet) 68%, var(--red-deep));
      border: 2px solid var(--gold-bright);
      box-shadow: 0 3px 8px rgba(110, 18, 33, 0.25);
      display: grid;
      place-items: center;
      flex-shrink: 0;
    }

    .brand-title {
      font-family: var(--font-serif);
      font-size: clamp(1.05rem, 3.2vw, 1.32rem);
      font-weight: 700;
      letter-spacing: 0.01em;
      color: var(--red-deep);
      margin: 0;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .btn-pill {
      appearance: none;
      border: 1.5px solid rgba(143, 99, 29, 0.35);
      background: rgba(255, 252, 244, 0.88);
      color: var(--ink-main);
      font-family: var(--font-ui);
      font-size: 0.92rem;
      font-weight: 600;
      min-height: 46px;
      padding: 0 15px;
      border-radius: 999px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 7px;
      cursor: pointer;
      box-shadow: 0 3px 10px rgba(90, 35, 35, 0.08);
      transition: transform 0.14s ease, background-color 0.2s ease, border-color 0.2s ease;
      user-select: none;
    }

    .btn-pill:active {
      transform: scale(0.96);
    }

    @media (hover: hover) {
      .btn-pill:hover {
        border-color: var(--gold-main);
        background: #fffdf8;
      }
    }

    .btn-sound[data-muted="true"] {
      opacity: 0.78;
      color: var(--ink-muted);
    }

    /* Demo Banner */
    .demo-banner {
      position: fixed;
      bottom: max(14px, env(safe-area-inset-bottom));
      left: 50%;
      transform: translateX(-50%);
      z-index: 40;
      background: rgba(110, 18, 33, 0.92);
      color: var(--cream-pure);
      border: 1.5px solid var(--gold-bright);
      border-radius: 999px;
      padding: 9px 18px;
      font-size: 0.88rem;
      font-weight: 600;
      letter-spacing: 0.01em;
      box-shadow: 0 8px 24px rgba(60, 14, 20, 0.28);
      display: flex;
      align-items: center;
      gap: 8px;
      white-space: nowrap;
      pointer-events: none;
      animation: pulseSoft 2.4s ease-in-out infinite;
    }

    .demo-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: var(--gold-bright);
      flex-shrink: 0;
    }

    /* Main Stage */
    .stage {
      width: 100%;
      max-width: 720px;
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .view {
      width: 100%;
      display: none;
      flex-direction: column;
      align-items: center;
      animation: viewEnter 0.38s ease both;
    }

    .view.is-active {
      display: flex;
    }

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

    /* ================= COMPOSE VIEW ================= */
    .compose-card {
      width: 100%;
      max-width: 500px;
      background: var(--paper-frame);
      border-radius: 22px;
      padding: 10px;
      box-shadow: var(--shadow-card);
      border: 1.5px solid rgba(202, 152, 64, 0.45);
      transition: background-color 0.35s ease, border-color 0.35s ease;
    }

    .compose-inner {
      background: linear-gradient(180deg, var(--paper-surface) 0%, var(--paper-surface-2) 100%);
      border-radius: 15px;
      border: 2px solid var(--paper-border);
      padding: 18px 16px 18px;
      position: relative;
      box-shadow: inset 0 0 0 4px rgba(255, 253, 248, 0.55);
      transition: background 0.35s ease, border-color 0.35s ease;
    }

    .compose-header {
      text-align: center;
      margin-bottom: 14px;
    }

    .compose-subtitle {
      font-family: var(--font-serif);
      font-style: italic;
      font-size: 1.04rem;
      color: var(--red-velvet);
      margin: 0;
    }

    /* Paper Style Selector */
    .style-section-label {
      display: block;
      font-size: 0.78rem;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 0.08em;
      color: var(--ink-muted);
      margin-bottom: 7px;
      text-align: center;
    }

    .paper-picker {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 8px;
      margin-bottom: 14px;
    }

    .paper-swatch {
      appearance: none;
      position: relative;
      min-height: 54px;
      padding: 8px 6px;
      border-radius: 13px;
      border: 2px solid rgba(143, 99, 29, 0.22);
      background: rgba(255, 255, 255, 0.72);
      cursor: pointer;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 5px;
      color: var(--ink-main);
      font-family: var(--font-ui);
      font-size: 0.8rem;
      font-weight: 700;
      transition: transform 0.14s ease, border-color 0.22s ease, box-shadow 0.22s ease;
    }

    .paper-swatch:active {
      transform: scale(0.96);
    }

    .paper-swatch.is-selected {
      border-color: var(--gold-main);
      box-shadow: 0 0 0 3px rgba(202, 152, 64, 0.24), 0 4px 12px rgba(110, 18, 33, 0.12);
      background: #fffdf8;
    }

    .swatch-preview {
      width: 34px;
      height: 22px;
      border-radius: 6px;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
    }

    .swatch-preview--ivory {
      background: #fffdf5;
      border: 1.5px solid #d5a654;
    }

    .swatch-preview--crimson {
      background: linear-gradient(135deg, #9f2235, #761323);
      border: 1.5px solid #e6c378;
    }

    .swatch-preview--blush {
      background: linear-gradient(135deg, #fbe8e2, #eecac0);
      border: 1.5px solid #c98f61;
    }

    .swatch-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
    }

    .swatch-preview--ivory .swatch-dot { background: #ba293d; }
    .swatch-preview--crimson .swatch-dot { background: #e6c378; }
    .swatch-preview--blush .swatch-dot { background: #a8253e; }

    /* Form Fields */
    .names-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 10px;
      margin-bottom: 11px;
    }

    @media (max-width: 390px) {
      .names-row {
        grid-template-columns: 1fr;
      }
    }

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

    .field-label {
      font-size: 0.8rem;
      font-weight: 700;
      letter-spacing: 0.04em;
      text-transform: uppercase;
      color: var(--red-velvet);
      padding-left: 4px;
    }

    .field-input, .field-textarea {
      width: 100%;
      font-family: var(--font-serif);
      font-size: 16px;
      color: var(--ink-main);
      background: rgba(255, 255, 255, 0.78);
      border: 1.5px solid rgba(180, 128, 62, 0.38);
      border-radius: 12px;
      padding: 11px 12px;
      outline: none;
      transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
    }

    .field-input {
      min-height: 48px;
    }

    .field-textarea {
      min-height: 112px;
      resize: vertical;
      line-height: 1.58;
      background-image: repeating-linear-gradient(
        to bottom,
        transparent 0,
        transparent 24px,
        var(--paper-rule) 24px,
        var(--paper-rule) 25.2px
      );
      background-position: 0 9px;
    }

    .field-input::placeholder, .field-textarea::placeholder {
      color: rgba(120, 82, 85, 0.56);
      font-style: italic;
    }

    .field-input:focus, .field-textarea:focus {
      border-color: var(--red-warm);
      background-color: #fffef9;
      box-shadow: 0 0 0 3px rgba(186, 43, 63, 0.14);
    }

    .field-input.is-demo-focus, .field-textarea.is-demo-focus {
      border-color: var(--gold-main);
      box-shadow: 0 0 0 3px rgba(202, 152, 64, 0.24);
      background-color: #fffef9;
    }

    .msg-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 4px;
      padding: 0 4px;
      font-size: 0.78rem;
      color: var(--ink-muted);
    }

    /* Quick One-Tap Inspirations (no keyboard needed!) */
    .quick-notes {
      display: flex;
      flex-wrap: wrap;
      gap: 7px;
      margin: 10px 0 14px;
    }

    .chip-btn {
      appearance: none;
      min-height: 44px;
      padding: 6px 12px;
      border-radius: 999px;
      border: 1.5px solid rgba(186, 43, 63, 0.25);
      background: rgba(255, 251, 242, 0.9);
      color: var(--red-deep);
      font-family: var(--font-ui);
      font-size: 0.84rem;
      font-weight: 600;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 5px;
      transition: transform 0.14s ease, background-color 0.2s ease, border-color 0.2s ease;
    }

    .chip-btn:active {
      transform: scale(0.95);
    }

    @media (hover: hover) {
      .chip-btn:hover {
        background: #fff6e4;
        border-color: var(--gold-main);
      }
    }

    .compose-hint {
      min-height: 22px;
      margin-bottom: 10px;
      text-align: center;
      font-size: 0.88rem;
      font-weight: 600;
      color: var(--red-velvet);
      opacity: 0;
      transform: translateY(-3px);
      transition: opacity 0.25s ease, transform 0.25s ease;
    }

    .compose-hint.is-visible {
      opacity: 1;
      transform: translateY(0);
    }

    .btn-send {
      appearance: none;
      width: 100%;
      min-height: 56px;
      border-radius: 16px;
      border: 2px solid var(--gold-bright);
      background: linear-gradient(180deg, #c73247 0%, #9b1d30 58%, #771222 100%);
      color: var(--cream-pure);
      font-family: var(--font-serif);
      font-size: 1.15rem;
      font-weight: 700;
      letter-spacing: 0.02em;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
      box-shadow: 0 10px 24px rgba(120, 18, 34, 0.28), inset 0 1px 0 rgba(255, 240, 200, 0.38);
      transition: transform 0.15s ease, box-shadow 0.2s ease;
    }

    .btn-send:active, .btn-send.is-pressed {
      transform: translateY(2px) scale(0.985);
      box-shadow: 0 4px 12px rgba(120, 18, 34, 0.28);
    }

    /* ================= DELIVERY VIEW ================= */
    .delivery-stage {
      width: 100%;
      max-width: 720px;
      min-height: clamp(360px, 60dvh, 490px);
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: flex-end;
      padding-bottom: 18px;
      overflow: hidden;
    }

    .delivery-horizon {
      position: relative;
      width: 100%;
      height: 310px;
      display: flex;
      align-items: flex-end;
      justify-content: center;
    }

    /* Cozy warm path / tabletop ground */
    .delivery-ground {
      position: absolute;
      left: 4%;
      right: 4%;
      bottom: 42px;
      height: 18px;
      border-radius: 50%;
      background: radial-gradient(ellipse at center, rgba(168, 108, 58, 0.22) 0%, rgba(168, 108, 58, 0) 74%);
      pointer-events: none;
    }

    .delivery-path-line {
      position: absolute;
      left: 6%;
      right: 6%;
      bottom: 51px;
      height: 2px;
      background: linear-gradient(90deg, transparent, rgba(182, 128, 62, 0.42) 22%, rgba(182, 128, 62, 0.42) 78%, transparent);
      pointer-events: none;
    }

    .cat-actor {
      position: absolute;
      bottom: 46px;
      left: 50%;
      width: 146px;
      height: 136px;
      pointer-events: none;
      will-change: transform, opacity;
      z-index: 6;
      opacity: 0;
    }

    .cat-actor svg {
      width: 100%;
      height: 100%;
      overflow: visible;
    }

    /* Waiting Interactive Envelope */
    .envelope-wrap {
      position: relative;
      z-index: 5;
      margin-bottom: 34px;
      display: flex;
      flex-direction: column;
      align-items: center;
      opacity: 0;
      transform: scale(0.35) translateY(20px);
      pointer-events: none;
      transition: opacity 0.42s ease, transform 0.55s cubic-bezier(0.22, 1.25, 0.36, 1);
    }

    .envelope-wrap.is-landed {
      opacity: 1;
      transform: scale(1) translateY(0);
      pointer-events: auto;
    }

    .envelope-wrap.is-opening {
      pointer-events: none;
    }

    .envelope-btn {
      appearance: none;
      border: none;
      background: transparent;
      padding: 10px;
      cursor: pointer;
      position: relative;
      perspective: 950px;
      display: flex;
      flex-direction: column;
      align-items: center;
      animation: envelopeFloat 3s ease-in-out infinite;
    }

    .envelope-wrap.is-opening .envelope-btn {
      animation: none;
    }

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

    .envelope-shadow {
      width: 240px;
      height: 22px;
      border-radius: 50%;
      background: radial-gradient(ellipse at center, rgba(84, 24, 30, 0.24) 0%, transparent 72%);
      margin-top: -4px;
      transition: transform 0.4s ease, opacity 0.4s ease;
    }

    .envelope-3d {
      position: relative;
      width: min(78vw, 296px);
      height: calc(min(78vw, 296px) * 0.64);
      transform-style: preserve-3d;
      transition: transform 0.6s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.45s ease;
    }

    .envelope-back {
      position: absolute;
      inset: 0;
      border-radius: 12px;
      background: var(--env-body);
      border: 2px solid var(--env-trim);
      box-shadow: 0 18px 34px rgba(72, 18, 26, 0.22);
      overflow: hidden;
    }

    /* Inner card sliding out during opening */
    .envelope-peek-card {
      position: absolute;
      left: 8%;
      right: 8%;
      top: 12%;
      bottom: 10%;
      background: var(--paper-surface);
      border: 1.5px solid var(--paper-border);
      border-radius: 8px;
      transform: translateY(0);
      transition: transform 0.68s cubic-bezier(0.22, 1, 0.36, 1);
      display: flex;
      align-items: flex-start;
      justify-content: center;
      padding-top: 14px;
    }

    .envelope-wrap.is-opening .envelope-peek-card {
      transform: translateY(-74%);
    }

    /* Pocket triangles (SVG overlay for crisp geometry) */
    .envelope-pocket-svg {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      z-index: 2;
      border-radius: 12px;
    }

    .envelope-address {
      position: absolute;
      inset: 0;
      z-index: 3;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: flex-end;
      padding: 12px 18px 14px;
      pointer-events: none;
      text-align: center;
    }

    .env-to {
      font-family: var(--font-serif);
      font-style: italic;
      font-size: clamp(1rem, 3.8vw, 1.24rem);
      font-weight: 700;
      color: var(--ink-main);
      max-width: 90%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      text-shadow: 0 1px 0 rgba(255, 255, 255, 0.4);
    }

    [data-paper="crimson"] .env-to,
    [data-paper="crimson"] .env-from {
      color: #fff6e4;
      text-shadow: 0 1px 2px rgba(45, 5, 10, 0.45);
    }

    .env-from {
      font-family: var(--font-serif);
      font-size: 0.8rem;
      color: var(--ink-muted);
      margin-top: 2px;
      max-width: 85%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    /* Top Flap */
    .envelope-flap {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 58%;
      z-index: 4;
      transform-origin: top center;
      transform-style: preserve-3d;
      transition: transform 0.65s cubic-bezier(0.32, 0.9, 0.32, 1);
    }

    .envelope-wrap.is-opening .envelope-flap {
      transform: rotateX(174deg);
      z-index: 1;
    }

    .envelope-flap svg {
      width: 100%;
      height: 100%;
      display: block;
      filter: drop-shadow(0 4px 6px rgba(72, 18, 26, 0.16));
    }

    /* Heart Wax Seal */
    .wax-seal {
      position: absolute;
      left: 50%;
      top: 52%;
      transform: translate(-50%, -50%);
      width: 52px;
      height: 52px;
      z-index: 6;
      border-radius: 50%;
      background: radial-gradient(circle at 32% 30%, rgba(255, 255, 255, 0.35), transparent 45%),
                  radial-gradient(circle at 50% 50%, var(--seal-color) 62%, var(--seal-rim) 100%);
      box-shadow: 0 5px 12px rgba(64, 10, 18, 0.36), inset 0 2px 3px rgba(255, 240, 210, 0.32);
      border: 2px solid rgba(255, 232, 178, 0.45);
      display: grid;
      place-items: center;
      transition: transform 0.35s ease, opacity 0.3s ease;
    }

    .envelope-wrap.is-opening .wax-seal {
      transform: translate(-50%, -95%) scale(0.75);
      opacity: 0;
    }

    .tap-prompt {
      margin-top: 12px;
      display: inline-flex;
      align-items: center;
      gap: 7px;
      padding: 8px 16px;
      border-radius: 999px;
      background: rgba(255, 252, 244, 0.92);
      border: 1.5px solid var(--gold-main);
      color: var(--red-deep);
      font-size: 0.92rem;
      font-weight: 700;
      box-shadow: 0 5px 14px rgba(84, 24, 30, 0.12);
      animation: pulseSoft 2s ease-in-out infinite;
    }

    .tap-ripple {
      position: absolute;
      left: 50%;
      top: 52%;
      width: 56px;
      height: 56px;
      border-radius: 50%;
      border: 3px solid var(--gold-bright);
      transform: translate(-50%, -50%) scale(0.4);
      opacity: 0;
      pointer-events: none;
      z-index: 9;
    }

    .tap-ripple.is-pop {
      animation: tapPop 0.65s ease-out forwards;
    }

    @keyframes tapPop {
      0% { transform: translate(-50%, -50%) scale(0.45); opacity: 0.95; }
      100% { transform: translate(-50%, -50%) scale(2.1); opacity: 0; }
    }

    .delivery-footer {
      margin-top: 6px;
      display: flex;
      gap: 10px;
      justify-content: center;
    }

    /* ================= POP-UP CARD VIEW ================= */
    .keepsake-wrap {
      width: 100%;
      max-width: 490px;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 12px;
    }

    .popup-card-frame {
      width: 100%;
      background: var(--card-mat);
      border: 2px solid var(--paper-border);
      border-radius: 22px;
      padding: 10px;
      box-shadow: var(--shadow-card);
      perspective: 1150px;
      transition: background-color 0.35s ease, border-color 0.35s ease;
    }

    .popup-card-inner {
      border-radius: 15px;
      border: 2px solid var(--paper-border);
      background: var(--paper-surface);
      display: flex;
      flex-direction: column;
      transform-style: preserve-3d;
      box-shadow: inset 0 0 0 1px rgba(255, 253, 248, 0.5);
    }

    /* Top Half: 3D Paper Pop-Up Diorama */
    .popup-diorama {
      position: relative;
      width: 100%;
      height: clamp(220px, 34dvh, 272px);
      border-radius: 13px 13px 0 0;
      perspective: 1000px;
      transform-style: preserve-3d;
      background: linear-gradient(180deg, var(--sky-top) 0%, var(--sky-bot) 100%);
      border-bottom: 2px solid rgba(212, 163, 89, 0.45);
    }

    .diorama-sky-clip {
      position: absolute;
      inset: 0;
      border-radius: 13px 13px 0 0;
      overflow: hidden;
      pointer-events: none;
    }

    .diorama-sky-svg {
      width: 100%;
      height: 100%;
      display: block;
    }

    /* Twinkling stars */
    .star-twinkle {
      animation: starTwinkle 2.8s ease-in-out infinite;
    }
    .star-twinkle.d2 { animation-delay: 0.9s; }
    .star-twinkle.d3 { animation-delay: 1.7s; }

    @keyframes starTwinkle {
      0%, 100% { opacity: 0.45; transform: scale(0.92); }
      50% { opacity: 1; transform: scale(1.08); }
    }

    /* 3D Pop-up Layers hinged at the bottom center fold */
    .popup-plane {
      position: absolute;
      inset: 0;
      transform-origin: bottom center;
      transform-style: preserve-3d;
      pointer-events: none;
      opacity: 0;
      transform: rotateX(82deg);
      transition: transform 0.95s cubic-bezier(0.22, 1.24, 0.36, 1), opacity 0.4s ease;
    }

    .popup-card-frame.is-unfolded .popup-plane {
      opacity: 1;
    }

    .popup-card-frame.is-unfolded .plane-hill {
      transform: translateZ(12px) rotateX(0deg);
      transition-delay: 0.08s;
    }

    .popup-card-frame.is-unfolded .plane-cats {
      transform: translateZ(26px) rotateX(0deg);
      transition-delay: 0.22s;
    }

    .popup-card-frame.is-unfolded .plane-flora {
      transform: translateZ(40px) rotateX(0deg);
      transition-delay: 0.36s;
    }

    .popup-plane svg {
      width: 100%;
      height: 100%;
      display: block;
      overflow: visible;
    }

    /* Subtle alive motion after unfolding */
    .popup-card-frame.is-unfolded .cats-alive {
      animation: catsGentle 4.8s ease-in-out infinite;
      transform-origin: 210px 210px;
    }

    @keyframes catsGentle {
      0%, 100% { transform: scaleY(1) translateY(0); }
      50% { transform: scaleY(1.015) translateY(-1px); }
    }

    .floating-heart {
      opacity: 0;
    }

    .popup-card-frame.is-unfolded .floating-heart {
      animation: floatHeartUp 5.4s ease-in-out infinite;
    }

    .floating-heart.fh2 { animation-delay: 1.4s !important; }
    .floating-heart.fh3 { animation-delay: 2.8s !important; }
    .floating-heart.fh4 { animation-delay: 4.1s !important; }

    @keyframes floatHeartUp {
      0% { opacity: 0; transform: translateY(10px) scale(0.75); }
      22% { opacity: 0.9; }
      75% { opacity: 0.78; }
      100% { opacity: 0; transform: translateY(-48px) scale(1.06); }
    }

    /* Center Fold Crease with physical paper tabs */
    .card-crease {
      position: relative;
      height: 10px;
      background: linear-gradient(180deg, rgba(110, 42, 42, 0.16) 0%, rgba(255, 250, 238, 0.85) 55%, rgba(143, 99, 29, 0.1) 100%);
      display: flex;
      justify-content: space-around;
      align-items: center;
      padding: 0 28px;
    }

    .crease-tab {
      width: 24px;
      height: 4px;
      border-radius: 2px;
      background: rgba(143, 99, 29, 0.25);
    }

    /* Bottom Half: Handwritten Letter Sheet */
    .letter-sheet {
      position: relative;
      padding: 18px 20px 20px;
      border-radius: 0 0 13px 13px;
      background:
        repeating-linear-gradient(
          to bottom,
          transparent 0,
          transparent 27px,
          var(--paper-rule) 27px,
          var(--paper-rule) 28.2px
        ),
        linear-gradient(180deg, var(--paper-surface) 0%, var(--paper-surface-2) 100%);
      background-position: 0 20px, 0 0;
      min-height: 175px;
      max-height: 290px;
      overflow-y: auto;
      -webkit-overflow-scrolling: touch;
      cursor: pointer;
    }

    .letter-salutation {
      font-family: var(--font-script);
      font-style: italic;
      font-size: 1.18rem;
      font-weight: 700;
      color: var(--red-velvet);
      margin-bottom: 8px;
      line-height: 1.5;
      overflow-wrap: anywhere;
    }

    .letter-body {
      font-family: var(--font-script);
      font-style: italic;
      font-size: clamp(1.04rem, 3.6vw, 1.16rem);
      line-height: 28.2px;
      color: var(--ink-main);
      min-height: 56px;
      overflow-wrap: anywhere;
    }

    .letter-signature {
      font-family: var(--font-script);
      font-style: italic;
      font-size: 1.12rem;
      font-weight: 700;
      color: var(--red-velvet);
      margin-top: 12px;
      text-align: right;
      line-height: 1.45;
      overflow-wrap: anywhere;
    }

    .word-wrap {
      display: inline-block;
      white-space: nowrap;
    }

    .char {
      display: inline;
      opacity: 0;
      transition: opacity 0.16s ease;
    }

    .char.is-inked {
      opacity: 1;
    }

    .char.space {
      white-space: pre-wrap;
    }

    /* Animated golden fountain-pen nib cursor */
    .pen-nib {
      position: absolute;
      width: 24px;
      height: 24px;
      pointer-events: none;
      opacity: 0;
      transform: translate(-3px, -21px) rotate(12deg);
      transition: left 0.05s linear, top 0.05s linear, opacity 0.2s ease;
      z-index: 4;
      filter: drop-shadow(0 2px 3px rgba(110, 18, 33, 0.24));
    }

    .pen-nib.is-writing {
      opacity: 1;
    }

    .flourish-row {
      display: flex;
      justify-content: flex-end;
      margin-top: 4px;
      height: 26px;
    }

    .end-flourish-path {
      stroke-dasharray: 120;
      stroke-dashoffset: 120;
      transition: stroke-dashoffset 0.85s cubic-bezier(0.35, 0, 0.25, 1);
    }

    .end-flourish-path.is-drawn {
      stroke-dashoffset: 0;
    }

    /* Keepsake Action Dock */
    .card-actions {
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 10px;
    }

    .actions-row {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      gap: 9px;
      justify-content: center;
    }

    .btn-replay {
      flex: 1 1 180px;
      min-height: 50px;
      border-radius: 15px;
      border: 2px solid var(--gold-bright);
      background: linear-gradient(180deg, #c73247 0%, #961c2e 100%);
      color: var(--cream-pure);
      font-family: var(--font-ui);
      font-size: 0.96rem;
      font-weight: 700;
      padding: 0 16px;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      box-shadow: 0 8px 20px rgba(110, 18, 33, 0.22);
      transition: transform 0.14s ease;
    }

    .btn-replay:active {
      transform: scale(0.97);
    }

    .btn-edit {
      flex: 1 1 130px;
      min-height: 50px;
      border-radius: 15px;
      border: 1.5px solid rgba(143, 99, 29, 0.42);
      background: rgba(255, 252, 245, 0.92);
      color: var(--ink-main);
      font-family: var(--font-ui);
      font-size: 0.94rem;
      font-weight: 700;
      padding: 0 16px;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 7px;
      box-shadow: 0 4px 12px rgba(84, 24, 30, 0.08);
      transition: transform 0.14s ease;
    }

    .btn-edit:active {
      transform: scale(0.97);
    }

    .mini-style-bar {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      flex-wrap: wrap;
      background: rgba(255, 251, 242, 0.85);
      border: 1.5px solid rgba(202, 152, 64, 0.35);
      border-radius: 999px;
      padding: 5px 10px;
    }

    .mini-style-label {
      font-size: 0.78rem;
      font-weight: 700;
      color: var(--ink-muted);
      padding-left: 4px;
    }

    .mini-swatch {
      appearance: none;
      min-height: 44px;
      min-width: 72px;
      padding: 0 11px;
      border-radius: 999px;
      border: 1.5px solid transparent;
      background: transparent;
      font-family: var(--font-ui);
      font-size: 0.8rem;
      font-weight: 700;
      color: var(--ink-main);
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.12s ease;
    }

    .mini-swatch:active {
      transform: scale(0.95);
    }

    .mini-swatch.is-selected {
      background: #fffdf8;
      border-color: var(--gold-main);
      box-shadow: 0 2px 7px rgba(110, 18, 33, 0.1);
    }

    .mini-dot {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      border: 1px solid rgba(110, 18, 33, 0.25);
      flex-shrink: 0;
    }

    .mini-dot--ivory { background: #fff9ea; border-color: #d4a351; }
    .mini-dot--crimson { background: #9b1d30; border-color: #e5c174; }
    .mini-dot--blush { background: #f1ccc1; border-color: #c98f61; }

    @keyframes pulseSoft {
      0%, 100% { opacity: 0.92; transform: scale(1); }
      50% { opacity: 1; transform: scale(1.025); }
    }

    /* Ensure demo banner uses translateX(-50%) cleanly */
    .demo-banner {
      animation: demoPulse 2.4s ease-in-out infinite;
    }

    @keyframes demoPulse {
      0%, 100% { opacity: 0.94; transform: translateX(-50%) scale(1); }
      50% { opacity: 1; transform: translateX(-50%) scale(1.02); }
    }

    [hidden] {
      display: none !important;
    }
  </style>
</head>
<body data-paper="ivory">
  <div class="app-shell">
    <header class="topbar">
      <div class="brand">
        <div class="brand-seal" aria-hidden="true">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <path d="M12 20.4s-7.4-4.7-9.3-9.2C1.4 8 3.2 4.6 6.7 4.6c2 0 3.7 1.1 5.3 2.9 1.6-1.8 3.3-2.9 5.3-2.9 3.5 0 5.3 3.4 4 6.6-1.9 4.5-9.3 9.2-9.3 9.2z" fill="#F9DF9A"/>
          </svg>
        </div>
        <h1 class="brand-title">A Little Love Letter</h1>
      </div>

      <button type="button" class="btn-pill btn-sound" id="btnSound" data-muted="false" aria-label="Toggle sound">
        <span id="soundIcon" aria-hidden="true">🔊</span>
        <span id="soundLabel">Sound On</span>
      </button>
    </header>

    <main class="stage">
      <!-- ==================== VIEW 1: COMPOSE ==================== -->
      <section class="view is-active" id="viewCompose" aria-label="Write a love letter">
        <div class="compose-card">
          <div class="compose-inner">
            <div class="compose-header">
              <p class="compose-subtitle">Seal a sweet thought for someone dear</p>
            </div>

            <span class="style-section-label">Choose Paper Style</span>
            <div class="paper-picker" role="radiogroup" aria-label="Paper style">
              <button type="button" class="paper-swatch is-selected" data-style="ivory" role="radio" aria-checked="true">
                <span class="swatch-preview swatch-preview--ivory"><span class="swatch-dot"></span></span>
                <span>Ivory Lace</span>
              </button>
              <button type="button" class="paper-swatch" data-style="crimson" role="radio" aria-checked="false">
                <span class="swatch-preview swatch-preview--crimson"><span class="swatch-dot"></span></span>
                <span>Velvet Red</span>
              </button>
              <button type="button" class="paper-swatch" data-style="blush" role="radio" aria-checked="false">
                <span class="swatch-preview swatch-preview--blush"><span class="swatch-dot"></span></span>
                <span>Blush Rose</span>
              </button>
            </div>

            <div class="names-row">
              <div class="field-group">
                <label class="field-label" for="inputTo">For</label>
                <input id="inputTo" class="field-input" type="text" maxlength="34" placeholder="Their name..." autocomplete="off">
              </div>
              <div class="field-group">
                <label class="field-label" for="inputFrom">From</label>
                <input id="inputFrom" class="field-input" type="text" maxlength="34" placeholder="Your name..." autocomplete="off">
              </div>
            </div>

            <div class="field-group">
              <label class="field-label" for="inputMessage">Your Message</label>
              <textarea id="inputMessage" class="field-textarea" maxlength="220" placeholder="Write a short love letter..."></textarea>
              <div class="msg-meta">
                <span>Tap a sweet note below or write your own</span>
                <span id="charCount">0 / 220</span>
              </div>
            </div>

            <div class="quick-notes" aria-label="One-tap sample notes">
              <button type="button" class="chip-btn" data-preset="moon">🌙 Under the Moon</button>
              <button type="button" class="chip-btn" data-preset="everyday">🌹 Thinking of You</button>
              <button type="button" class="chip-btn" data-preset="forever">✨ Forever Yours</button>
              <button type="button" class="chip-btn" id="btnClearDraft" aria-label="Clear note">✕ Clear</button>
            </div>

            <div class="compose-hint" id="composeHint" role="status" aria-live="polite"></div>

            <button type="button" class="btn-send" id="btnSend">
              <span>Send Love Letter</span>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <rect x="2.5" y="5" width="19" height="14" rx="2.5" stroke="#FFFDF8" stroke-width="2"/>
                <path d="M3.5 6.5L12 13.2L20.5 6.5" stroke="#F8DE94" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </button>
          </div>
        </div>
      </section>

      <!-- ==================== VIEW 2: CAT DELIVERY & ENVELOPE ==================== -->
      <section class="view" id="viewDelivery" aria-label="Cat postman delivery">
        <div class="delivery-stage">
          <div class="delivery-horizon">
            <div class="delivery-ground"></div>
            <div class="delivery-path-line"></div>

            <!-- Small Cat Postman in Blue Cap -->
            <div class="cat-actor" id="catActor" aria-hidden="true">
              <svg viewBox="0 0 180 158" xmlns="http://www.w3.org/2000/svg">
                <defs>
                  <linearGradient id="catFurGrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stop-color="#F6C88F"/>
                    <stop offset="100%" stop-color="#E39D5D"/>
                  </linearGradient>
                  <linearGradient id="catBlueCapGrad" x1="0" y1="0" x2="1" y2="1">
                    <stop offset="0%" stop-color="#4582BC"/>
                    <stop offset="100%" stop-color="#24507D"/>
                  </linearGradient>
                </defs>

                <!-- Floating little heart when placing letter -->
                <g id="catHeart" opacity="0" transform="translate(110, 12)">
                  <path d="M10 18s-7.5-4.8-9.2-9C-.3 6 1.5 2.8 4.8 2.8c1.9 0 3.4 1 5.2 2.7 1.8-1.7 3.3-2.7 5.2-2.7 3.3 0 5.1 3.2 4 6.2-1.7 4.2-9.2 9-9.2 9z" fill="#C42C41" stroke="#F6D88C" stroke-width="1"/>
                </g>

                <!-- Ground shadow beneath cat -->
                <ellipse cx="82" cy="145" rx="34" ry="7" fill="rgba(96, 36, 34, 0.16)"/>

                <!-- Tail -->
                <g id="catTail" style="transform-origin: 54px 104px;">
                  <path d="M56 104 C 32 104, 18 82, 28 66 C 34 57, 45 64, 40 74 C 35 84, 44 94, 58 95 Z" fill="#E39D5D" stroke="#9B5B2A" stroke-width="1.4"/>
                  <circle cx="33" cy="68" r="5.5" fill="#FFF7E8"/>
                </g>

                <!-- Far Hind Leg -->
                <g id="catLegFar" style="transform-origin: 73px 115px;">
                  <rect x="66" y="114" width="13" height="24" rx="6.5" fill="#D58E4F" stroke="#9B5B2A" stroke-width="1.3"/>
                  <ellipse cx="75" cy="139" rx="7.5" ry="4.5" fill="#FFF7E8" stroke="#9B5B2A" stroke-width="1.2"/>
                </g>

                <!-- Torso -->
                <ellipse cx="80" cy="98" rx="25" ry="26" fill="url(#catFurGrad)" stroke="#9B5B2A" stroke-width="1.5"/>
                <!-- Cream Belly -->
                <ellipse cx="88" cy="100" rx="14" ry="19" fill="#FFF7E8"/>

                <!-- Postman Blue Satchel Bag & Strap -->
                <path d="M62 80 Q 82 96 100 112" stroke="#2B5B89" stroke-width="5.5" stroke-linecap="round" fill="none"/>
                <rect x="52" y="96" width="22" height="19" rx="4" fill="#2B5B89" stroke="#183858" stroke-width="1.4"/>
                <path d="M52 101 L 63 108 L 74 101" fill="#3D76AC" stroke="#183858" stroke-width="1.2"/>
                <rect x="61" y="106" width="4" height="4" rx="1" fill="#ECCD7F"/>

                <!-- Near Hind Leg -->
                <g id="catLegNear" style="transform-origin: 83px 117px;">
                  <rect x="76" y="116" width="14" height="24" rx="7" fill="#EDAF72" stroke="#9B5B2A" stroke-width="1.3"/>
                  <ellipse cx="86" cy="141" rx="8" ry="4.8" fill="#FFF7E8" stroke="#9B5B2A" stroke-width="1.2"/>
                </g>

                <!-- Head Group -->
                <g id="catHead" style="transform-origin: 84px 72px;">
                  <!-- Back Ear -->
                  <path d="M96 36 L 106 16 L 114 38 Z" fill="#DF9554" stroke="#9B5B2A" stroke-width="1.4" stroke-linejoin="round"/>
                  <path d="M100 34 L 106 21 L 110 35 Z" fill="#F0A7A9"/>
                  <!-- Front Ear -->
                  <path d="M58 38 L 62 15 L 78 32 Z" fill="#F0AF70" stroke="#9B5B2A" stroke-width="1.4" stroke-linejoin="round"/>
                  <path d="M62 35 L 64 21 L 74 32 Z" fill="#F0A7A9"/>

                  <!-- Face Circle -->
                  <ellipse cx="86" cy="52" rx="25" ry="22" fill="url(#catFurGrad)" stroke="#9B5B2A" stroke-width="1.5"/>
                  <!-- Forehead Stripes -->
                  <path d="M84 32 L 85 38 M 90 33 L 90 38" stroke="#BC7235" stroke-width="2" stroke-linecap="round"/>
                  <!-- Cream Cheeks / Muzzle -->
                  <ellipse cx="95" cy="58" rx="14" ry="11" fill="#FFF7E8"/>

                  <!-- Eyes -->
                  <g id="catEyes">
                    <circle cx="84" cy="49" r="3.4" fill="#3B1D22"/>
                    <circle cx="85" cy="47.8" r="1.1" fill="#FFFFFF"/>
                    <circle cx="102" cy="49" r="3.2" fill="#3B1D22"/>
                    <circle cx="103" cy="47.8" r="1" fill="#FFFFFF"/>
                  </g>
                  <!-- Cute nose & smile -->
                  <polygon points="94,55 98,55 96,58.5" fill="#DF6A78"/>
                  <path d="M91 60 Q 94 63 96 59 Q 98 63 102 60" stroke="#6E3924" stroke-width="1.4" fill="none" stroke-linecap="round"/>
                  <!-- Cheek blush -->
                  <ellipse cx="77" cy="57" rx="4" ry="2.3" fill="#F29DA3" opacity="0.7"/>
                  <ellipse cx="108" cy="56" rx="3.4" ry="2.1" fill="#F29DA3" opacity="0.7"/>
                  <!-- Whiskers -->
                  <path d="M76 55 L 62 53 M 76 59 L 62 61" stroke="#8C5835" stroke-width="1.1" stroke-linecap="round"/>
                  <path d="M107 55 L 120 53 M 107 59 L 119 61" stroke="#8C5835" stroke-width="1.1" stroke-linecap="round"/>

                  <!-- Blue Postman Cap -->
                  <g id="catCap" style="transform-origin: 86px 34px;">
                    <path d="M65 34 C 66 19, 104 17, 108 32 Z" fill="url(#catBlueCapGrad)" stroke="#183858" stroke-width="1.5"/>
                    <!-- Gold hat band -->
                    <path d="M65 33 Q 87 30 108 32" stroke="#ECCD7F" stroke-width="2.6" fill="none"/>
                    <!-- Cap visor peaking forward -->
                    <path d="M84 32 Q 112 27 125 35 Q 110 38 86 35 Z" fill="#1D4368" stroke="#132E4A" stroke-width="1.3"/>
                    <!-- Tiny gold heart badge on cap -->
                    <circle cx="88" cy="25" r="4" fill="#ECCD7F" stroke="#8F631D" stroke-width="0.9"/>
                  </g>
                </g>

                <!-- Front Paws + Carried Envelope -->
                <g id="catCarryGroup">
                  <g id="catArmBack">
                    <path d="M98 84 Q 116 88 122 93" stroke="#D58E4F" stroke-width="9" stroke-linecap="round" fill="none"/>
                  </g>
                  <!-- Carried Mini Envelope -->
                  <g id="catHeldEnvelope" transform="translate(111, 74) rotate(-8)">
                    <rect id="miniEnvBody" x="0" y="0" width="44" height="30" rx="4" fill="#FCF3E1" stroke="#D4A351" stroke-width="1.8"/>
                    <path id="miniEnvFlap" d="M2 2 L 22 17 L 42 2" fill="none" stroke="#D4A351" stroke-width="1.6" stroke-linejoin="round"/>
                    <circle id="miniEnvSeal" cx="22" cy="15" r="4.5" fill="#BA293D"/>
                  </g>
                  <g id="catArmFront">
                    <path d="M88 86 Q 106 94 118 93" stroke="#F0AF70" stroke-width="9.5" stroke-linecap="round" fill="none"/>
                    <circle cx="118" cy="93" r="5" fill="#FFF7E8" stroke="#9B5B2A" stroke-width="1.1"/>
                  </g>
                </g>
              </svg>
            </div>

            <!-- Interactive Resting Envelope -->
            <div class="envelope-wrap" id="envelopeWrap">
              <button type="button" class="envelope-btn" id="btnOpenEnvelope" aria-label="Open love letter envelope">
                <div class="envelope-3d">
                  <div class="envelope-back">
                    <div class="envelope-peek-card">
                      <svg width="26" height="22" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                        <path d="M12 20s-7.4-4.7-9.3-9.2C1.4 8 3.2 4.6 6.7 4.6c2 0 3.7 1.1 5.3 2.9 1.6-1.8 3.3-2.9 5.3-2.9 3.5 0 5.3 3.4 4 6.6-1.9 4.5-9.3 9.2-9.3 9.2z" fill="#BA293D" opacity="0.8"/>
                      </svg>
                    </div>
                  </div>

                  <!-- Pocket geometric folds -->
                  <svg class="envelope-pocket-svg" viewBox="0 0 300 192" preserveAspectRatio="none" aria-hidden="true">
                    <!-- Left & right side flaps -->
                    <polygon points="0,0 132,96 0,192" fill="var(--env-pocket)" opacity="0.88"/>
                    <polygon points="300,0 168,96 300,192" fill="var(--env-pocket)" opacity="0.88"/>
                    <!-- Bottom triangular pocket -->
                    <polygon points="0,192 150,86 300,192" fill="var(--env-body)"/>
                    <polyline points="0,192 150,86 300,192" fill="none" stroke="var(--env-trim)" stroke-width="2"/>
                    <!-- Decorative postmark stamp -->
                    <g transform="translate(238, 16)">
                      <rect x="0" y="0" width="42" height="46" rx="4" fill="#FFFDF7" stroke="var(--env-trim)" stroke-width="1.5" stroke-dasharray="3 2"/>
                      <path d="M21 31s-8-5-10-9.8C9.6 17.8 11.4 14 15.2 14c2.1 0 4 1.2 5.8 3.1 1.8-1.9 3.7-3.1 5.8-3.1 3.8 0 5.6 3.8 4.2 7.2C29 26 21 31 21 31z" fill="#BA293D"/>
                      <path d="M-24 14 Q -14 10 -4 14 M -22 22 Q -12 18 -2 22" stroke="var(--env-trim)" stroke-width="1.4" fill="none" opacity="0.75"/>
                    </g>
                  </svg>

                  <!-- Top Flap -->
                  <div class="envelope-flap">
                    <svg viewBox="0 0 300 112" preserveAspectRatio="none" aria-hidden="true">
                      <path d="M2 2 L 298 2 L 156 105 Q 150 110 144 105 Z" fill="var(--env-flap)" stroke="var(--env-trim)" stroke-width="2.2" stroke-linejoin="round"/>
                    </svg>
                  </div>

                  <!-- Wax Seal -->
                  <div class="wax-seal" aria-hidden="true">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                      <path d="M12 20s-7.4-4.7-9.3-9.2C1.4 8 3.2 4.6 6.7 4.6c2 0 3.7 1.1 5.3 2.9 1.6-1.8 3.3-2.9 5.3-2.9 3.5 0 5.3 3.4 4 6.6-1.9 4.5-9.3 9.2-9.3 9.2z" fill="var(--seal-emblem)"/>
                    </svg>
                  </div>

                  <div class="tap-ripple" id="tapRipple"></div>

                  <div class="envelope-address">
                    <div class="env-to" id="envToText">For My Dearest</div>
                    <div class="env-from" id="envFromText">From Someone Who Loves You</div>
                  </div>
                </div>
              </button>
              <div class="envelope-shadow"></div>
              <div class="tap-prompt" id="tapPrompt">
                <span>Tap the envelope to open</span>
              </div>
            </div>
          </div>

          <div class="delivery-footer">
            <button type="button" class="btn-pill" id="btnDeliveryEdit">← Edit Letter</button>
          </div>
        </div>
      </section>

      <!-- ==================== VIEW 3: POP-UP CARD & HANDWRITTEN LETTER ==================== -->
      <section class="view" id="viewCard" aria-label="Pop-up love letter">
        <div class="keepsake-wrap">
          <div class="popup-card-frame" id="popupCardFrame">
            <div class="popup-card-inner">
              <!-- Top Half: 3D Paper Pop-Up Scene -->
              <div class="popup-diorama">
                <!-- Sky Backdrop: Moon + Gold Stars + Arch Frame -->
                <div class="diorama-sky-clip">
                  <svg class="diorama-sky-svg" viewBox="0 0 420 250" preserveAspectRatio="xMidYMax slice" aria-hidden="true">
                    <defs>
                      <radialGradient id="moonAura" cx="50%" cy="50%" r="50%">
                        <stop offset="0%" stop-color="#FFF5D6" stop-opacity="0.55"/>
                        <stop offset="55%" stop-color="#E8C97A" stop-opacity="0.18"/>
                        <stop offset="100%" stop-color="#E8C97A" stop-opacity="0"/>
                      </radialGradient>
                      <radialGradient id="moonDisc" cx="38%" cy="35%" r="65%">
                        <stop offset="0%" stop-color="#FFFDF5"/>
                        <stop offset="70%" stop-color="#F7E3AC"/>
                        <stop offset="100%" stop-color="#DFBA67"/>
                      </radialGradient>
                    </defs>

                    <!-- Gold Foil Decorative Arch Border -->
                    <path d="M14 248 L 14 78 C 14 28, 72 14, 210 14 C 348 14, 406 28, 406 78 L 406 248" fill="none" stroke="#E5C174" stroke-width="2" opacity="0.55"/>
                    <path d="M22 248 L 22 82 C 22 36, 78 22, 210 22 C 342 22, 398 36, 398 82 L 398 248" fill="none" stroke="#E5C174" stroke-width="1" stroke-dasharray="4 4" opacity="0.45"/>

                    <!-- Moon Glow & Full Moon -->
                    <circle cx="210" cy="76" r="68" fill="url(#moonAura)"/>
                    <circle cx="210" cy="76" r="33" fill="url(#moonDisc)"/>
                    <!-- Subtle Moon Craters -->
                    <circle cx="198" cy="68" r="6" fill="#DEC07A" opacity="0.28"/>
                    <circle cx="222" cy="84" r="4.5" fill="#DEC07A" opacity="0.24"/>
                    <circle cx="216" cy="64" r="3" fill="#DEC07A" opacity="0.22"/>

                    <!-- Twinkling Gold Foil Stars -->
                    <g fill="#F4D788">
                      <path class="star-twinkle" d="M68 58 L70 64 L76 66 L70 68 L68 74 L66 68 L60 66 L66 64 Z" style="transform-origin: 68px 66px;"/>
                      <path class="star-twinkle d2" d="M126 42 L127.6 46.5 L132 48 L127.6 49.5 L126 54 L124.4 49.5 L120 48 L124.4 46.5 Z" style="transform-origin: 126px 48px;"/>
                      <path class="star-twinkle d3" d="M294 42 L295.6 46.5 L300 48 L295.6 49.5 L294 54 L292.4 49.5 L288 48 L292.4 46.5 Z" style="transform-origin: 294px 48px;"/>
                      <path class="star-twinkle" d="M350 64 L352 70 L358 72 L352 74 L350 80 L348 74 L342 72 L348 70 Z" style="transform-origin: 350px 72px;"/>
                      <circle class="star-twinkle d2" cx="95" cy="96" r="2.1"/>
                      <circle class="star-twinkle d3" cx="152" cy="88" r="1.8"/>
                      <circle class="star-twinkle" cx="268" cy="88" r="1.8"/>
                      <circle class="star-twinkle d2" cx="322" cy="100" r="2.2"/>
                      <circle class="star-twinkle d3" cx="46" cy="106" r="1.7"/>
                      <circle class="star-twinkle" cx="374" cy="112" r="1.7"/>
                    </g>

                    <!-- Floating Gentle Hearts in Moonlit Sky -->
                    <g fill="#E14B5F" stroke="#F8DE94" stroke-width="0.6">
                      <path class="floating-heart" d="M148 134s-5.2-3.3-6.5-6.4c-.9-2.2.4-4.5 2.7-4.5 1.4 0 2.5.7 3.8 1.9 1.3-1.2 2.4-1.9 3.8-1.9 2.3 0 3.6 2.3 2.7 4.5-1.3 3.1-6.5 6.4-6.5 6.4z"/>
                      <path class="floating-heart fh2" d="M274 130s-4.4-2.8-5.5-5.4c-.8-1.9.3-3.8 2.3-3.8 1.2 0 2.1.6 3.2 1.6 1.1-1 2-1.6 3.2-1.6 2 0 3.1 1.9 2.3 3.8-1.1 2.6-5.5 5.4-5.5 5.4z"/>
                      <path class="floating-heart fh3" d="M188 118s-3.8-2.4-4.8-4.7c-.7-1.6.3-3.3 2-3.3 1 0 1.8.5 2.8 1.4 1-.9 1.8-1.4 2.8-1.4 1.7 0 2.7 1.7 2 3.3-1 2.3-4.8 4.7-4.8 4.7z" fill="#F3D283"/>
                      <path class="floating-heart fh4" d="M236 116s-3.8-2.4-4.8-4.7c-.7-1.6.3-3.3 2-3.3 1 0 1.8.5 2.8 1.4 1-.9 1.8-1.4 2.8-1.4 1.7 0 2.7 1.7 2 3.3-1 2.3-4.8 4.7-4.8 4.7z"/>
                    </g>
                  </svg>
                </div>

                <!-- Pop-Up Layer 1: Moonlit Paper Hillock & Arching Gold Foliage -->
                <div class="popup-plane plane-hill" aria-hidden="true">
                  <svg viewBox="0 0 420 250" preserveAspectRatio="xMidYMax slice">
                    <defs>
                      <filter id="paperCutShadow" x="-15%" y="-15%" width="130%" height="140%">
                        <feDropShadow dx="0" dy="4" stdDeviation="4" flood-color="#22070D" flood-opacity="0.34"/>
                      </filter>
                    </defs>
                    <g filter="url(#paperCutShadow)">
                      <!-- Back secondary hills -->
                      <path d="M0 250 L0 198 Q 85 162 172 192 Q 260 220 345 178 Q 390 158 420 176 L420 250 Z" fill="#D2A765" opacity="0.88"/>
                      <!-- Main Cream-Gold Center Hillock -->
                      <path d="M0 250 L0 212 Q 108 176 210 172 Q 312 176 420 212 L420 250 Z" fill="#F5E5C6" stroke="#D5A654" stroke-width="1.8"/>
                      <path d="M35 232 Q 210 182 385 232" fill="none" stroke="#D5A654" stroke-width="1" stroke-dasharray="4 4" opacity="0.65"/>
                    </g>
                  </svg>
                </div>

                <!-- Pop-Up Layer 2: Two Cats Sitting Together Under the Moon -->
                <div class="popup-plane plane-cats" aria-hidden="true">
                  <svg viewBox="0 0 420 250" preserveAspectRatio="xMidYMax slice">
                    <g filter="url(#paperCutShadow)" class="cats-alive">
                      <!-- Intertwined Heart-Shaped Tails behind/around the two cats -->
                      <path d="M168 205 C 128 200, 118 164, 146 154 C 166 147, 178 164, 178 178" fill="none" stroke="#E4A76D" stroke-width="8" stroke-linecap="round"/>
                      <path d="M168 205 C 128 200, 118 164, 146 154 C 166 147, 178 164, 178 178" fill="none" stroke="#FFF6E5" stroke-width="2" stroke-linecap="round" opacity="0.5"/>
                      <path d="M252 205 C 292 200, 302 164, 274 154 C 254 147, 242 164, 242 178" fill="none" stroke="#B66D72" stroke-width="8" stroke-linecap="round"/>
                      <path d="M252 205 C 292 200, 302 164, 274 154 C 254 147, 242 164, 242 178" fill="none" stroke="#FFF6E5" stroke-width="2" stroke-linecap="round" opacity="0.45"/>

                      <!-- Tiny glowing paper heart right between them -->
                      <path d="M210 132s-8.5-5.4-10.6-10.4c-1.4-3.5.7-7.2 4.4-7.2 2.2 0 4 1.2 6.2 3.2 2.2-2 4-3.2 6.2-3.2 3.7 0 5.8 3.7 4.4 7.2-2.1 5-10.6 10.4-10.6 10.4z" fill="#BA293D" stroke="#F8DE94" stroke-width="1.5"/>

                      <!-- LEFT CAT (Warm Cream & Cinnamon-Ginger) -->
                      <g transform="translate(158, 134)">
                        <!-- Body -->
                        <path d="M10 76 C 8 46, 16 32, 30 32 C 44 32, 52 46, 50 76 Z" fill="#F4C58D" stroke="#9B5B2A" stroke-width="1.5"/>
                        <ellipse cx="32" cy="56" rx="10" ry="15" fill="#FFF7EA"/>
                        <!-- Crimson Ribbon Scarf -->
                        <path d="M18 35 Q 30 41 42 35" stroke="#B8293D" stroke-width="4.5" stroke-linecap="round" fill="none"/>
                        <!-- Head tilted warmly toward right -->
                        <g transform="translate(2, 0) rotate(5 30 22)">
                          <polygon points="14,15 16,0 26,11" fill="#E8A565" stroke="#9B5B2A" stroke-width="1.4" stroke-linejoin="round"/>
                          <polygon points="34,11 44,0 46,15" fill="#E8A565" stroke="#9B5B2A" stroke-width="1.4" stroke-linejoin="round"/>
                          <ellipse cx="30" cy="22" rx="18" ry="15.5" fill="#F6CCA0" stroke="#9B5B2A" stroke-width="1.5"/>
                          <ellipse cx="34" cy="25" rx="9" ry="6.5" fill="#FFF7EA"/>
                          <!-- Happy peaceful curved eyes -->
                          <path d="M22 20 Q 25 17 28 20 M 36 20 Q 39 17 42 20" stroke="#4D2426" stroke-width="1.8" fill="none" stroke-linecap="round"/>
                          <polygon points="32,23 35,23 33.5,25.5" fill="#DE6C79"/>
                          <ellipse cx="21" cy="24" rx="3" ry="1.8" fill="#EF979D" opacity="0.7"/>
                        </g>
                      </g>

                      <!-- RIGHT CAT (Ivory-Blush with Cocoa-Rose Ears) -->
                      <g transform="translate(208, 138)">
                        <!-- Body -->
                        <path d="M8 72 C 6 44, 14 30, 28 30 C 42 30, 50 44, 48 72 Z" fill="#FFF8EE" stroke="#94565B" stroke-width="1.5"/>
                        <ellipse cx="26" cy="53" rx="9" ry="14" fill="#F8E2DC"/>
                        <!-- Gold Pendant Collar -->
                        <path d="M16 33 Q 28 39 40 33" stroke="#D4A351" stroke-width="3.2" stroke-linecap="round" fill="none"/>
                        <circle cx="28" cy="37" r="2.8" fill="#F7DC94" stroke="#8F631D" stroke-width="0.9"/>
                        <!-- Head tilted warmly toward left -->
                        <g transform="translate(-2, 0) rotate(-6 28 21)">
                          <polygon points="12,15 14,0 24,11" fill="#A65E64" stroke="#7A3C42" stroke-width="1.4" stroke-linejoin="round"/>
                          <polygon points="32,11 42,0 44,15" fill="#A65E64" stroke="#7A3C42" stroke-width="1.4" stroke-linejoin="round"/>
                          <ellipse cx="28" cy="21" rx="17" ry="15" fill="#FFF8EE" stroke="#94565B" stroke-width="1.5"/>
                          <path d="M18 20 Q 21 17 24 20 M 32 20 Q 35 17 38 20" stroke="#4D2426" stroke-width="1.8" fill="none" stroke-linecap="round"/>
                          <polygon points="24,23 27,23 25.5,25.5" fill="#DE6C79"/>
                          <ellipse cx="36" cy="24" rx="3" ry="1.8" fill="#EF979D" opacity="0.7"/>
                        </g>
                      </g>
                    </g>
                  </svg>
                </div>

                <!-- Pop-Up Layer 3: Layered Paper Flowers & Die-Cut Hearts -->
                <div class="popup-plane plane-flora" aria-hidden="true">
                  <svg viewBox="0 0 420 250" preserveAspectRatio="xMidYMax slice">
                    <g filter="url(#paperCutShadow)">
                      <!-- Paper-spring stems holding hearts -->
                      <path d="M98 220 Q 72 165 92 122" fill="none" stroke="#E5C174" stroke-width="2.2"/>
                      <path d="M322 220 Q 348 165 328 122" fill="none" stroke="#E5C174" stroke-width="2.2"/>
                      <path d="M126 226 Q 112 186 124 152" fill="none" stroke="#E5C174" stroke-width="1.8"/>
                      <path d="M294 226 Q 308 186 296 152" fill="none" stroke="#E5C174" stroke-width="1.8"/>

                      <!-- Paper-cutout Hearts on Springs -->
                      <path d="M92 132s-10.5-6.6-13.2-12.8c-1.8-4.4.8-9 5.5-9 2.8 0 5 1.5 7.7 4 2.7-2.5 4.9-4 7.7-4 4.7 0 7.3 4.6 5.5 9-2.7 6.2-13.2 12.8-13.2 12.8z" fill="#C22D42" stroke="#F8DE94" stroke-width="1.5"/>
                      <path d="M328 132s-10.5-6.6-13.2-12.8c-1.8-4.4.8-9 5.5-9 2.8 0 5 1.5 7.7 4 2.7-2.5 4.9-4 7.7-4 4.7 0 7.3 4.6 5.5 9-2.7 6.2-13.2 12.8-13.2 12.8z" fill="#C22D42" stroke="#F8DE94" stroke-width="1.5"/>
                      <path d="M124 160s-7.5-4.7-9.4-9.1c-1.3-3.1.6-6.4 3.9-6.4 2 0 3.6 1.1 5.5 2.8 1.9-1.7 3.5-2.8 5.5-2.8 3.3 0 5.2 3.3 3.9 6.4-1.9 4.4-9.4 9.1-9.4 9.1z" fill="#E8C26E" stroke="#FFF9EB" stroke-width="1.2"/>
                      <path d="M296 160s-7.5-4.7-9.4-9.1c-1.3-3.1.6-6.4 3.9-6.4 2 0 3.6 1.1 5.5 2.8 1.9-1.7 3.5-2.8 5.5-2.8 3.3 0 5.2 3.3 3.9 6.4-1.9 4.4-9.4 9.1-9.4 9.1z" fill="#E8C26E" stroke="#FFF9EB" stroke-width="1.2"/>

                      <!-- LEFT FLORAL CLUSTER (warm gold leaves + crimson & cream blossoms) -->
                      <g transform="translate(8, 175)">
                        <!-- Gold leaves -->
                        <path d="M22 65 Q 2 38 22 18 Q 38 40 22 65 Z" fill="#C79E4C" stroke="#8F631D" stroke-width="1"/>
                        <path d="M58 65 Q 72 34 94 28 Q 84 54 58 65 Z" fill="#B68B3C" stroke="#8F631D" stroke-width="1"/>
                        <path d="M98 70 Q 112 44 134 48 Q 120 66 98 70 Z" fill="#D1AA58" stroke="#8F631D" stroke-width="1"/>

                        <!-- Cream 5-petal flower -->
                        <g transform="translate(46, 44)">
                          <circle cx="0" cy="-12" r="9.5" fill="#FFF9EC" stroke="#D5A654" stroke-width="1.1"/>
                          <circle cx="11.5" cy="-3.5" r="9.5" fill="#FFF9EC" stroke="#D5A654" stroke-width="1.1"/>
                          <circle cx="7" cy="10" r="9.5" fill="#FFF9EC" stroke="#D5A654" stroke-width="1.1"/>
                          <circle cx="-7" cy="10" r="9.5" fill="#FFF9EC" stroke="#D5A654" stroke-width="1.1"/>
                          <circle cx="-11.5" cy="-3.5" r="9.5" fill="#FFF9EC" stroke="#D5A654" stroke-width="1.1"/>
                          <circle cx="0" cy="0" r="6" fill="#E2B254"/>
                        </g>

                        <!-- Layered Crimson Rose -->
                        <g transform="translate(86, 56)">
                          <circle cx="0" cy="0" r="17" fill="#A62034" stroke="#F4D788" stroke-width="1.2"/>
                          <path d="M-9 -4 C-9 -12, 9 -12, 9 -4 C9 4, -5 8, -5 0 C-5 -4, 4 -4, 4 0" fill="none" stroke="#F4B7BD" stroke-width="2" stroke-linecap="round"/>
                        </g>

                        <!-- Tiny cream bud -->
                        <circle cx="18" cy="52" r="9" fill="#BA293D" stroke="#F8DE94" stroke-width="1"/>
                        <circle cx="18" cy="52" r="3.5" fill="#F8DE94"/>
                      </g>

                      <!-- RIGHT FLORAL CLUSTER -->
                      <g transform="translate(274, 175)">
                        <path d="M116 65 Q 136 38 116 18 Q 100 40 116 65 Z" fill="#C79E4C" stroke="#8F631D" stroke-width="1"/>
                        <path d="M80 65 Q 66 34 44 28 Q 54 54 80 65 Z" fill="#B68B3C" stroke="#8F631D" stroke-width="1"/>
                        <path d="M40 70 Q 26 44 4 48 Q 18 66 40 70 Z" fill="#D1AA58" stroke="#8F631D" stroke-width="1"/>

                        <!-- Cream 5-petal flower -->
                        <g transform="translate(92, 44)">
                          <circle cx="0" cy="-12" r="9.5" fill="#FFF9EC" stroke="#D5A654" stroke-width="1.1"/>
                          <circle cx="11.5" cy="-3.5" r="9.5" fill="#FFF9EC" stroke="#D5A654" stroke-width="1.1"/>
                          <circle cx="7" cy="10" r="9.5" fill="#FFF9EC" stroke="#D5A654" stroke-width="1.1"/>
                          <circle cx="-7" cy="10" r="9.5" fill="#FFF9EC" stroke="#D5A654" stroke-width="1.1"/>
                          <circle cx="-11.5" cy="-3.5" r="9.5" fill="#FFF9EC" stroke="#D5A654" stroke-width="1.1"/>
                          <circle cx="0" cy="0" r="6" fill="#E2B254"/>
                        </g>

                        <!-- Layered Crimson Rose -->
                        <g transform="translate(52, 56)">
                          <circle cx="0" cy="0" r="17" fill="#A62034" stroke="#F4D788" stroke-width="1.2"/>
                          <path d="M-9 -4 C-9 -12, 9 -12, 9 -4 C9 4, -5 8, -5 0 C-5 -4, 4 -4, 4 0" fill="none" stroke="#F4B7BD" stroke-width="2" stroke-linecap="round"/>
                        </g>

                        <!-- Accent crimson blossom -->
                        <circle cx="120" cy="52" r="9" fill="#BA293D" stroke="#F8DE94" stroke-width="1"/>
                        <circle cx="120" cy="52" r="3.5" fill="#F8DE94"/>
                      </g>

                      <!-- Foreground scalloped paper trim along bottom fold -->
                      <path d="M0 250 L0 236 Q 35 224 70 236 Q 105 248 140 236 Q 175 224 210 236 Q 245 248 280 236 Q 315 224 350 236 Q 385 248 420 236 L420 250 Z" fill="#E8C680" opacity="0.65"/>
                    </g>
                  </svg>
                </div>
              </div>

              <!-- Center Paper Fold Crease -->
              <div class="card-crease" aria-hidden="true">
                <span class="crease-tab"></span>
                <span class="crease-tab"></span>
                <span class="crease-tab"></span>
              </div>

              <!-- Bottom Half: Handwritten Letter Message -->
              <div class="letter-sheet" id="letterSheet" title="Tap to reveal instantly while writing">
                <div class="letter-salutation" id="letterSalutation"></div>
                <div class="letter-body" id="letterBody"></div>
                <div class="letter-signature" id="letterSignature"></div>
                <div class="flourish-row" aria-hidden="true">
                  <svg width="74" height="24" viewBox="0 0 74 24" fill="none">
                    <path class="end-flourish-path" id="endFlourishPath" d="M4 15 C 18 19, 32 10, 44 13 C 50 15, 53 19, 58 17 C 61 15, 60 8, 56 8 C 52 8, 52 13, 57 17 C 62 13, 66 8, 62 6 C 59 5, 57 8, 57 11" stroke="#BA293D" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                </div>

                <!-- Animated Pen Nib Sparkle -->
                <svg class="pen-nib" id="penNib" viewBox="0 0 28 28" fill="none" aria-hidden="true">
                  <path d="M4 24 L 9 13 L 21 3 L 25 7 L 15 19 Z" fill="#D5A654" stroke="#6E1221" stroke-width="1.3" stroke-linejoin="round"/>
                  <path d="M4 24 L 12 16" stroke="#6E1221" stroke-width="1.1"/>
                  <circle cx="4" cy="24" r="2.2" fill="#BA293D"/>
                </svg>
              </div>
            </div>
          </div>

          <!-- Presentation / Replay Action Dock -->
          <div class="card-actions">
            <div class="actions-row">
              <button type="button" class="btn-replay" id="btnReplay">
                <svg width="19" height="19" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                  <path d="M4 12a8 8 0 1 0 2.3-5.6L4 8.7" stroke="#FFFDF8" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="M4 4v4.8h4.8" stroke="#F8DE94" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                <span>Replay Delivery</span>
              </button>
              <button type="button" class="btn-edit" id="btnEdit">
                <span>✎ Edit Letter</span>
              </button>
            </div>

            <div class="mini-style-bar" role="radiogroup" aria-label="Change paper style">
              <span class="mini-style-label">Paper:</span>
              <button type="button" class="mini-swatch is-selected" data-style="ivory" role="radio" aria-checked="true">
                <span class="mini-dot mini-dot--ivory"></span>
                <span>Ivory</span>
              </button>
              <button type="button" class="mini-swatch" data-style="crimson" role="radio" aria-checked="false">
                <span class="mini-dot mini-dot--crimson"></span>
                <span>Velvet</span>
              </button>
              <button type="button" class="mini-swatch" data-style="blush" role="radio" aria-checked="false">
                <span class="mini-dot mini-dot--blush"></span>
                <span>Blush</span>
              </button>
            </div>
          </div>
        </div>
      </section>
    </main>
  </div>

  <div class="demo-banner" id="demoBanner" hidden>
    <span class="demo-dot" aria-hidden="true"></span>
    <span>Preview Loop · Tap anywhere to write your own</span>
  </div>

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

      /* ================= SAFE STORAGE ================= */
      const STORAGE_KEY = 'love_letter_draft_v1';
      function safeGet(key) {
        try {
          return window.localStorage ? window.localStorage.getItem(key) : null;
        } catch (e) {
          return null;
        }
      }
      function safeSet(key, val) {
        try {
          if (window.localStorage) window.localStorage.setItem(key, val);
        } catch (e) {
          /* ignored inside sandboxed iframe */
        }
      }

      /* ================= SOFT CODE-SYNTHESIZED AUDIO ================= */
      const SoundEngine = (function () {
        let ctx = null;
        let master = null;
        let noiseBuffer = null;
        let muted = false;

        function ensureCtx() {
          if (muted) return null;
          try {
            const AudioCtx = window.AudioContext || window.webkitAudioContext;
            if (!AudioCtx) return null;
            if (!ctx) {
              ctx = new AudioCtx();
              master = ctx.createGain();
              master.gain.value = 0.55;
              master.connect(ctx.destination);
              noiseBuffer = createNoiseBuffer(ctx);
            }
            if (ctx.state === 'suspended') {
              ctx.resume().catch(function () {});
            }
            return ctx;
          } catch (e) {
            return null;
          }
        }

        function createNoiseBuffer(audioCtx) {
          const len = Math.floor(audioCtx.sampleRate * 0.5);
          const buf = audioCtx.createBuffer(1, len, audioCtx.sampleRate);
          const data = buf.getChannelData(0);
          for (let i = 0; i < len; i++) {
            data[i] = Math.random() * 2 - 1;
          }
          return buf;
        }

        function playTone(freqStart, freqEnd, duration, type, peakGain, delaySec) {
          const audioCtx = ensureCtx();
          if (!audioCtx || audioCtx.state !== 'running') return;
          try {
            const now = audioCtx.currentTime + (delaySec || 0);
            const osc = audioCtx.createOscillator();
            const gain = audioCtx.createGain();
            const filter = audioCtx.createBiquadFilter();

            osc.type = type || 'sine';
            osc.frequency.setValueAtTime(freqStart, now);
            if (freqEnd && freqEnd !== freqStart) {
              osc.frequency.exponentialRampToValueAtTime(Math.max(40, freqEnd), now + duration);
            }

            filter.type = 'lowpass';
            filter.frequency.setValueAtTime(2400, now);

            gain.gain.setValueAtTime(0.0001, now);
            gain.gain.linearRampToValueAtTime(peakGain, now + 0.014);
            gain.gain.exponentialRampToValueAtTime(0.0001, now + duration);

            osc.connect(filter);
            filter.connect(gain);
            gain.connect(master);

            osc.start(now);
            osc.stop(now + duration + 0.03);
          } catch (e) {}
        }

        function playPaperWhisper(duration, centerFreq, peakGain) {
          const audioCtx = ensureCtx();
          if (!audioCtx || audioCtx.state !== 'running' || !noiseBuffer) return;
          try {
            const now = audioCtx.currentTime;
            const src = audioCtx.createBufferSource();
            src.buffer = noiseBuffer;

            const filter = audioCtx.createBiquadFilter();
            filter.type = 'bandpass';
            filter.frequency.setValueAtTime(centerFreq, now);
            filter.Q.setValueAtTime(1.4, now);

            const gain = audioCtx.createGain();
            gain.gain.setValueAtTime(0.0001, now);
            gain.gain.linearRampToValueAtTime(peakGain, now + duration * 0.25);
            gain.gain.exponentialRampToValueAtTime(0.0001, now + duration);

            src.connect(filter);
            filter.connect(gain);
            gain.connect(master);

            src.start(now);
            src.stop(now + duration + 0.02);
          } catch (e) {}
        }

        const pentatonic = [523.25, 587.33, 659.25, 783.99, 880.0, 1046.5];

        return {
          unlock: function () {
            ensureCtx();
          },
          setMuted: function (isMuted) {
            muted = !!isMuted;
            if (master && ctx) {
              try {
                master.gain.setValueAtTime(muted ? 0 : 0.55, ctx.currentTime);
              } catch (e) {}
            }
          },
          isMuted: function () {
            return muted;
          },
          playTap: function () {
            playTone(520, 390, 0.055, 'sine', 0.08, 0);
          },
          playStyleSwitch: function (idx) {
            const freqs = [523.25, 587.33, 659.25];
            const f = freqs[idx % freqs.length];
            playTone(f, f * 1.01, 0.16, 'triangle', 0.075, 0);
          },
          playSend: function () {
            [523.25, 659.25, 783.99, 1046.5].forEach(function (f, i) {
              playTone(f, f, 0.34, 'triangle', 0.075, i * 0.075);
            });
          },
          playFootstep: function () {
            playTone(125, 64, 0.05, 'sine', 0.045, 0);
            playPaperWhisper(0.032, 950, 0.022);
          },
          playCatMew: function () {
            const audioCtx = ensureCtx();
            if (!audioCtx || audioCtx.state !== 'running') return;
            try {
              const now = audioCtx.currentTime;
              const osc = audioCtx.createOscillator();
              const gain = audioCtx.createGain();
              const filter = audioCtx.createBiquadFilter();

              osc.type = 'triangle';
              osc.frequency.setValueAtTime(510, now);
              osc.frequency.exponentialRampToValueAtTime(790, now + 0.08);
              osc.frequency.exponentialRampToValueAtTime(590, now + 0.24);

              filter.type = 'bandpass';
              filter.frequency.setValueAtTime(1150, now);
              filter.Q.setValueAtTime(1.5, now);

              gain.gain.setValueAtTime(0.0001, now);
              gain.gain.linearRampToValueAtTime(0.11, now + 0.04);
              gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.26);

              osc.connect(filter);
              filter.connect(gain);
              gain.connect(master);

              osc.start(now);
              osc.stop(now + 0.28);
            } catch (e) {}
          },
          playEnvelopeOpen: function () {
            playTone(260, 130, 0.08, 'sine', 0.09, 0);
            playPaperWhisper(0.24, 1750, 0.07);
          },
          playUnfoldChime: function () {
            const notes = [349.23, 440.0, 523.25, 659.25, 783.99, 1046.5];
            notes.forEach(function (f, i) {
              playTone(f, f, 0.72, 'sine', 0.068, i * 0.09);
            });
            playPaperWhisper(0.35, 1350, 0.045);
          },
          playPenTick: function (step) {
            playPaperWhisper(0.022, 2200, 0.022);
            if (step % 4 === 0) {
              const f = pentatonic[(step >> 2) % pentatonic.length];
              playTone(f, f, 0.14, 'sine', 0.02, 0);
            }
          },
          playFinishFlourish: function () {
            playTone(783.99, 783.99, 0.45, 'triangle', 0.06, 0);
            playTone(1046.5, 1046.5, 0.65, 'sine', 0.075, 0.14);
          }
        };
      })();

      /* ================= DOM REFERENCES ================= */
      const elBody = document.body;
      const viewCompose = document.getElementById('viewCompose');
      const viewDelivery = document.getElementById('viewDelivery');
      const viewCard = document.getElementById('viewCard');

      const btnSound = document.getElementById('btnSound');
      const soundIcon = document.getElementById('soundIcon');
      const soundLabel = document.getElementById('soundLabel');

      const inputTo = document.getElementById('inputTo');
      const inputFrom = document.getElementById('inputFrom');
      const inputMessage = document.getElementById('inputMessage');
      const charCount = document.getElementById('charCount');
      const composeHint = document.getElementById('composeHint');
      const btnSend = document.getElementById('btnSend');
      const btnClearDraft = document.getElementById('btnClearDraft');

      const styleSwatches = Array.from(document.querySelectorAll('[data-style]'));
      const presetButtons = Array.from(document.querySelectorAll('[data-preset]'));

      const catActor = document.getElementById('catActor');
      const catLegNear = document.getElementById('catLegNear');
      const catLegFar = document.getElementById('catLegFar');
      const catTail = document.getElementById('catTail');
      const catHead = document.getElementById('catHead');
      const catCap = document.getElementById('catCap');
      const catHeart = document.getElementById('catHeart');
      const catHeldEnvelope = document.getElementById('catHeldEnvelope');
      const miniEnvBody = document.getElementById('miniEnvBody');
      const miniEnvFlap = document.getElementById('miniEnvFlap');
      const miniEnvSeal = document.getElementById('miniEnvSeal');

      const envelopeWrap = document.getElementById('envelopeWrap');
      const btnOpenEnvelope = document.getElementById('btnOpenEnvelope');
      const tapRipple = document.getElementById('tapRipple');
      const tapPrompt = document.getElementById('tapPrompt');
      const envToText = document.getElementById('envToText');
      const envFromText = document.getElementById('envFromText');
      const btnDeliveryEdit = document.getElementById('btnDeliveryEdit');

      const popupCardFrame = document.getElementById('popupCardFrame');
      const letterSheet = document.getElementById('letterSheet');
      const letterSalutation = document.getElementById('letterSalutation');
      const letterBody = document.getElementById('letterBody');
      const letterSignature = document.getElementById('letterSignature');
      const endFlourishPath = document.getElementById('endFlourishPath');
      const penNib = document.getElementById('penNib');

      const btnReplay = document.getElementById('btnReplay');
      const btnEdit = document.getElementById('btnEdit');
      const demoBanner = document.getElementById('demoBanner');

      /* ================= APP STATE ================= */
      const STYLE_COLORS = {
        ivory: { body: '#FCF3E1', trim: '#D4A351', seal: '#BA293D' },
        crimson: { body: '#8E1B2D', trim: '#E7C67B', seal: '#D6A247' },
        blush: { body: '#F6DFD9', trim: '#CB9163', seal: '#A8253E' }
      };

      const PRESETS = {
        moon: {
          to: 'My Moonbeam',
          from: 'Yours Always',
          message: 'No matter how far apart we are tonight, we still share the same warm moon. Thank you for making every ordinary day glow.'
        },
        everyday: {
          to: 'Sweetheart',
          from: 'Your Admirer',
          message: 'Just a little note to remind you that my favorite place in the whole world is right next to you. You make my heart feel at home.'
        },
        forever: {
          to: 'My Love',
          from: 'Forever Yours',
          message: 'Every laugh, every quiet evening, every tiny moment with you is my dearest treasure. I love you more than words on paper can hold.'
        }
      };

      let currentStyle = 'ivory';
      let currentRunId = 0;
      let activeRaf = null;
      let activeTimers = [];
      let handwritingControls = null;

      let demoActive = false;
      let demoTimers = [];
      let demoLoopCount = 0;

      function clearScheduledRun() {
        currentRunId++;
        if (activeRaf !== null) {
          cancelAnimationFrame(activeRaf);
          activeRaf = null;
        }
        activeTimers.forEach(clearTimeout);
        activeTimers = [];
        handwritingControls = null;
      }

      function scheduleTimeout(fn, ms, runId) {
        const id = setTimeout(function () {
          if (runId !== undefined && runId !== currentRunId) return;
          fn();
        }, ms);
        activeTimers.push(id);
        return id;
      }

      /* ================= VIEW SWITCHING & PAPER STYLES ================= */
      function setView(viewEl) {
        [viewCompose, viewDelivery, viewCard].forEach(function (v) {
          v.classList.toggle('is-active', v === viewEl);
        });
      }

      function applyPaperStyle(styleId, playAudio) {
        if (!STYLE_COLORS[styleId]) styleId = 'ivory';
        currentStyle = styleId;
        elBody.setAttribute('data-paper', styleId);

        const palette = STYLE_COLORS[styleId];
        miniEnvBody.setAttribute('fill', palette.body);
        miniEnvBody.setAttribute('stroke', palette.trim);
        miniEnvFlap.setAttribute('stroke', palette.trim);
        miniEnvSeal.setAttribute('fill', palette.seal);

        styleSwatches.forEach(function (btn) {
          const match = btn.getAttribute('data-style') === styleId;
          btn.classList.toggle('is-selected', match);
          btn.setAttribute('aria-checked', match ? 'true' : 'false');
        });

        if (playAudio) {
          const idx = styleId === 'ivory' ? 0 : styleId === 'crimson' ? 1 : 2;
          SoundEngine.playStyleSwitch(idx);
        }
        persistDraft();
      }

      function updateCharCount() {
        charCount.textContent = inputMessage.value.length + ' / 220';
      }

      function persistDraft() {
        if (demoActive) return;
        safeSet(STORAGE_KEY, JSON.stringify({
          to: inputTo.value,
          from: inputFrom.value,
          message: inputMessage.value,
          style: currentStyle
        }));
      }

      function restoreDraft() {
        const raw = safeGet(STORAGE_KEY);
        if (!raw) return;
        try {
          const data = JSON.parse(raw);
          if (data && typeof data === 'object') {
            if (typeof data.to === 'string') inputTo.value = data.to.slice(0, 34);
            if (typeof data.from === 'string') inputFrom.value = data.from.slice(0, 34);
            if (typeof data.message === 'string') inputMessage.value = data.message.slice(0, 220);
            if (data.style && STYLE_COLORS[data.style]) applyPaperStyle(data.style, false);
          }
        } catch (e) {}
        updateCharCount();
      }

      function showHint(text) {
        composeHint.textContent = text;
        composeHint.classList.add('is-visible');
        setTimeout(function () {
          composeHint.classList.remove('is-visible');
        }, 2800);
      }

      /* ================= CAT POSTMAN DELIVERY ================= */
      function startDeliverySequence() {
        clearScheduledRun();
        const runId = currentRunId;

        const toVal = inputTo.value.trim();
        const fromVal = inputFrom.value.trim();
        envToText.textContent = toVal ? 'For ' + toVal : 'For My Dearest';
        envFromText.textContent = fromVal ? 'From ' + fromVal : 'With Love';

        // Reset delivery DOM
        envelopeWrap.classList.remove('is-landed', 'is-opening');
        tapPrompt.style.opacity = '1';
        tapRipple.classList.remove('is-pop');
        catHeldEnvelope.setAttribute('opacity', '1');
        catHeart.setAttribute('opacity', '0');
        catCap.setAttribute('transform', '');
        catActor.style.opacity = '1';

        setView(viewDelivery);

        const horizonWidth = Math.max(320, viewDelivery.clientWidth || window.innerWidth);
        const startX = -(horizonWidth * 0.5 + 115);
        const stopX = -88; // Centers cat nicely just left of the envelope drop spot
        const exitX = horizonWidth * 0.5 + 135;

        const walkInMs = 1950;
        const placeMs = 880;
        const walkOffMs = 1200;
        const totalMs = walkInMs + placeMs + walkOffMs;

        const t0 = performance.now();
        let lastStepTick = -1;
        let placed = false;
        let mewed = false;

        function animateCat(now) {
          if (runId !== currentRunId) return;
          const elapsed = now - t0;

          if (elapsed < walkInMs) {
            // Phase A: Brisk cheerful trot carrying envelope
            const p = elapsed / walkInMs;
            const eased = 1 - Math.pow(1 - p, 1.45);
            const x = startX + (stopX - startX) * eased;
            const stride = elapsed * 0.017;
            const bounce = Math.abs(Math.sin(stride)) * 6.5;

            catActor.style.transform = 'translate(' + x.toFixed(1) + 'px, ' + (-bounce).toFixed(1) + 'px)';
            catLegNear.style.transform = 'rotate(' + (Math.sin(stride) * 24).toFixed(1) + 'deg)';
            catLegFar.style.transform = 'rotate(' + (-Math.sin(stride) * 24).toFixed(1) + 'deg)';
            catTail.style.transform = 'rotate(' + (Math.sin(stride * 0.85) * 14).toFixed(1) + 'deg)';
            catHead.style.transform = 'rotate(' + (Math.sin(stride) * 2.5).toFixed(1) + 'deg)';

            const stepTick = Math.floor(stride / Math.PI);
            if (stepTick > lastStepTick) {
              lastStepTick = stepTick;
              SoundEngine.playFootstep();
            }
          } else if (elapsed < walkInMs + placeMs) {
            // Phase B: Cat pauses, sets envelope down in front, tips blue cap & mews
            const p = (elapsed - walkInMs) / placeMs;
            catLegNear.style.transform = 'rotate(0deg)';
            catLegFar.style.transform = 'rotate(0deg)';

            if (p > 0.22 && !placed) {
              placed = true;
              catHeldEnvelope.setAttribute('opacity', '0');
              envelopeWrap.classList.add('is-landed');
              SoundEngine.playTap();
            }

            if (p > 0.42 && !mewed) {
              mewed = true;
              SoundEngine.playCatMew();
            }

            // Cute cap tip & floating heart
            const bowAngle = p < 0.4 ? Math.sin((p / 0.4) * Math.PI) * 7 : 0;
            const capLift = p >= 0.4 ? Math.sin(((p - 0.4) / 0.6) * Math.PI) : 0;
            catActor.style.transform = 'translate(' + stopX + 'px, 0px)';
            catHead.style.transform = 'rotate(' + bowAngle.toFixed(1) + 'deg)';
            catCap.setAttribute('transform', 'translate(0, ' + (-capLift * 5).toFixed(1) + ') rotate(' + (-capLift * 10).toFixed(1) + ' 86 34)');
            catTail.style.transform = 'rotate(' + (Math.sin(elapsed * 0.012) * 16).toFixed(1) + 'deg)';

            const heartOpacity = p > 0.35 ? Math.sin(Math.min(1, (p - 0.35) / 0.65) * Math.PI) : 0;
            catHeart.setAttribute('opacity', heartOpacity.toFixed(2));
            catHeart.setAttribute('transform', 'translate(110, ' + (14 - p * 18).toFixed(1) + ')');
          } else if (elapsed < totalMs) {
            // Phase C: Cat trots happily off screen right
            const p = (elapsed - walkInMs - placeMs) / walkOffMs;
            const eased = p * p * (2 - p * 0.25);
            const x = stopX + (exitX - stopX) * p;
            const stride = elapsed * 0.019;
            const bounce = Math.abs(Math.sin(stride)) * 6.5;

            catHeart.setAttribute('opacity', '0');
            catCap.setAttribute('transform', '');
            catActor.style.transform = 'translate(' + x.toFixed(1) + 'px, ' + (-bounce).toFixed(1) + 'px)';
            catActor.style.opacity = p > 0.78 ? String(Math.max(0, 1 - (p - 0.78) / 0.22)) : '1';
            catLegNear.style.transform = 'rotate(' + (Math.sin(stride) * 26).toFixed(1) + 'deg)';
            catLegFar.style.transform = 'rotate(' + (-Math.sin(stride) * 26).toFixed(1) + 'deg)';
            catTail.style.transform = 'rotate(' + (Math.sin(stride) * 16).toFixed(1) + 'deg)';
            catHead.style.transform = 'rotate(' + (Math.sin(stride) * 2).toFixed(1) + 'deg)';

            const stepTick = Math.floor(stride / Math.PI);
            if (stepTick > lastStepTick) {
              lastStepTick = stepTick;
              if (p < 0.75) SoundEngine.playFootstep();
            }
          } else {
            catActor.style.opacity = '0';
            activeRaf = null;
            return;
          }

          activeRaf = requestAnimationFrame(animateCat);
        }

        activeRaf = requestAnimationFrame(animateCat);
      }

      /* ================= ENVELOPE OPEN & POP-UP CARD ================= */
      function openEnvelopeSequence() {
        if (!envelopeWrap.classList.contains('is-landed') || envelopeWrap.classList.contains('is-opening')) {
          return;
        }
        const runId = currentRunId;
        envelopeWrap.classList.add('is-opening');
        tapPrompt.style.opacity = '0';
        tapRipple.classList.remove('is-pop');
        void tapRipple.offsetWidth;
        tapRipple.classList.add('is-pop');

        SoundEngine.playEnvelopeOpen();

        scheduleTimeout(function () {
          showPopUpCard(runId);
        }, 760, runId);
      }

      function buildWordSpans(container, text) {
        container.textContent = '';
        const charNodes = [];
        const lines = text.split('\n');

        lines.forEach(function (line, lineIdx) {
          if (lineIdx > 0) {
            container.appendChild(document.createElement('br'));
          }
          // Split preserving runs of spaces vs words
          const tokens = line.match(/\S+|\s+/g) || [];
          tokens.forEach(function (token) {
            if (/^\s+$/.test(token)) {
              for (const ch of token) {
                const sp = document.createElement('span');
                sp.className = 'char space';
                sp.textContent = ch;
                container.appendChild(sp);
                charNodes.push(sp);
              }
            } else {
              const wordEl = document.createElement('span');
              wordEl.className = 'word-wrap';
              for (const ch of token) {
                const sp = document.createElement('span');
                sp.className = 'char';
                sp.textContent = ch;
                wordEl.appendChild(sp);
                charNodes.push(sp);
              }
              container.appendChild(wordEl);
            }
          });
        });

        return charNodes;
      }

      function showPopUpCard(runId) {
        popupCardFrame.classList.remove('is-unfolded');
        endFlourishPath.classList.remove('is-drawn');
        penNib.classList.remove('is-writing');
        letterSheet.scrollTop = 0;

        const toVal = inputTo.value.trim();
        const fromVal = inputFrom.value.trim();
        const msgVal = inputMessage.value.trim() || PRESETS.moon.message;

        const salutationText = toVal ? 'Dearest ' + toVal + ',' : 'My Dearest,';
        const signatureText = fromVal ? 'With love, ' + fromVal : 'With all my love';

        const salNodes = buildWordSpans(letterSalutation, salutationText);
        const bodyNodes = buildWordSpans(letterBody, msgVal);
        const sigNodes = buildWordSpans(letterSignature, signatureText);
        const allChars = salNodes.concat(bodyNodes, sigNodes);

        setView(viewCard);
        SoundEngine.playUnfoldChime();

        // Trigger 3D pop-up layers unfolding
        scheduleTimeout(function () {
          popupCardFrame.classList.add('is-unfolded');
        }, 70, runId);

        // Start letter-by-letter handwriting slightly after diorama begins rising
        scheduleTimeout(function () {
          startHandwriting(allChars, runId);
        }, 420, runId);
      }

      function startHandwriting(allChars, runId) {
        let idx = 0;
        let finished = false;
        const total = allChars.length;
        // Scale letter speed gently so even long letters complete crisply within ~5.5-7s
        const baseStepMs = Math.max(26, Math.min(68, Math.round(5200 / Math.max(1, total))));

        penNib.classList.add('is-writing');

        function movePenTo(node) {
          if (!node) return;
          const x = node.offsetLeft + node.offsetWidth;
          const y = node.offsetTop + node.offsetHeight * 0.68;
          penNib.style.left = x + 'px';
          penNib.style.top = y + 'px';

          // Gently keep pen nib visible inside scrollable letter sheet
          const visibleBottom = letterSheet.scrollTop + letterSheet.clientHeight - 28;
          if (y > visibleBottom) {
            letterSheet.scrollTop = Math.max(0, y - letterSheet.clientHeight + 40);
          }
        }

        function finishAll() {
          if (finished || runId !== currentRunId) return;
          finished = true;
          allChars.forEach(function (node) {
            node.classList.add('is-inked');
          });
          penNib.classList.remove('is-writing');
          endFlourishPath.classList.add('is-drawn');
          SoundEngine.playFinishFlourish();
          handwritingControls = null;
        }

        handwritingControls = { finishImmediately: finishAll };

        function step() {
          if (finished || runId !== currentRunId) return;
          if (idx >= total) {
            finishAll();
            return;
          }
          const chNode = allChars[idx];
          chNode.classList.add('is-inked');
          movePenTo(chNode);

          const ch = chNode.textContent;
          if (ch && !/^\s$/.test(ch)) {
            SoundEngine.playPenTick(idx);
          }

          idx++;
          let pause = baseStepMs;
          if (ch === '.' || ch === '!' || ch === '?') pause += baseStepMs * 2.2;
          else if (ch === ',') pause += baseStepMs * 1.1;

          scheduleTimeout(step, pause, runId);
        }

        step();
      }

      /* ================= INTERACTIVE HANDLERS ================= */
      btnSound.addEventListener('click', function () {
        const nextMuted = !SoundEngine.isMuted();
        SoundEngine.setMuted(nextMuted);
        btnSound.setAttribute('data-muted', String(nextMuted));
        soundIcon.textContent = nextMuted ? '🔇' : '🔊';
        soundLabel.textContent = nextMuted ? 'Muted' : 'Sound On';
        if (!nextMuted) {
          SoundEngine.unlock();
          SoundEngine.playTap();
        }
      });

      styleSwatches.forEach(function (btn) {
        btn.addEventListener('click', function () {
          SoundEngine.unlock();
          applyPaperStyle(btn.getAttribute('data-style'), true);
        });
      });

      presetButtons.forEach(function (btn) {
        btn.addEventListener('click', function () {
          SoundEngine.unlock();
          SoundEngine.playTap();
          const key = btn.getAttribute('data-preset');
          const p = PRESETS[key];
          if (!p) return;
          if (!inputTo.value.trim()) inputTo.value = p.to;
          if (!inputFrom.value.trim()) inputFrom.value = p.from;
          inputMessage.value = p.message;
          updateCharCount();
          persistDraft();
        });
      });

      btnClearDraft.addEventListener('click', function () {
        SoundEngine.unlock();
        SoundEngine.playTap();
        inputTo.value = '';
        inputFrom.value = '';
        inputMessage.value = '';
        updateCharCount();
        persistDraft();
      });

      [inputTo, inputFrom, inputMessage].forEach(function (el) {
        el.addEventListener('input', function () {
          updateCharCount();
          persistDraft();
        });
      });

      btnSend.addEventListener('click', function () {
        SoundEngine.unlock();
        if (!inputMessage.value.trim()) {
          SoundEngine.playTap();
          showHint('Write a short message above, or tap a sweet note pill!');
          inputMessage.focus();
          return;
        }
        SoundEngine.playSend();
        persistDraft();
        startDeliverySequence();
      });

      btnOpenEnvelope.addEventListener('click', function () {
        SoundEngine.unlock();
        openEnvelopeSequence();
      });

      letterSheet.addEventListener('click', function () {
        if (handwritingControls) {
          SoundEngine.unlock();
          handwritingControls.finishImmediately();
        }
      });

      btnReplay.addEventListener('click', function () {
        SoundEngine.unlock();
        SoundEngine.playSend();
        startDeliverySequence();
      });

      function goToEditor() {
        clearScheduledRun();
        SoundEngine.unlock();
        SoundEngine.playTap();
        setView(viewCompose);
      }

      btnEdit.addEventListener('click', goToEditor);
      btnDeliveryEdit.addEventListener('click', goToEditor);

      /* ================= #DEMO 20-SECOND HANDS-FREE LOOP ================= */
      function isDemoHash() {
        const hash = (window.location.hash || '').toLowerCase();
        const href = (window.location.href || '').toLowerCase();
        return hash === '#demo' || href.endsWith('#demo');
      }

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

      function clearDemoTimers() {
        demoTimers.forEach(clearTimeout);
        demoTimers = [];
      }

      function stopDemoOnRealTouch(e) {
        if (!demoActive) return;
        if (e && e.isTrusted === false) return;

        demoActive = false;
        clearDemoTimers();
        clearScheduledRun();

        window.removeEventListener('pointerdown', stopDemoOnRealTouch, true);
        window.removeEventListener('touchstart', stopDemoOnRealTouch, true);
        window.removeEventListener('mousedown', stopDemoOnRealTouch, true);
        window.removeEventListener('keydown', stopDemoOnRealTouch, true);

        demoBanner.hidden = true;
        SoundEngine.unlock();

        // Clear demo visuals & return cleanly to interactive composer
        [inputTo, inputFrom, inputMessage].forEach(function (el) {
          el.classList.remove('is-demo-focus');
        });
        btnSend.classList.remove('is-pressed');
        inputTo.value = '';
        inputFrom.value = '';
        inputMessage.value = '';
        restoreDraft();
        updateCharCount();
        setView(viewCompose);
      }

      function typeTextInto(inputEl, text, startMs, charMs) {
        inputEl.value = '';
        const chars = Array.from(text);
        scheduleDemo(function () {
          inputEl.classList.add('is-demo-focus');
        }, startMs);

        chars.forEach(function (ch, idx) {
          scheduleDemo(function () {
            inputEl.value += ch;
            if (inputEl === inputMessage) updateCharCount();
          }, startMs + 50 + idx * charMs);
        });

        scheduleDemo(function () {
          inputEl.classList.remove('is-demo-focus');
        }, startMs + 80 + chars.length * charMs);
      }

      function runDemoCycle() {
        if (!demoActive) return;
        clearDemoTimers();
        clearScheduledRun();

        const loopStyles = ['ivory', 'crimson', 'blush'];
        const chosenStyle = loopStyles[demoLoopCount % loopStyles.length];
        demoLoopCount++;

        // 0.0s: Reset to composer
        btnSend.classList.remove('is-pressed');
        inputTo.value = '';
        inputFrom.value = '';
        inputMessage.value = '';
        updateCharCount();
        applyPaperStyle('ivory', false);
        setView(viewCompose);

        // 0.4s - 1.4s: Showcase all 3 paper styles briefly
        scheduleDemo(function () { applyPaperStyle('crimson', false); }, 450);
        scheduleDemo(function () { applyPaperStyle('blush', false); }, 950);
        scheduleDemo(function () { applyPaperStyle(chosenStyle, false); }, 1450);

        // 1.75s - 4.0s: Fill To, From, Message
        typeTextInto(inputTo, 'Clara', 1750, 48);
        typeTextInto(inputFrom, 'Julian', 2100, 48);
        typeTextInto(
          inputMessage,
          'Two hearts beneath the same golden moon. Forever yours.',
          2480,
          28
        );

        // 4.25s: Press Send -> Cat Postman walks across & delivers envelope
        scheduleDemo(function () {
          btnSend.classList.add('is-pressed');
        }, 4250);

        scheduleDemo(function () {
          btnSend.classList.remove('is-pressed');
          startDeliverySequence();
        }, 4500);

        // 9.4s: Tap envelope to open pop-up scene + letter-by-letter writing
        scheduleDemo(function () {
          openEnvelopeSequence();
        }, 9400);

        // 19.9s: Restart ~20-second demo loop seamlessly
        scheduleDemo(function () {
          runDemoCycle();
        }, 19900);
      }

      function startDemoMode() {
        if (demoActive) return;
        demoActive = true;
        demoBanner.hidden = false;

        window.addEventListener('pointerdown', stopDemoOnRealTouch, true);
        window.addEventListener('touchstart', stopDemoOnRealTouch, true);
        window.addEventListener('mousedown', stopDemoOnRealTouch, true);
        window.addEventListener('keydown', stopDemoOnRealTouch, true);

        runDemoCycle();
      }

      /* ================= INITIALIZATION ================= */
      if (isDemoHash()) {
        startDemoMode();
      } else {
        restoreDraft();
        updateCharCount();
      }

      window.addEventListener('hashchange', function () {
        if (isDemoHash() && !demoActive) {
          startDemoMode();
        }
      });
    })();
  </script>
</body>
</html>