/* Branching intake form */

const GENRES = ["Pop anthem", "Country", "Rap/trap", "Rock/punk", "80s power ballad", "EDM/dance", "Acoustic singer-songwriter"];

// Live progress meter — how full the cassette label is
function completion(answers, songType, step) {
  let total = 0, filled = 0;
  const fields = ["nickname", "pronunciation", "genre", "senderMessage"];
  if (songType === "Roast") fields.push("story", "hobby", "secretGreatness");
  fields.forEach(f => { total++; if (answers[f] && answers[f].toString().trim().length > 0) filled++; });
  if (songType === "Roast") {
    answers.traits.forEach(t => { total++; if (t && t.trim()) filled++; });
  }
  return Math.min(1, filled / Math.max(1, total));
}

function Intake({ data = {}, onSubmit, onBack }) {
  const [step, setStep] = React.useState(0);
  const [boundaries, setBoundaries] = React.useState(false);
  const [answers, setAnswers] = React.useState({
    nickname: "May-May",
    pronunciation: "MAY-uh",
    genre: "Pop anthem",
    customVibe: "",
    avoid: "",
    senderMessage: "Happy 30th, weirdo. You deserve to be sung about.",
    // roast
    traits: ["Always 20 mins late", "Texts in all caps", "Insists she's an introvert"],
    story: "The cancun trip where she lost her shoes in the ocean and refused to admit it.",
    hobby: "Selling out at hot girl walks",
    offLimits: "her dad's recent surgery",
    secretGreatness: "She actually remembers every birthday and shows up for everyone",
  });
  const songType = data.songType || "Roast";
  const tier = data.tier || "Quick";
  const set = (k, v) => setAnswers(a => ({ ...a, [k]: v }));

  // Live cassette derived values
  const liveRecipient = data.recipient || "your person";
  const liveTitle = answers.nickname && answers.nickname.trim()
    ? `For ${liveRecipient} (${answers.nickname.trim()})`
    : `For ${liveRecipient}`;
  const durationSeconds = tier === "Polished" ? 112 : 54;
  const cassetteTraits = createPrototypeCassetteTraits({
    seed: createPrototypeCassetteSeed({
      recipient: liveRecipient,
      occasion: data.occasion || "custom gift",
      songType,
      genre: answers.genre || "Pop anthem",
      tier,
      title: liveTitle,
    }),
    recipient: liveRecipient,
    occasion: data.occasion || "custom gift",
    title: liveTitle,
    songType,
    genre: answers.genre || "Pop anthem",
    tier,
    durationSeconds,
  });
  const cassettePreview = getPrototypeCassettePreviewProps(cassetteTraits, {
    title: cassetteTraits.label.title,
    recipient: liveRecipient,
    includeEdition: false,
  });
  const progress = completion(answers, songType, step);

  const baseStep = (
    <div className="appear">
      <span className="eyebrow">Step 1 of 3 · The basics</span>
      <h1 className="display" style={{ fontSize: 48, margin: "12px 0 8px" }}>
        Now the <em>details</em> that make this personal.
      </h1>
      <p style={{ fontSize: 16, opacity: 0.75, marginBottom: 32, maxWidth: 580 }}>
        The more specific you are, the better the song gets. Names, pronunciations, the running bit, the inside-out details only you would know.
      </p>
      <div className="ij-intake-form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div className="field"><label>Recipient nickname (optional)</label><input value={answers.nickname} onChange={e => set("nickname", e.target.value)}/></div>
        <div className="field"><label>Pronunciation note</label><input value={answers.pronunciation} onChange={e => set("pronunciation", e.target.value)} placeholder="say it like…"/></div>
        <div className="field"><label>Genre / vibe</label>
          <select value={answers.genre} onChange={e => set("genre", e.target.value)}>
            {GENRES.map(g => <option key={g}>{g}</option>)}
          </select>
        </div>
        <div className="field"><label>Custom vibe (optional)</label><input value={answers.customVibe} onChange={e => set("customVibe", e.target.value)} placeholder="like Phoebe Bridgers but happier"/></div>
        <div className="field ij-span-all" style={{ gridColumn: "1 / -1" }}><label>Things to avoid</label><textarea value={answers.avoid} onChange={e => set("avoid", e.target.value)} placeholder="Topics, phrases, anything we should leave out"/></div>
      </div>
    </div>
  );

  const storyStep = songType === "Roast" ? (
    <div className="appear">
      <span className="eyebrow">Step 2 of 3 · The roast material</span>
      <h1 className="display" style={{ fontSize: 48, margin: "12px 0 8px" }}>
        What makes them <em>roastable</em>?
      </h1>
      <p style={{ fontSize: 16, opacity: 0.75, marginBottom: 32, maxWidth: 580 }}>
        The funnier and more specific the trait, the better the bit. We need the kind of stuff their group chat already knows.
      </p>
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        <div className="field">
          <label>Three funny traits or quirks</label>
          {answers.traits.map((t, i) => (
            <input key={i} value={t} onChange={e => {
              const next = [...answers.traits]; next[i] = e.target.value; set("traits", next);
            }} placeholder={`Trait ${i+1}`} style={{ marginBottom: 8 }}/>
          ))}
        </div>
        <div className="field"><label>One specific story or inside joke</label><textarea value={answers.story} onChange={e => set("story", e.target.value)}/></div>
        <div className="ij-intake-form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <div className="field"><label>A hobby or obsession</label><input value={answers.hobby} onChange={e => set("hobby", e.target.value)}/></div>
          <div className="field"><label>Off-limits topics</label><input value={answers.offLimits} onChange={e => set("offLimits", e.target.value)}/></div>
        </div>
        <div className="field"><label>Secret greatness <span style={{ opacity: 0.55 }}>(optional)</span></label>
          <span className="hint">"What's one thing they're genuinely great at, even if you'd never admit it to their face?"</span>
          <textarea value={answers.secretGreatness} onChange={e => set("secretGreatness", e.target.value)}/>
        </div>
      </div>
    </div>
  ) : (
    <div className="appear">
      <span className="eyebrow">Step 2 of 3 · The story tape</span>
      <h1 className="display" style={{ fontSize: 48, margin: "12px 0 8px" }}>
        What should the song <em>remember</em>?
      </h1>
      <p style={{ fontSize: 16, opacity: 0.75, marginBottom: 32, maxWidth: 580 }}>
        Give us the memories, phrases, places, and tiny details that make this feel like it could only be for them.
      </p>
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        <div className="field"><label>One specific story or memory</label><textarea value={answers.story} onChange={e => set("story", e.target.value)} placeholder="The trip, toast, inside joke, project launch, first date, or family moment this should carry."/></div>
        <div className="ij-intake-form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <div className="field"><label>Details to include</label><input value={answers.hobby} onChange={e => set("hobby", e.target.value)} placeholder="Places, phrases, habits, wins"/></div>
          <div className="field"><label>Off-limits topics</label><input value={answers.offLimits} onChange={e => set("offLimits", e.target.value)} placeholder="Anything sensitive to avoid"/></div>
        </div>
        <div className="field"><label>Why they matter</label>
          <span className="hint">A sincere line, a funny contradiction, or the thing everyone loves about them.</span>
          <textarea value={answers.secretGreatness} onChange={e => set("secretGreatness", e.target.value)}/>
        </div>
      </div>
    </div>
  );

  const finalStep = (
    <div className="appear">
      <span className="eyebrow">Step 3 of 3 · Wrap it up</span>
      <h1 className="display" style={{ fontSize: 48, margin: "12px 0 8px" }}>
        A <em>note</em> from you.
      </h1>
      <p style={{ fontSize: 16, opacity: 0.75, marginBottom: 32, maxWidth: 580 }}>
        Shows on the gift page above the player. Keep it short and from the heart (or the group chat).
      </p>
      <div className="field"><label>Sender message</label><textarea value={answers.senderMessage} onChange={e => set("senderMessage", e.target.value)} rows={4}/></div>

      <div style={{ marginTop: 32, padding: 22, border: "1.5px solid var(--line-strong)", borderRadius: 14, background: "var(--paper-2)" }}>
          <span className="eyebrow">Before we make the tape</span>
          <p style={{ fontSize: 14, lineHeight: 1.55, marginTop: 10 }}>
          Confirm the song stays playful, consensual, and safe. We cannot make songs with hate or slurs, threats, doxxing, sexual content involving minors, non-consensual content, jokes about serious medical, disability, addiction, self-harm, or trauma, harassment, voice cloning without consent, political attacks, scams, or impersonation.
        </p>
        <label style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 14, cursor: "pointer", fontSize: 14 }}>
          <input type="checkbox" checked={boundaries} onChange={e => setBoundaries(e.target.checked)} style={{ width: 18, height: 18 }}/>
          I agree to InsideJams' content boundaries and confirm I have permission for any name, voice, or likeness referenced.
        </label>
      </div>
    </div>
  );

  const steps = [baseStep, storyStep, finalStep];

  return (
    <div style={{ minHeight: "100vh", background: "var(--paper)" }}>
      <div className="ij-intake-topbar" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 40px", borderBottom: "1px solid var(--line)" }}>
        <Logo/>
        <div className="ij-intake-token" style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <span className="chip solid">PAID · ORDER #IJ-2046</span>
          <span style={{ fontFamily: "var(--f-mono)", fontSize: 11, opacity: 0.6 }}>Token expires in 30 days</span>
        </div>
      </div>

      <div className="ij-intake-shell" style={{ display: "grid", gridTemplateColumns: "1fr 380px", maxWidth: 1240, margin: "0 auto", padding: "60px 40px 100px", gap: 60 }}>
        <div>
          <div style={{ display: "flex", gap: 8, marginBottom: 30 }}>
            {[0,1,2].map(i => (
              <div key={i} style={{ flex: 1, height: 4, background: i <= step ? "var(--tangerine)" : "var(--line-strong)", borderRadius: 2 }}/>
            ))}
          </div>
          {steps[step]}
          <div className="ij-intake-actions" style={{ display: "flex", justifyContent: "space-between", marginTop: 40 }}>
            <button className="btn ghost" onClick={() => step === 0 ? onBack() : setStep(step-1)}>← {step === 0 ? "Back to confirmation" : "Previous"}</button>
            {step < 2 ? (
              <button className="btn primary" onClick={() => setStep(step+1)}>Continue →</button>
            ) : (
              <button className="btn primary" disabled={!boundaries} onClick={() => onSubmit({ ...data, ...answers })} style={{ opacity: boundaries ? 1 : 0.4, cursor: boundaries ? "pointer" : "not-allowed" }}>
                Submit intake →
              </button>
            )}
          </div>
        </div>

        {/* Sidebar · LIVE cassette being built */}
        <aside className="ij-intake-sidebar" style={{ position: "sticky", top: 100, alignSelf: "start" }}>
          <div style={{ padding: "22px 18px 18px", borderRadius: 16, background: "linear-gradient(180deg, #2a2a32 0%, #15151a 50%, #2a2a32 100%)", boxShadow: "0 1px 0 rgba(255,255,255,0.08) inset, 0 30px 60px -28px rgba(0,0,0,0.55)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <span style={{ fontFamily: "var(--f-mono)", fontSize: 9, letterSpacing: "0.16em", color: "#FAEAC4", opacity: 0.7 }}>BUILDING YOUR CASSETTE</span>
              <span style={{ fontFamily: "var(--f-mono)", fontSize: 9, letterSpacing: "0.1em", color: tier === "Polished" ? "var(--honey)" : "#FAEAC4", opacity: tier === "Polished" ? 1 : 0.6 }}>
                · {cassettePreview.styleSignal}
              </span>
            </div>
            {/* Cassette */}
            <div style={{ padding: "14px 8px", background: "linear-gradient(180deg, #08080c 0%, #1a1a20 100%)", borderRadius: 10, boxShadow: "inset 0 4px 12px rgba(0,0,0,0.7)", display: "flex", justifyContent: "center" }}>
              {cassetteTraits.tierStyle === "premium" ? (
                <CassetteByVariant variant={cassettePreview.variant} recipient={cassettePreview.recipient} title={cassettePreview.title} meta={cassettePreview.meta} w={300} spinning={progress > 0.4} accent={cassettePreview.accent}/>
              ) : (
                <SkeuoCassette w={300} title={cassettePreview.title} meta={cassettePreview.meta} spinning={progress > 0.4} accent={cassettePreview.accent} body={cassettePreview.body} bodyHighlight={cassettePreview.bodyHighlight} bodyShadow={cassettePreview.bodyShadow} labelTone={cassettePreview.labelTone}/>
              )}
            </div>
            {/* Progress bar */}
            <div style={{ marginTop: 14 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--f-mono)", fontSize: 9, color: "#FAEAC4", letterSpacing: "0.1em", marginBottom: 6 }}>
                <span>FILL LEVEL</span>
                <span style={{ opacity: 0.7 }}>{Math.round(progress * 100)}%</span>
              </div>
              <div style={{ height: 5, background: "rgba(255,255,255,0.08)", borderRadius: 3, overflow: "hidden" }}>
                <div style={{ height: "100%", width: `${progress * 100}%`, background: `linear-gradient(90deg, ${cassettePreview.accent} 0%, ${cassettePreview.bodyHighlight} 100%)`, transition: "width 220ms var(--ease-out)", boxShadow: `0 0 8px ${cassettePreview.accent}` }}/>
              </div>
            </div>
            {/* Personality stamps · appear as user fills traits */}
            {songType === "Roast" && answers.traits.some(t => t && t.trim()) && (
              <div style={{ marginTop: 14, display: "flex", flexWrap: "wrap", gap: 6 }}>
                {answers.traits.filter(t => t && t.trim()).map((t, i) => (
                  <span key={i} style={{
                    fontFamily: "var(--f-italic)", fontStyle: "italic", fontSize: 11,
                    padding: "3px 8px", borderRadius: 999,
                    background: "rgba(245,233,215,0.08)", color: "#FAEAC4",
                    border: "1px dashed rgba(245,233,215,0.25)",
                    maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                  }}>{t}</span>
                ))}
              </div>
            )}
          </div>
          <div style={{ marginTop: 16, padding: 16, border: "1.5px solid var(--line)", borderRadius: 14, fontSize: 13, lineHeight: 1.55, opacity: 0.85, background: "var(--paper-2)" }}>
            <span className="eyebrow" style={{ fontSize: 9 }}>Your order</span>
            <div style={{ marginTop: 8, fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.04em", opacity: 0.78, lineHeight: 1.65 }}>
              <div>TYPE · {(data.songType || "Roast").toUpperCase()}{data.tone ? ` · ${data.tone.toUpperCase()}` : ""}</div>
              <div>OCCASION · {(data.occasion || "30th birthday").toUpperCase()}</div>
              <div>ETA · {tier === "Polished" ? "WITHIN 24 HRS" : "UNDER 10 MIN"}</div>
            </div>
          </div>
          <div style={{ marginTop: 12, padding: 14, border: "1px dashed var(--line-strong)", borderRadius: 12, fontSize: 12, lineHeight: 1.5, opacity: 0.75 }}>
            Specifics beat generalities. "Owns 14 chapsticks and loses them all" beats "she's quirky" every time.
          </div>
        </aside>
      </div>
    </div>
  );
}

// Submitted confirmation
function IntakeSubmitted({ data, onContinue }) {
  return (
    <div style={{ minHeight: "100%", background: "var(--paper)", display: "grid", placeItems: "center", padding: "80px 40px" }}>
      <div style={{ maxWidth: 580, textAlign: "center" }}>
        <div className="tape" style={{ fontSize: 12 }}>INTAKE RECEIVED · ORDER #IJ-2046</div>
        <h1 className="display" style={{ fontSize: 72, margin: "24px 0 16px" }}>
          We're <em>on</em> it.
        </h1>
        <p style={{ fontSize: 18, lineHeight: 1.55, opacity: 0.78 }}>
          Your {data.tier === "Polished" ? "Polished" : "Quick"} Jam for {data.recipient || "Maya"} is in the works. We'll email you when it's ready, usually {data.tier === "Polished" ? "within 24 hours" : "under the Quick Jam target window"}.
        </p>
        <div style={{ display: "flex", justifyContent: "center", gap: 12, marginTop: 32 }}>
          <button className="btn primary" onClick={onContinue}>Preview a sample gift page →</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Intake, IntakeSubmitted, GENRES });
