/* Pre-check + Checkout flow */

function PreCheck({ onContinue, onBack, mood }) {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    recipient: "Maya",
    relationship: "Best friend",
    occasion: "30th birthday",
    songType: "Roast",
    tier: "Quick",
    tone: "Medium",
  });
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

  const songTypes = [
    { name: "Roast", desc: "Funny, sharp, group-chat energy", color: "var(--tangerine)" },
    { name: "Heartfelt", desc: "Sincere, emotional, gift-y", color: "#C8553D" },
    { name: "Hype", desc: "Make them feel legendary", color: "var(--honey)" },
    { name: "Romantic", desc: "Anniversary / Valentine's energy", color: "#E8779B" },
    { name: "Birthday/Holiday", desc: "Custom seasonal gift", color: "#5C9EAD" },
    { name: "Business", desc: "Team, brand, or commercial use", color: "var(--pool)" },
    { name: "Other", desc: "Tell us the brief", color: "var(--ink)" },
  ];

  const showRoast = ["Roast"].includes(data.songType);
  const requiresPolished = data.songType === "Business";
  const recommendedPolished = ["Heartfelt", "Romantic"].includes(data.songType) || requiresPolished;
  React.useEffect(() => {
    if (recommendedPolished && data.tier !== "Polished") set("tier", "Polished");
  }, [recommendedPolished, data.tier]);

  return (
    <div style={{ minHeight: "100vh", background: "var(--paper)", color: "var(--ink)" }}>
      <nav className="ij-precheck-nav" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 40px", borderBottom: "1px solid var(--line)" }}>
        <Logo/>
        <button className="btn ghost small" onClick={onBack}>← Back to home</button>
      </nav>

      <div className="ij-precheck-shell" style={{ maxWidth: 720, margin: "0 auto", padding: "60px 40px 100px" }}>
        <div style={{ display: "flex", gap: 8, marginBottom: 30 }}>
          {[0,1,2,3].map(i => (
            <div key={i} style={{ flex: 1, height: 4, background: i <= step ? "var(--tangerine)" : "var(--line-strong)", borderRadius: 2, transition: "background .2s var(--ease-out), transform .2s var(--ease-out)", transform: i === step ? "scaleY(1.65)" : "scaleY(1)", transformOrigin: "center" }}/>
          ))}
        </div>
        <span className="eyebrow">Step {step+1} of 4 · Find the right song gift</span>

        {step === 0 && (
          <div className="appear">
            <h1 className="display" style={{ fontSize: 56, margin: "16px 0 8px" }}>
              Who's this <em>for</em>?
            </h1>
            <p style={{ fontSize: 17, opacity: 0.75, marginBottom: 36, maxWidth: 540 }}>
              We only need enough to recommend the right tier. The deep story details unlock after checkout through your private intake link.
            </p>
            <div className="ij-precheck-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              <div className="field"><label>Recipient first name</label><input value={data.recipient} onChange={e => set("recipient", e.target.value)}/></div>
              <div className="field"><label>Your relationship</label><input value={data.relationship} onChange={e => set("relationship", e.target.value)} placeholder="Best friend, mom, partner…"/></div>
              <div className="field ij-span-all" style={{ gridColumn: "1 / -1" }}><label>Occasion</label><input value={data.occasion} onChange={e => set("occasion", e.target.value)} placeholder="30th birthday, anniversary, fantasy league punishment"/></div>
            </div>
          </div>
        )}

        {step === 1 && (
          <div className="appear">
            <h1 className="display" style={{ fontSize: 56, margin: "16px 0 8px" }}>
              What should the <em>song do</em>?
            </h1>
            <p style={{ fontSize: 17, opacity: 0.75, marginBottom: 36 }}>Pick the emotional job. You can refine the genre, details, and tone after checkout.</p>
            <div className="ij-precheck-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              {songTypes.map(t => (
                <button key={t.name} className="choice-card" onClick={() => set("songType", t.name)} style={{
                  textAlign: "left", padding: "20px 22px", borderRadius: 16,
                  border: data.songType === t.name ? `1.5px solid var(--ink)` : `1.5px solid var(--line-strong)`,
                  background: data.songType === t.name ? "var(--paper-2)" : "var(--paper)",
                  color: "var(--ink)",
                  cursor: "pointer",
                  display: "flex", alignItems: "center", gap: 16,
                }}>
                  <span style={{ width: 14, height: 14, borderRadius: 999, background: t.color, flexShrink: 0 }}/>
                  <div>
                    <div className="display" style={{ fontSize: 22, fontStyle: "italic" }}>{t.name}</div>
                    <div style={{ fontSize: 13, opacity: 0.65, marginTop: 2 }}>{t.desc}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>
        )}

        {step === 2 && (
          <div className="appear">
            <h1 className="display" style={{ fontSize: 56, margin: "16px 0 8px" }}>
              Quick or <em>polished</em>?
            </h1>
            <p style={{ fontSize: 17, opacity: 0.75, marginBottom: 20 }}>
              {recommendedPolished
                ? requiresPolished
                  ? "Business and commercial songs use Polished Jam so the lyrics, usage, and audio quality get a human pass before delivery."
                  : "Quick Jam works great for simple, fun gifts. For emotional or highly specific songs, we recommend Polished Jam for better lyrics, structure, and quality review."
                : "Both work. Pick the one that fits your timeline and budget."}
            </p>
            <div className="ij-tier-helper" style={{ marginBottom: 20, display: "flex", gap: 8, flexWrap: "wrap" }}>
              <span className="chip">Quick = fast laugh</span>
              <span className="chip">Polished = keepsake</span>
              <span className="chip accent">No account required</span>
            </div>
            <div className="ij-precheck-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              {[
                { tier: "Quick", price: 29, length: "45-60 sec", time: "Under 10 min", body: "Fast, funny, perfect for tonight's group chat. No promised human review.", disabled: requiresPolished },
                { tier: "Polished", price: 69, length: "90-120 sec", time: "Within 24 hr", body: "Human-polished lyrics, deeper personalization, audio QA, and one minor revision.", recommended: recommendedPolished },
              ].map(t => (
                <button key={t.tier} className="choice-card" disabled={t.disabled} onClick={() => !t.disabled && set("tier", t.tier)} style={{
                  textAlign: "left", padding: 24, borderRadius: 16,
                  border: data.tier === t.tier ? "1.5px solid var(--ink)" : "1.5px solid var(--line-strong)",
                  background: data.tier === t.tier ? (t.tier === "Polished" ? "var(--ink)" : "var(--paper-2)") : "var(--paper)",
                  color: data.tier === t.tier && t.tier === "Polished" ? "var(--paper)" : "var(--ink)",
                  cursor: t.disabled ? "not-allowed" : "pointer",
                  opacity: t.disabled ? 0.68 : 1,
                  position: "relative",
                }}>
                  {t.recommended && <span className="tape" style={{ position: "absolute", top: -10, right: 14 }}>{requiresPolished ? "Required" : "Best fit"}</span>}
                  <div className="display" style={{ fontSize: 28 }}>{t.tier} Jam</div>
                  <div className="display" style={{ fontSize: 56, marginTop: 4 }}>${t.price}</div>
                  <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.08em", opacity: 0.7, marginTop: 8 }}>
                    {t.length.toUpperCase()} · {t.time.toUpperCase()}
                  </div>
                  <p style={{ fontSize: 14, opacity: 0.85, marginTop: 14, lineHeight: 1.5 }}>{t.disabled ? "Business and commercial use starts with Polished Jam." : t.body}</p>
                </button>
              ))}
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="appear">
            <h1 className="display" style={{ fontSize: 56, margin: "16px 0 8px" }}>
              {showRoast ? <>How <em>spicy</em>?</> : <>One <em>last</em> thing.</>}
            </h1>
            <p style={{ fontSize: 17, opacity: 0.75, marginBottom: 36 }}>
              {showRoast ? "Set the roast level. We'll never include hate, threats, doxxing, or off-limits topics regardless." : "Confirm and head to checkout."}
            </p>
            {showRoast && (
              <div className="ij-precheck-grid ij-precheck-tone-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 32 }}>
                {[
                  { name: "Mild", desc: "Playful, family-friendly teasing" },
                  { name: "Medium", desc: "Sharper jokes, light profanity ok" },
                  { name: "Savage", desc: "Adult language, harsher roasts" },
                ].map(t => (
                  <button key={t.name} className="choice-card" onClick={() => set("tone", t.name)} style={{
                    textAlign: "left", padding: 18, borderRadius: 14,
                    border: data.tone === t.name ? "1.5px solid var(--ink)" : "1.5px solid var(--line-strong)",
                    background: data.tone === t.name ? "var(--paper-2)" : "var(--paper)",
                    color: "var(--ink)",
                    cursor: "pointer",
                  }}>
                    <div className="display" style={{ fontSize: 22, fontStyle: "italic" }}>{t.name}</div>
                    <div style={{ fontSize: 12, opacity: 0.65, marginTop: 4, lineHeight: 1.4 }}>{t.desc}</div>
                  </button>
                ))}
              </div>
            )}

            <div style={{ padding: 24, background: "var(--paper-2)", borderRadius: 16, border: "1.5px solid var(--line)" }}>
              <span className="eyebrow">Order summary</span>
              <div style={{ marginTop: 12, display: "flex", gap: 8, flexWrap: "wrap" }}>
                <span className="chip accent">{data.tier === "Polished" ? "Human polish" : "Fast gift"}</span>
                <span className="chip">Private link</span>
                <span className="chip">No account</span>
                <span className="chip">{data.tier === "Polished" ? "1 minor revision" : "1 technical regen"}</span>
              </div>
              <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "1fr auto", rowGap: 10, fontSize: 15 }}>
                <div style={{ opacity: 0.7 }}>For</div><div style={{ fontWeight: 600 }}>{data.recipient} ({data.relationship})</div>
                <div style={{ opacity: 0.7 }}>Occasion</div><div style={{ fontWeight: 600 }}>{data.occasion}</div>
                <div style={{ opacity: 0.7 }}>Type</div><div style={{ fontWeight: 600 }}>{data.songType} Jam{showRoast ? ` · ${data.tone}` : ""}</div>
                <div style={{ opacity: 0.7 }}>Tier</div><div style={{ fontWeight: 600 }}>{data.tier} Jam</div>
                <hr className="divider" style={{ gridColumn: "1 / -1", margin: "10px 0" }}/>
                <div className="display" style={{ fontSize: 26 }}>Total</div>
                <div className="display" style={{ fontSize: 26 }}>${data.tier === "Polished" ? 69 : 29}.00</div>
              </div>
            </div>
          </div>
        )}

        <div className="ij-precheck-actions" style={{ display: "flex", justifyContent: "space-between", marginTop: 40 }}>
          <button className="btn ghost" onClick={() => step === 0 ? onBack() : setStep(step-1)}>
            ← {step === 0 ? "Back" : "Previous"}
          </button>
          {step < 3 ? (
            <button className="btn primary" onClick={() => setStep(step+1)}>Continue →</button>
          ) : (
            <button className="btn primary" onClick={() => onContinue(data)}>Continue to checkout →</button>
          )}
        </div>
      </div>
    </div>
  );
}

// === Stripe-style Checkout (visual stub) ===
function toApiPayload(data) {
  const songTypeMap = {
    Roast: "roast",
    Heartfelt: "heartfelt",
    Hype: "hype",
    Romantic: "romantic",
    "Birthday/Holiday": "birthday_holiday",
    Business: "business",
    Other: "other",
  };

  return {
    recipientName: data.recipient,
    relationship: data.relationship,
    occasion: data.occasion,
    songType: songTypeMap[data.songType] || "other",
    tier: data.tier === "Polished" ? "polished" : "quick",
    tone: data.tone,
    businessUse: data.songType === "Business",
  };
}

function redirectToCheckout(checkoutUrl) {
  try {
    if (window.top && window.top !== window) {
      window.top.location.assign(checkoutUrl);
      return;
    }
  } catch (error) {
    // Fall back to the current frame if browser policies block top navigation.
  }
  window.location.assign(checkoutUrl);
}

function Checkout({ data = {}, onComplete, onBack }) {
  const price = data.tier === "Polished" ? 69 : 29;
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");
  const checkoutTraits = createPrototypeCassetteTraits({
    seed: createPrototypeCassetteSeed({
      recipient: data.recipient || "Maya",
      occasion: data.occasion || "custom gift",
      songType: data.songType || "Roast",
      genre: "Pop anthem",
      tier: data.tier || "Quick",
      title: `Checkout preview for ${data.recipient || "Maya"}`,
    }),
    recipient: data.recipient || "Maya",
    occasion: data.occasion || "custom gift",
    title: `Checkout preview for ${data.recipient || "Maya"}`,
    songType: data.songType || "Roast",
    genre: "Pop anthem",
    tier: data.tier || "Quick",
    durationSeconds: data.tier === "Polished" ? 112 : 54,
  });
  const checkoutPreview = getPrototypeCassettePreviewProps(checkoutTraits, {
    recipient: data.recipient || "Maya",
    includeEdition: false,
  });

  const startCheckout = async () => {
    setLoading(true);
    setError("");
    try {
      const response = await fetch("/api/checkout/session", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(toApiPayload(data)),
      });
      const result = await response.json();
      if (!response.ok) throw new Error(result.error || "Checkout failed.");
      redirectToCheckout(result.checkoutUrl);
    } catch (checkoutError) {
      setError(checkoutError instanceof Error ? checkoutError.message : "Checkout failed.");
      setLoading(false);
    }
  };

  return (
    <div className="ij-checkout-shell" style={{ minHeight: "100vh", background: "#fafafa", color: "#1a1a1a", display: "grid", gridTemplateColumns: "1fr 1fr", position: "relative", overflow: "hidden" }}>
      {/* Left · order */}
      <div className="ij-checkout-summary" style={{ padding: "60px 60px 60px 80px", background: "var(--ink)", color: "var(--paper)", position: "relative", overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, opacity: 0.7, fontSize: 13, marginBottom: 32, cursor: "pointer", position: "relative", zIndex: 2 }} onClick={onBack}>
          <Logo /> <span>·</span> <span>Secure checkout</span>
        </div>

        {/* HERO cassette · dominates the left panel as the product anchor */}
        <div className="ij-checkout-cassette-preview" style={{
          position: "relative", marginLeft: -40, marginRight: -40, marginBottom: 32,
          display: "flex", justifyContent: "center",
        }}>
          <div style={{
            transform: "rotate(-4deg)",
            filter: "drop-shadow(0 30px 50px rgba(0,0,0,0.55))",
            zIndex: 2,
          }}>
            {checkoutTraits.tierStyle === "premium" ? (
              <CassetteByVariant
                w={520}
                variant={checkoutPreview.variant}
                recipient={checkoutPreview.recipient}
                title={checkoutPreview.title}
                meta={checkoutPreview.meta}
                spinning={true}
                accent={checkoutPreview.accent}
              />
            ) : (
              <SkeuoCassette
                w={520}
                title={checkoutPreview.title}
                meta={checkoutPreview.meta}
                spinning={true}
                accent={checkoutPreview.accent}
                body={checkoutPreview.body}
                bodyHighlight={checkoutPreview.bodyHighlight}
                bodyShadow={checkoutPreview.bodyShadow}
                labelTone={checkoutPreview.labelTone}
              />
            )}
          </div>
        </div>
        <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.1em", opacity: 0.6, position: "relative", zIndex: 2 }}>{(data.tier || "Quick").toUpperCase()} JAM · ${price}.00</div>
        <div style={{ fontFamily: "var(--f-italic)", fontStyle: "italic", fontSize: 64, marginTop: 6, lineHeight: 1, letterSpacing: "-0.02em", WebkitFontSmoothing: "antialiased", textRendering: "geometricPrecision", position: "relative", zIndex: 2 }}>${price}.00</div>
        <div style={{ marginTop: 4, opacity: 0.7, position: "relative", zIndex: 2 }}>One-time, includes private gift page</div>

        <hr className="divider" style={{ background: "rgba(245,233,215,0.15)", margin: "32px 0" }}/>

        <div style={{ display: "grid", gridTemplateColumns: "1fr auto", rowGap: 12, fontSize: 15 }}>
          <div style={{ opacity: 0.7 }}>{data.tier || "Quick"} Jam · for {data.recipient || "Maya"}</div>
          <div>${price}.00</div>
          <div style={{ opacity: 0.7 }}>Tax</div>
          <div>$0.00</div>
          <hr className="divider" style={{ gridColumn: "1 / -1", background: "rgba(245,233,215,0.15)", margin: "8px 0" }}/>
          <div style={{ fontWeight: 600 }}>Total due today</div>
          <div style={{ fontWeight: 600 }}>${price}.00</div>
        </div>

        <div style={{ marginTop: 60, fontSize: 12, opacity: 0.5, lineHeight: 1.6 }}>
          Powered by Stripe · After payment you receive an intake link by email and on the next page. No accounts required.
        </div>
      </div>

      {/* Right · payment */}
      <div className="ij-checkout-form" style={{ padding: "60px 80px 60px 60px", display: "flex", flexDirection: "column", justifyContent: "center", position: "relative", overflow: "hidden" }}>
        {/* Decorative cassette · floats behind the form, low opacity */}
        <div aria-hidden style={{
          position: "absolute", top: -60, right: -180,
          transform: "rotate(18deg)",
          opacity: 0.10,
          pointerEvents: "none",
          zIndex: 0,
        }}>
          <SkeuoCassette
            w={620}
            title=""
            meta=""
            spinning={false}
            accent={checkoutPreview.accent}
            body={checkoutPreview.body}
            bodyHighlight={checkoutPreview.bodyHighlight}
            bodyShadow={checkoutPreview.bodyShadow}
            labelTone={checkoutPreview.labelTone}
          />
        </div>
        <div style={{ position: "relative", zIndex: 2 }}>
        <h2 style={{
          fontFamily: "var(--f-italic)", fontStyle: "italic", fontWeight: 400,
          fontSize: 38, lineHeight: 1, margin: 0, letterSpacing: "-0.02em",
          WebkitFontSmoothing: "antialiased", textRendering: "geometricPrecision",
        }}>Pay with card</h2>
        <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ background: "#fff", border: "1px solid #dcdcdc", borderRadius: 14, padding: 18, color: "#1A1A24" }}>
            <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.08em", opacity: 0.62 }}>SECURE STRIPE CHECKOUT</div>
            <p style={{ margin: "10px 0 0", fontSize: 15, lineHeight: 1.5, opacity: 0.74 }}>
              You'll finish payment on Stripe, then return to the paid intake page for the story details.
            </p>
          </div>
        </div>
        <button className="btn primary" onClick={startCheckout} disabled={loading} style={{ marginTop: 28, width: "100%", justifyContent: "center", padding: "18px 22px", fontSize: 16 }}>
          {loading ? "Opening secure checkout..." : `Continue to secure Stripe Checkout · $${price}.00`}
        </button>
        {error && <p role="alert" style={{ color: "#B3261E", marginTop: 14 }}>{error}</p>}
        <div style={{ marginTop: 14, textAlign: "center", fontFamily: "var(--f-mono)", fontSize: 11, opacity: 0.6, letterSpacing: "0.05em" }}>
          SECURED BY STRIPE · PAYMENT DETAILS STAY OFF INSIDEJAMS
        </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PreCheck, Checkout });
