/* Mobile gift page · purpose-built for 420px width
   Sized for one-thumb scrolling, restacks the deck/transport, polaroid, CTAs. */

const MOBILE_JAM_PALETTES = {
  Roast:     { body: "#D4501A", bodyHighlight: "#FF7A3E", bodyShadow: "#8C2A0A", accent: "#D93616", labelTone: "warm" },
  Heartfelt: { body: "#C8553D", bodyHighlight: "#E87A60", bodyShadow: "#7A2A1C", accent: "#A8412E", labelTone: "warm" },
  Hype:      { body: "#F5C518", bodyHighlight: "#FFE873", bodyShadow: "#A88408", accent: "#D93616", labelTone: "neon" },
  Romantic:  { body: "#D85A8A", bodyHighlight: "#F590B5", bodyShadow: "#8A2E58", accent: "#A8412E", labelTone: "warm" },
};

function MobileDeckBtn({ children, onClick, active, label, flex }) {
  return (
    <button onClick={onClick} aria-label={label} style={{
      flex: flex || "0 0 auto",
      height: 48, minWidth: 48, padding: "0 10px", border: 0, borderRadius: 6,
      background: active ? "linear-gradient(180deg, #FF7A3E 0%, #D4501A 100%)" : "linear-gradient(180deg, #4a4a52 0%, #2a2a30 50%, #1a1a20 100%)",
      color: active ? "#fff" : "#FAEAC4",
      boxShadow: active
        ? "inset 0 -2px 0 rgba(0,0,0,0.4), inset 0 1px 0 rgba(255,255,255,0.25), 0 0 12px rgba(255,122,62,0.5)"
        : "inset 0 -2px 0 rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.12), 0 2px 4px rgba(0,0,0,0.3)",
      cursor: "pointer", display: "grid", placeItems: "center",
      fontFamily: "'JetBrains Mono', monospace", fontSize: 12, letterSpacing: "0.1em",
    }}>{children}</button>
  );
}

function MobileGiftPage({ song = {}, onMakeYourOwn, onWaitlist }) {
  const [mCopied, setMCopied] = React.useState(false);
  const [mSide, setMSide] = React.useState("A");
  const mCopy = React.useCallback(() => {
    const url = window.location.href;
    if (navigator.clipboard?.writeText) {
      navigator.clipboard.writeText(url).then(() => {
        setMCopied(true);
        setTimeout(() => setMCopied(false), 1800);
      }).catch(() => {});
    }
  }, []);
  const {
    recipient = "Maya",
    title = "The Ballad of May-May",
    occasion = "30th birthday",
    senderName = "Jess",
    senderMessage = "Happy 30th, weirdo. You deserve to be sung about.",
    songType = "Roast",
    genre = "Pop anthem",
    duration = 54,
    lyrics: lyricsRaw,
  } = song;

  const palette = MOBILE_JAM_PALETTES[songType] || MOBILE_JAM_PALETTES.Roast;
  const [playing, setPlaying] = React.useState(false);
  const [t, setT] = React.useState(0);
  const [scrubbing, setScrubbing] = React.useState(false);
  const audioRef = React.useRef(null);
  const audioSrc = song.audioUrl || (typeof SAMPLE_AUDIO !== "undefined" ? SAMPLE_AUDIO[songType] : null) || "data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQAAAAA=";
  const simulateAudio = /^data:audio\//.test(audioSrc || "");

  React.useEffect(() => {
    const a = audioRef.current;
    if (!a || simulateAudio) return;
    if (playing) a.play().catch(() => setPlaying(false));
    else a.pause();
  }, [playing, simulateAudio]);

  React.useEffect(() => {
    if (!playing || !simulateAudio) return undefined;
    const timer = setInterval(() => {
      setT((current) => {
        const next = Math.min(duration, current + 0.25);
        if (next >= duration) {
          setPlaying(false);
          return 0;
        }
        return next;
      });
    }, 250);
    return () => clearInterval(timer);
  }, [duration, playing, simulateAudio]);

  React.useEffect(() => {
    const a = audioRef.current;
    if (!a || simulateAudio) return;
    const onTime = () => {
      const cur = Math.min(a.currentTime, duration);
      setT(cur);
      if (a.currentTime >= duration) { a.pause(); setPlaying(false); }
    };
    const onEnd = () => { setPlaying(false); setT(0); };
    a.addEventListener("timeupdate", onTime);
    a.addEventListener("ended", onEnd);
    return () => { a.removeEventListener("timeupdate", onTime); a.removeEventListener("ended", onEnd); };
  }, [duration, simulateAudio]);

  const seek = React.useCallback((newT) => {
    const clamped = Math.max(0, Math.min(duration, newT));
    setT(clamped);
    if (audioRef.current) audioRef.current.currentTime = clamped;
  }, [duration]);
  const scrubToPointer = React.useCallback((e) => {
    const r = e.currentTarget.getBoundingClientRect();
    const next = ((e.clientX - r.left) / r.width) * duration;
    seek(next);
    setMSide(next / duration >= 0.52 ? "B" : "A");
  }, [duration, seek]);

  const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
  const progress = t / duration;
  const cassetteTraits = createPrototypeCassetteTraits({
    seed: song.giftSlug || `${recipient}-${occasion}-${title}`,
    recipient,
    occasion,
    title,
    songType,
    genre,
    tier: song.tier || "quick",
    durationSeconds: duration,
  });
  const cassetteMeta = cassetteTraits.label.meta;
  const lyrics = lyricsRaw || `[Verse 1]
She rolls in twenty minutes late...
(no lyrics provided)`;
  const mSides = React.useMemo(() => {
    const lines = lyrics.split("\n");
    const bridgeIdx = lines.findIndex(l => /\[Bridge\]/i.test(l));
    if (bridgeIdx < 0) return { A: lyrics, B: "(B-side coming soon...)" };
    return {
      A: lines.slice(0, bridgeIdx).join("\n").trim(),
      B: lines.slice(bridgeIdx).join("\n").trim(),
    };
  }, [lyrics]);

  return (
    <div style={{ background: "var(--paper)", color: "var(--ink)", minHeight: "100vh" }}>
      <audio ref={audioRef} src={audioSrc} preload="metadata" crossOrigin="anonymous"/>
      {/* Top bar */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 20px", borderBottom: "1px solid var(--line)" }}>
        <Logo size={20}/>
        <div style={{ fontFamily: "var(--f-mono)", fontSize: 9, letterSpacing: "0.08em", opacity: 0.55 }}>
          PRIVATE · /jam/{recipient.toLowerCase()}
        </div>
      </div>

      {/* Hero title block */}
      <section style={{ padding: "32px 20px 20px", textAlign: "center" }}>
        <span className="tape" style={{ fontSize: 9, letterSpacing: "0.14em" }}>
          A SONG FROM {senderName.toUpperCase()} · FOR {recipient.toUpperCase()}
        </span>
        <h1 className="display" style={{
          fontSize: 36, lineHeight: 1.05, margin: "14px 0 8px",
          textWrap: "balance", fontFamily: "var(--f-italic)", fontStyle: "italic",
          color: palette.accent,
        }}>
          "{title}"
        </h1>
        <p style={{ fontSize: 11, opacity: 0.7, fontFamily: "var(--f-mono)", letterSpacing: "0.08em" }}>
          {cassetteMeta}
        </p>
      </section>

      {/* The deck — sized for 420 */}
      <section style={{ padding: "0 16px" }}>
        <div className={playing ? "ij-gift-deck is-playing" : "ij-gift-deck"} style={{
          padding: "18px 14px 16px",
          borderRadius: 16,
          background: "linear-gradient(180deg, #2a2a32 0%, #15151a 50%, #2a2a32 100%)",
          boxShadow: "0 1px 0 rgba(255,255,255,0.08) inset, 0 18px 36px -18px rgba(0,0,0,0.55)",
          position: "relative",
        }}>
          {/* Brand strip + VUs */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
            <div style={{ fontFamily: "var(--f-mono)", fontSize: 8, letterSpacing: "0.16em", color: "#FAEAC4", opacity: 0.5 }}>
              INSIDEJAMS · STEREO
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              <VUMeter w={62} h={28} level={playing ? 0.5 + Math.sin(t * 1.7) * 0.25 : 0.05} label="L"/>
              <VUMeter w={62} h={28} level={playing ? 0.55 + Math.cos(t * 1.4) * 0.2 : 0.05} label="R"/>
            </div>
          </div>

          {/* Cassette bay */}
          <div style={{
            padding: "16px 12px",
            background: "linear-gradient(180deg, #08080c 0%, #1a1a20 100%)",
            borderRadius: 10,
            boxShadow: "inset 0 4px 14px rgba(0,0,0,0.7), inset 0 -2px 0 rgba(255,255,255,0.04)",
            display: "flex", justifyContent: "center",
          }}>
            <div style={{ filter: "drop-shadow(0 2px 0 rgba(0,0,0,0.4))", width: "100%", maxWidth: "100%", minWidth: 0 }}>
              <GiftPlayer3D
                traits={cassetteTraits}
                playing={playing}
                progress={progress}
                duration={duration}
                scrubbing={scrubbing}
                compact
              />
            </div>
          </div>

          {/* Scrubber */}
          <div style={{
            marginTop: 14, padding: "10px 12px",
            background: "linear-gradient(180deg, #08080c 0%, #1a1a20 100%)",
            borderRadius: 8, boxShadow: "inset 0 2px 6px rgba(0,0,0,0.6)",
          }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--f-mono)", fontSize: 10, color: "#FAEAC4", letterSpacing: "0.1em", marginBottom: 6 }}>
              <span>{fmt(t)}</span>
              <span style={{ opacity: 0.6 }}>{fmt(duration)}</span>
            </div>
            <div
              className={scrubbing ? "ij-tape-scrubber is-scrubbing" : "ij-tape-scrubber"}
              style={{ height: 6, background: "rgba(255,255,255,0.08)", borderRadius: 3, position: "relative", cursor: "grab", touchAction: "none" }}
              onPointerDown={(e) => {
                e.currentTarget.setPointerCapture?.(e.pointerId);
                setScrubbing(true);
                scrubToPointer(e);
              }}
              onPointerMove={(e) => {
                if (scrubbing) scrubToPointer(e);
              }}
              onPointerUp={() => setScrubbing(false)}
              onPointerCancel={() => setScrubbing(false)}>
              <div style={{ position: "absolute", inset: 0, width: `${progress * 100}%`, background: `linear-gradient(90deg, ${palette.accent} 0%, ${palette.bodyHighlight} 100%)`, borderRadius: 3, boxShadow: `0 0 8px ${palette.accent}` }}/>
              <div style={{ position: "absolute", left: `${progress * 100}%`, top: -4, width: 14, height: 14, borderRadius: "50%", background: "#FAEAC4", transform: "translateX(-50%)", boxShadow: "0 2px 4px rgba(0,0,0,0.5)" }}/>
            </div>
          </div>

          {/* Transport row */}
          <div style={{ marginTop: 12, display: "flex", gap: 6 }}>
            <MobileDeckBtn label="Rewind" onClick={() => seek(t - 10)} flex="1 1 0">◀◀</MobileDeckBtn>
            <MobileDeckBtn label="Play" onClick={() => setPlaying(!playing)} active={playing} flex="2 1 0">
              {playing ? "❚❚ PAUSE" : "▶ PLAY"}
            </MobileDeckBtn>
            <MobileDeckBtn label="Stop" onClick={() => { setPlaying(false); seek(0); }} flex="1 1 0">■</MobileDeckBtn>
            <MobileDeckBtn label="Fast forward" onClick={() => seek(t + 10)} flex="1 1 0">▶▶</MobileDeckBtn>
          </div>
        </div>
      </section>

      {/* Action buttons — restacked under deck */}
      <section style={{ padding: "20px 20px 0", display: "flex", flexDirection: "column", gap: 10 }}>
        <button className="btn primary" style={{ background: palette.accent, borderColor: palette.accent, justifyContent: "center", padding: "13px 16px", fontSize: 14 }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M7 1.5 L7 9.5 M3.5 6 L7 9.5 L10.5 6 M2 12 L12 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
          Download MP3
        </button>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn ghost" onClick={mCopy} style={{ flex: 1, justifyContent: "center", padding: "11px 12px", fontSize: 13 }}>{mCopied ? "✓ Copied" : "Copy link"}</button>
          <button className="btn ghost" onClick={() => {
            if (navigator.share) {
              navigator.share({ title: `A song for ${recipient}`, text: `${senderName} made you a song`, url: window.location.href }).catch(() => {});
            } else {
              mCopy();
            }
          }} style={{ flex: 1, justifyContent: "center", padding: "11px 12px", fontSize: 13 }}>Share</button>
        </div>
      </section>

      {/* Sender note · polaroid */}
      <section style={{ padding: "32px 20px 0", display: "flex", justifyContent: "center" }}>
        <div style={{
          background: "#fff",
          padding: "16px 18px 22px",
          transform: "rotate(-1.5deg)",
          boxShadow: "0 12px 30px -10px rgba(0,0,0,0.25)",
          border: "1px solid rgba(0,0,0,0.08)",
          maxWidth: 340,
          color: "#1A1A24",
        }}>
          <span style={{ fontFamily: "var(--f-mono)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: palette.accent, opacity: 0.85 }}>
            A note from {senderName}
          </span>
          <p className="display" style={{ fontFamily: "var(--f-italic)", fontSize: 18, fontStyle: "italic", lineHeight: 1.35, marginTop: 8, color: "#1A1A24" }}>
            "{senderMessage}"
          </p>
        </div>
      </section>

      <section style={{ padding: "28px 20px 0" }}>
        <div className={scrubbing ? "ij-lyrics-sync is-scrubbing" : "ij-lyrics-sync"} style={{
          padding: "18px 18px 20px",
          borderRadius: 14,
          border: "1.5px solid var(--line-strong)",
          background: "var(--paper-2)",
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12 }}>
            <div>
              <span className="eyebrow" style={{ fontSize: 9 }}>Lyric sheet</span>
              <div className="display" style={{ fontFamily: "var(--f-italic)", fontStyle: "italic", fontSize: 24, marginTop: 5 }}>Side {mSide}</div>
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              {["A", "B"].map(s => (
                <button key={s} onClick={() => setMSide(s)} className={mSide === s ? "chip solid" : "chip"} style={{
                  cursor: "pointer",
                  padding: "5px 9px",
                  fontSize: 9,
                  borderColor: mSide === s ? palette.accent : "var(--line-strong)",
                  background: mSide === s ? palette.accent : "transparent",
                  color: mSide === s ? "#fff" : "var(--ink)",
                }}>Side {s}</button>
              ))}
            </div>
          </div>
          <pre style={{
            margin: "14px 0 0",
            whiteSpace: "pre-wrap",
            fontFamily: "var(--f-sans)",
            fontSize: 15,
            lineHeight: 1.65,
            color: "var(--ink)",
          }}>{mSides[mSide]}</pre>
        </div>
      </section>

      <section style={{ padding: "18px 20px 0" }}>
        <div style={{
          minWidth: 0,
          padding: "18px 18px 20px",
          borderRadius: 14,
          background: "#15151a",
          color: "#FAEAC4",
          boxShadow: "0 1px 0 rgba(255,255,255,0.08) inset, 0 16px 34px -24px rgba(0,0,0,0.55)",
        }}>
          <span style={{
            fontFamily: "var(--f-mono)",
            fontSize: 9,
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            opacity: 0.65,
          }}>Keepsake notes</span>
          <p style={{
            margin: "12px 0 0",
            fontSize: 14,
            lineHeight: 1.55,
            opacity: 0.84,
            overflowWrap: "anywhere",
          }}>
            This private page is unlisted and made for sharing by link. Save the MP3, keep the lyrics, or send it when the moment is right.
          </p>
          <div style={{ marginTop: 16, display: "flex", flexWrap: "wrap", gap: 7, maxWidth: "100%" }}>
            {["UNLISTED", "MP3", "LYRICS", "NO ACCOUNT"].map(t => (
              <span key={t} style={{
                maxWidth: "100%",
                fontFamily: "var(--f-mono)",
                fontSize: 8,
                letterSpacing: "0.08em",
                padding: "5px 8px",
                borderRadius: 999,
                border: "1px solid rgba(250,234,196,0.25)",
                overflowWrap: "anywhere",
              }}>{t}</span>
            ))}
          </div>
        </div>
      </section>

      <section style={{ padding: "18px 20px 0" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          {[
            ["Made for", recipient],
            ["From", senderName],
            ["Occasion", occasion],
            ["Page", "Private"],
          ].map(([label, value]) => (
            <div key={label} style={{ padding: "10px 11px", border: "1px solid var(--line)", borderRadius: 10, background: "var(--paper-2)" }}>
              <div style={{ fontFamily: "var(--f-mono)", fontSize: 8, letterSpacing: "0.1em", textTransform: "uppercase", opacity: 0.55 }}>{label}</div>
              <div style={{ marginTop: 3, fontSize: 13, fontWeight: 700, overflowWrap: "anywhere" }}>{value}</div>
            </div>
          ))}
        </div>
      </section>

      {/* CTA */}
      <section style={{ padding: "56px 20px 32px", textAlign: "center" }}>
        <div className="display" style={{ fontSize: 28, lineHeight: 1.15, fontFamily: "var(--f-italic)", fontStyle: "italic", textWrap: "balance" }}>
          Got someone <em>else</em> in mind?
        </div>
        <p style={{ fontSize: 14, opacity: 0.7, marginTop: 10 }}>
          Make your own InsideJam. Starts at $29 with a private gift page.
        </p>
        <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 22 }}>
          <button className="btn primary" onClick={onMakeYourOwn} style={{ justifyContent: "center", padding: "13px 16px", fontSize: 14 }}>
            Start their jam →
          </button>
          <button className="btn ghost" onClick={onWaitlist} style={{ justifyContent: "center", padding: "11px 16px", fontSize: 13 }}>
            Card waitlist →
          </button>
        </div>
      </section>

      <footer style={{ padding: "24px 20px 28px", textAlign: "center", fontFamily: "var(--f-mono)", fontSize: 10, letterSpacing: "0.08em", opacity: 0.55, borderTop: "1px solid var(--line)" }}>
        UNLISTED · NOT INDEXED · INSIDEJAMS © 2026
      </footer>
    </div>
  );
}

Object.assign(window, { MobileGiftPage });
