/* eslint-disable */
/* Celebration screens — three variants based on flow */

const { useState: useStateC, useEffect: useEffectC, useMemo: useMemoC } = React;

/* Recommendation logic — derives SPECIFIC Chase products from answers,
   with a "why" string that names the answer the match came from. */
function recommend(state) {
  const { flow, answers } = state;

  if (flow === "business" || flow === "both") {
    const cap = answers.biz_capital || [];
    const rev = answers.biz_rev;
    const bank = answers.biz_bank;
    const pay = answers.biz_payments;

    // Account tier — Chase Business Complete vs Performance vs Platinum
    let tier = { name: "Chase Business Complete Banking®", why: "Right-sized for your revenue and transaction volume." };
    if (rev === "500_2") tier = { name: "Chase Performance Business Checking®", why: "$500K–$2M revenue band — fewer fees, more free transactions." };
    if (rev === "2_10" || rev === "10plus") tier = { name: "Chase Platinum Business Checking®", why: "$2M+ revenue — dedicated banker, treasury services, no monthly fee at $100K balance." };

    // Card — Ink family
    let card = { name: "Chase Ink Business Cash® Credit Card", why: "5% on office supplies, internet, cable, phone — covers the basics." };
    if (cap.includes("growth") || cap.includes("expand")) card = { name: "Chase Ink Business Premier℠ Credit Card", why: "Higher limits and 2.5% on $5K+ purchases — built for growth spend." };
    if (pay === "ours" || cap.includes("equip")) card = { name: "Chase Ink Business Unlimited® Credit Card", why: "Flat 1.5% on everything — simplest fit when expenses sprawl." };

    // Lending
    let lend = null;
    if (cap.includes("real")) lend = { name: "Chase Commercial Real Estate financing", est: "Pre-qual: $250K – $2.5M" };
    else if (cap.includes("equip")) lend = { name: "Chase Equipment Financing", est: "Pre-qual: $25K – $500K" };
    else if (cap.includes("sba")) lend = { name: "Chase SBA 7(a) loan program", est: "Pre-qual: up to $5M" };
    else if (cap.includes("wc") || cap.includes("bridge")) lend = { name: "Chase Business Line of Credit", est: "Pre-qual: $50K – $500K" };
    else if (cap.includes("expand") || cap.includes("growth")) lend = { name: "Chase Term Loan for Expansion", est: "Pre-qual: $100K – $1M" };

    const switching = ["big1","big2","big3","local","cu","online","personal"].includes(bank);
    return { kind: "business", tier, card, lend, switching };
  }

  if (flow === "personal") {
    const switchAns = answers.p_switch || [];
    const chaseUse = answers.p_chase_use || [];
    const isChase = answers.p_bank === "us";
    const travel = answers.p_travel;
    const move = answers.p_move || [];
    const stage = answers.p_stage;
    const side = answers.p_side;

    // CARD — specific Chase products
    let card;
    if (travel === "intl") {
      card = { name: "Chase Sapphire Reserve®", why: "You take multiple international trips — the $300 annual travel credit alone covers most of the fee.", offer: "Earn 60,000 bonus points after $4,000 in 3 months." };
    } else if (travel === "13") {
      card = { name: "Chase Sapphire Preferred® Card", why: "1–3 trips a year is the sweet spot — 2x on travel & dining, 5x on Chase Travel℠.", offer: "Earn 60,000 bonus points after $4,000 in 3 months." };
    } else if (switchAns.includes("cash") || stage === "fam") {
      card = { name: "Chase Freedom Unlimited®", why: "Flat 1.5% everywhere, plus 3% dining and drugstores — the everyday workhorse.", offer: "$200 bonus after $500 spent in 3 months." };
    } else if (stage === "first") {
      card = { name: "Chase Freedom Rise℠ Credit Card", why: "Built for people building credit — designed to graduate you to Sapphire.", offer: "1.5% cash back on every purchase." };
    } else {
      card = { name: "Chase Freedom Flex®", why: "5% rotating bonus categories and 3% dining — bonus mileage if you spend deliberately.", offer: "$200 bonus after $500 spent in 3 months." };
    }

    // BANKING — specific tiers
    let bank;
    if (stage === "ret" || stage === "ahead" || (chaseUse.includes("invest"))) {
      bank = { name: "Chase Private Client", why: "$150K+ deposits or investments — dedicated advisor, no ATM fees worldwide, premium rates.", offer: "Up to $3,000 bonus to qualify." };
    } else if (move.includes("invest") || (isChase && chaseUse.includes("savings"))) {
      bank = { name: "Chase Sapphire Banking", why: "Pairs with your Sapphire card — no fees, premium support, 0.01% APY interest.", offer: "Up to $900 to open and qualify." };
    } else {
      bank = { name: "Chase Total Checking®", why: "Most popular checking — $0 with $500 in monthly direct deposit.", offer: "$300 bonus when you set up direct deposit." };
    }

    // SECONDARY — life-event product
    let secondary = null;
    if (move.includes("home")) secondary = { name: "Chase Home Lending", why: "Pre-approval in 24 hours — Chase customers get a relationship discount on rate." };
    else if (move.includes("refi")) secondary = { name: "Chase Refinance review", why: "Current Chase customer rates — see if it pencils before you commit." };
    else if (move.includes("car")) secondary = { name: "Chase Auto Financing", why: "Pre-qualification with no impact to your credit score." };
    else if (move.includes("invest")) secondary = { name: "J.P. Morgan Self-Directed Investing", why: "Unlimited $0 commission trades — sits inside the Chase app you already use." };
    else if (move.includes("debt")) secondary = { name: "Chase Slate Edge℠", why: "Automatic APR reduction when you pay on time — built for paying down balances." };

    const stealthBiz = move.includes("biz") || (side && side !== "no");
    return { kind: "personal", card, bank, secondary, stealthBiz, sideKind: side };
  }

  // Just here
  const market = answers.j_market || [];
  let rec;
  if (market.includes("card")) rec = { name: "Chase Sapphire Preferred® Card", why: "You said you're shopping for a new card — this is our most-recommended starter Sapphire." };
  else if (market.includes("home")) rec = { name: "Chase Home Lending", why: "Pre-approval in 24 hours when you're ready." };
  else if (market.includes("invest")) rec = { name: "J.P. Morgan Self-Directed Investing", why: "Start with $0 — sits in the Chase app." };
  else if (market.includes("biz")) rec = { name: "Chase Business Complete Banking®", why: "Switch in under 10 minutes with our concierge." };
  else if (market.includes("switch")) rec = { name: "Chase Total Checking®", why: "$300 bonus when you switch and set up direct deposit." };
  else rec = { name: "Chase Total Checking®", why: "Our most popular account — start here when you're ready." };

  return { kind: "just", rec, stealthBiz: market.includes("biz") };
}

/* Bankers (placeholder roster) */
const BANKERS = {
  business: { name: "Marisol Aguilar", role: "Senior Business Banker · Hudson Yards", initials: "MA" },
  personal: { name: "Devon Park", role: "Personal Banker · Hudson Yards", initials: "DP" },
  just:     { name: "Jordan Reyes", role: "Welcome Banker · Hudson Yards", initials: "JR" },
};

// Helper — fire demo CTA modal via window event
function fireDemoCTA(label, deeplink) {
  window.dispatchEvent(new CustomEvent("demo-cta", { detail: { label, deeplink: deeplink || "concept demo · not a live offer" }}));
}

// Slugify product name to a chase.com deeplink
function chaseDeeplink(productName) {
  const slug = (productName || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
  return `chase.com/${slug}`;
}

function Celebration({ state, onRestart, onAddBiz }) {
  const rec = useMemoC(() => recommend(state), [state]);
  const banker = BANKERS[rec.kind] || BANKERS.just;
  const firstName = state.firstName || null;

  return (
    <div className="celeb">
      <Statusbar/>
      <div className="celeb__hero">
        <div className="celeb__seal">
          <I.spark s={22}/>
        </div>
        {rec.kind === "business" && (
          <>
            <h1 className="celeb__title">Your <em>match</em> is ready.</h1>
            <p className="celeb__sub">{firstName ? `${firstName}, here's` : "Here's"} what Marisol will walk you through. Ten minutes at her desk and you can be opening accounts.</p>
          </>
        )}
        {rec.kind === "personal" && (
          <>
            <h1 className="celeb__title">We found <em>your card</em>.</h1>
            <p className="celeb__sub">{rec.card.offer ? rec.card.offer : "Built from your answers."} Apply now and your bonus is reserved for 7 days.</p>
          </>
        )}
        {rec.kind === "just" && (
          <>
            <h1 className="celeb__title">You're <em>entered</em>.</h1>
            <p className="celeb__sub">Thanks for stopping in. Here's what we'd love to show you next time.</p>
          </>
        )}
      </div>

      <div className="celeb__body">
        {/* Match cards — specific Chase products with WHY */}
        <div className="match">
          {rec.kind === "business" && (
            <>
              <div className="match__card match__card--featured">
                <div className="match__label">Recommended account</div>
                <p className="match__name">{rec.tier.name}</p>
                <p className="match__desc">{rec.tier.why}</p>
              </div>
              <div className="match__card">
                <div className="match__label">Card</div>
                <p className="match__name">{rec.card.name}</p>
                <p className="match__desc">{rec.card.why}</p>
              </div>
              {rec.lend && (
                <div className="match__card">
                  <div className="match__label">Lending fit</div>
                  <p className="match__name">{rec.lend.name}</p>
                  <p className="match__desc">{rec.lend.est}</p>
                </div>
              )}
              {rec.switching && (
                <div className="match__card">
                  <div className="match__label">Switch offer</div>
                  <p className="match__name">$750 to move your business banking</p>
                  <p className="match__desc">Chase concierge handles payroll, vendors, auto-debits — usually under a week.</p>
                </div>
              )}
            </>
          )}
          {rec.kind === "personal" && (
            <>
              <div className="match__card match__card--featured">
                <div className="match__label">Your card match</div>
                <p className="match__name">{rec.card.name}</p>
                <p className="match__desc">{rec.card.why}</p>
                {rec.card.offer && <p className="match__offer">→ {rec.card.offer}</p>}
              </div>
              <div className="match__card">
                <div className="match__label">Banking</div>
                <p className="match__name">{rec.bank.name}</p>
                <p className="match__desc">{rec.bank.why}</p>
                {rec.bank.offer && <p className="match__offer">→ {rec.bank.offer}</p>}
              </div>
              {rec.secondary && (
                <div className="match__card">
                  <div className="match__label">Worth a look</div>
                  <p className="match__name">{rec.secondary.name}</p>
                  <p className="match__desc">{rec.secondary.why}</p>
                </div>
              )}
            </>
          )}
          {rec.kind === "just" && (
            <div className="match__card match__card--featured">
              <div className="match__label">Picked for you</div>
              <p className="match__name">{rec.rec.name}</p>
              <p className="match__desc">{rec.rec.why}</p>
            </div>
          )}
        </div>

        {/* Rewards row — soft-framed for concept demo */}
        <div className="rewards">
          <div className="reward">
            <div className="reward__num">+50</div>
            <div className="reward__label">Reward points · concept demo</div>
          </div>
          <div className="reward">
            <div className="reward__num"><em>1</em></div>
            <div className="reward__label">Monthly experience entry</div>
          </div>
        </div>

        {/* Lending pre-qual disclaimer — only shown if lending recommendation present */}
        {rec.kind === "business" && rec.lend && (
          <Disclaimer label="Educational pre-qualification only">
            Lending pre-qual ranges are illustrative based on declared answers — not credit decisions. Real Chase business credit applications go through underwriting, ECOA / Reg B disclosure flow, and Chase relationship review.
          </Disclaimer>
        )}

        {/* Stealth-SMB upsell — lead with concrete Chase Ink value, not a sketchy grant */}
        {rec.stealthBiz && rec.kind === "personal" && (
          <div className="upsell">
            <div className="upsell__icon"><I.spark/></div>
            <div style={{flex:1}}>
              <p className="upsell__title">You mentioned earning outside your W-2.</p>
              <p className="upsell__desc">A <b>Chase Ink Business Cash®</b> card could be putting 5% back on your phone, internet, and supplies — even for freelance and side income. Want to see if you'd qualify?</p>
              <button className="upsell__cta" onClick={onAddBiz}>See my Ink match →</button>
            </div>
          </div>
        )}

        {/* Primary CTA — wired to demo modal (no real Chase API calls) */}
        <div className="cta-stack">
          {rec.kind === "personal" && (
            <>
              <button className="cta" onClick={() => fireDemoCTA(`Apply for ${rec.card.name}`, chaseDeeplink(rec.card.name))}>
                Apply for {rec.card.name.replace("Chase ", "").replace("®","").replace("℠","")} now
                <I.arrow/>
              </button>
              <button className="cta cta--ghost" onClick={() => fireDemoCTA(`See ${banker.name} at the desk`, "branch banker queue · concept demo")}>
                See {banker.name.split(" ")[0]} at the desk · 5 min
              </button>
            </>
          )}
          {rec.kind === "business" && (
            <>
              <button className="cta" onClick={() => fireDemoCTA(`Open business account with ${banker.name}`, "chase.com/business · banker queue")}>
                Open my business account with {banker.name.split(" ")[0]}
                <I.arrow/>
              </button>
              <button className="cta cta--ghost" onClick={() => fireDemoCTA("Email match summary to me", "no email actually sent · concept demo")}>
                Send me the match by email
              </button>
            </>
          )}
          {rec.kind === "just" && (
            <button className="cta" onClick={() => fireDemoCTA("Save match for next time", "saved to your sweepstakes profile · concept demo")}>
              Save my match for next time
              <I.arrow/>
            </button>
          )}
        </div>

        {/* Banker handoff */}
        <div className="banker">
          <div className="banker__avatar">{banker.initials}</div>
          <div style={{flex:1}}>
            <p className="banker__name">{banker.name}</p>
            <p className="banker__role">{banker.role}</p>
          </div>
          <button className="cta cta--ghost" style={{width:"auto", padding:"8px 14px", fontSize:12}} onClick={() => fireDemoCTA(`Book 15 min with ${banker.name}`, "calendar.chase.com/branch-booking · concept demo")}>
            Book 15 min
          </button>
        </div>

        <button
          onClick={onRestart}
          style={{
            background: "none", border: 0, padding: "16px 0 8px",
            font: "500 12px/1 'Geist Mono', monospace", letterSpacing:"0.1em",
            color: "var(--ink-3)", textTransform: "uppercase",
            cursor: "pointer", width:"100%",
          }}
        >
          Start over
        </button>
      </div>
    </div>
  );
}

window.Celebration = Celebration;
window.recommend = recommend;
window.BANKERS = BANKERS;
