/* eslint-disable */
/* Buyer Overlay — desktop-only "what we just learned" pane for the Chase pitch */

const { useMemo: useMemoBO } = React;

function fmt(v, dict) {
  if (v == null) return "—";
  if (Array.isArray(v)) return v.map(x => dict?.[x] || x).join(", ") || "—";
  if (typeof v === "object") {
    // Contact-shape: {email, phone, optIn, verified, smsOptIn}
    if (v.email || v.phone) {
      const parts = [];
      if (v.email) parts.push(v.email);
      if (v.phone) parts.push(v.phone);
      if (v.verified) parts.push("verified");
      return parts.join(" · ") || "[record]";
    }
    return "[record]";
  }
  if (typeof v === "boolean") return v ? "yes" : "no";
  return dict?.[v] || v || "—";
}

const DICT = {
  // gate
  personal: "Personal", business: "Business", both: "Business + personal", just: "Just here",
  // biz
  owner:"Owner", co:"Co-owner", founder:"Founder", cfo:"CFO", ops:"Ops", help:"Helps run it",
  food:"Food/hospitality", retail:"Retail/e-comm", pro:"Pro services", trades:"Trades",
  health:"Healthcare", tech:"Tech", creator:"Creator/agency", real:"Real estate", mfg:"Manufacturing",
  transp:"Transport", edu:"Edu/nonprofit", other:"Other",
  pre:"Pre-revenue", lt1:"<1 yr", "1to3":"1–3 yrs", "3to10":"3–10 yrs", "10plus":"10+ yrs",
  u100:"<$100K", "100_500":"$100K–$500K", "500_2":"$500K–$2M", "2_10":"$2M–$10M", skip:"—",
  open:"Open account", loan:"Loan/LOC", switch:"Switching", talk:"Banker chat", exist:"Existing acct help", explore:"Exploring",
  wc:"Working capital", equip:"Equipment", sba:"SBA", bridge:"Bridge", expand:"Expansion", growth:"Growth", none:"None",
  us:"With Chase", big1:"BofA", big2:"Wells", big3:"Other big bank", local:"Local bank", cu:"Credit union", online:"Online-only", personal:"Personal acct",
  slow:"Slow lending", credit:"Limited credit", app:"App", human:"Hard to reach", fees:"High fees", smb:"Doesn't get SMB", nothing:"Nothing",
  square:"Square", stripe:"Stripe", toast:"Toast", clover:"Clover", shop:"Shopify", ours:"Chase Payment Solutions", paypal:"PayPal",
  // biz q08 (split)
  lending:"Faster lending", advisor:"Real banker", rates:"Better rates", tech:"Modern app",
  checking:"Checking", merchant:"Payment Solutions", payroll:"Payroll", wealth:"Wealth/treasury",
  // personal
  new:"Open new", manage:"Manage existing", look:"Browsing",
  travel:"Travel rewards", cash:"Cashback", invest:"Investing", service:"Service", branch:"Branches nearby",
  intl:"Intl regular", "13":"1–3 trips/yr", dom:"Domestic", rare:"Rarely", goal:"Travel-curious",
  house:"Housing", bills:"Bills", kids:"Kids", save:"Saving",
  home:"Home purchase", refi:"Refinance", car:"Auto", debt:"Debt payoff", trip:"Big trip", biz:"Side hustle/biz",
  free:"Freelance", rental:"Rental income", etsy:"E-comm", rei:"REI", no:"None",
  first:"Building credit", work:"Wealth building", fam:"Family", ahead:"Pre-retirement", ret:"Retired",
  // just
  pers:"Chase personal customer", card:"Chase card-only", neither:"Unbanked",
  rewards:"Stronger rewards", water:"Just water",
};

function BuyerOverlay({ state }) {
  const { flow, answers, screenIndex } = state;
  const rec = useMemoBO(() => (flow ? recommend(state) : null), [state]);

  const signals = useMemoBO(() => {
    const s = [];
    if (!flow) return [];

    if (flow === "business" || flow === "both") {
      const a = answers;
      if (a.biz_intent === "switch") s.push({ hot: true, text: "Switching from another bank — switching offer eligible." });
      if (a.biz_intent === "loan") s.push({ hot: true, text: "Walked in for a loan — route to lending desk now." });
      if ((a.biz_capital || []).length && !(a.biz_capital || []).includes("none"))
        s.push({ hot: false, text: `Capital need declared: ${(a.biz_capital||[]).map(x=>DICT[x]||x).join(", ")}.` });
      if (a.biz_bank && !["us","skip"].includes(a.biz_bank))
        s.push({ hot: a.biz_bank === "big1" || a.biz_bank === "big2", text: `Currently at ${DICT[a.biz_bank]}.` });
      if (a.biz_payments && a.biz_payments !== "ours" && a.biz_payments !== "none")
        s.push({ hot: false, text: `Merchant Services lead: currently on ${DICT[a.biz_payments]}.` });
      if (a.biz_switch && (a.biz_switch || []).length)
        s.push({ hot: true, text: `Switch motivators: ${(a.biz_switch||[]).map(x=>DICT[x]||x).join(", ")}.` });
      if (a.biz_chase_gap && (a.biz_chase_gap || []).length)
        s.push({ hot: false, text: `Existing Chase usage: ${(a.biz_chase_gap||[]).map(x=>DICT[x]||x).join(", ")}.` });
    }

    if (flow === "personal") {
      const a = answers;
      if (a.p_intent === "switch") s.push({ hot: true, text: "Switching from another bank." });
      if ((a.p_move || []).includes("biz") || (a.p_side && a.p_side !== "no"))
        s.push({ hot: true, text: "Stealth-SMB signal — surface business sweepstakes." });
      if ((a.p_move || []).includes("home") || (a.p_move || []).includes("refi"))
        s.push({ hot: true, text: "Home lending trigger." });
      if ((a.p_switch || []).includes("travel") || a.p_travel === "intl")
        s.push({ hot: false, text: "Premium travel-card fit." });
    }

    if (flow === "just") {
      const a = answers;
      if ((a.j_market || []).includes("biz"))
        s.push({ hot: true, text: "Stealth-SMB signal — short business follow-up triggered." });
      if (a.j_customer === "card") s.push({ hot: false, text: "Card-only customer — banking cross-sell opportunity." });
      if (a.j_customer === "no" || a.j_customer === "neither")
        s.push({ hot: false, text: "Net-new prospect." });
    }
    return s;
  }, [flow, answers]);

  if (!flow && screenIndex === 0) {
    return (
      <div className="bo">
        <div className="bo__head">
          <span className="bo__pulse"/>
          <span className="bo__label bo__label--strong">Buyer Overlay</span>
          <span className="bo__label" style={{marginLeft:"auto"}}>Idle · awaiting scan</span>
        </div>
        <p style={{color:"var(--ink-3)", fontSize:13, lineHeight:1.5, margin:0}}>
          The branch-facing pane. As soon as someone scans a can on the floor, this fills with what they told us — in real time, before they finish.
        </p>
        <h3>What goes here</h3>
        <ul style={{paddingLeft:18, margin:0, fontSize:13, lineHeight:1.6, color:"var(--ink-2)"}}>
          <li>Live answer transcript</li>
          <li>Extracted signals (hot leads in amber)</li>
          <li>Product matches with confidence</li>
          <li>Banker routing</li>
          <li>One-click handoff to your CRM</li>
        </ul>
        <div className="rail__footer" style={{position:"static", marginTop:24, padding:0, borderTop:"1px solid var(--line-2)", paddingTop:14}}>
          Demo data · This pane is desktop-only and is not shown to the branch visitor.
        </div>
      </div>
    );
  }

  return (
    <div className="bo">
      <div className="bo__head">
        <span className="bo__pulse"/>
        <span className="bo__label bo__label--strong">Live · Buyer Overlay</span>
        <span className="bo__label" style={{marginLeft:"auto"}}>
          {flow === "business" ? "BIZ-04711" : flow === "personal" ? "P-19284" : "J-30201"}
        </span>
      </div>

      <h3>Identity</h3>
      <div className="bo__row"><span>Flow</span><b>{DICT[flow] || flow}</b></div>
      <div className="bo__row"><span>Branch</span><b>Hudson Yards · NYC-022</b></div>
      <div className="bo__row"><span>Scan time</span><b>{new Date().toLocaleTimeString([], {hour:"2-digit", minute:"2-digit"})}</b></div>

      {Object.keys(answers).length > 0 && (
        <>
          <h3>Answer transcript</h3>
          {Object.entries(answers).map(([k, v]) => (
            <div key={k} className="bo__row">
              <span style={{color:"var(--ink-3)"}}>{k.replace(/^(biz|p|j)_/, "")}</span>
              <b>{fmt(v, DICT)}</b>
            </div>
          ))}
        </>
      )}

      {signals.length > 0 && (
        <>
          <h3>Signals extracted</h3>
          {signals.map((s, i) => (
            <div key={i} className={"bo__signal" + (s.hot ? " bo__signal--hot" : "")}>
              <span className="bo__signal__dot"/>
              <span>{s.text}</span>
            </div>
          ))}
        </>
      )}

      {rec && (
        <>
          <h3>Product match</h3>
          {rec.kind === "business" && (
            <>
              <div className="bo__match-card">
                <p className="name">{rec.tier.name}</p>
                <p className="why">{rec.tier.why}</p>
                <span className="conf">High confidence (illustrative)</span>
              </div>
              <div className="bo__match-card">
                <p className="name">{rec.card.name}</p>
                <p className="why">{rec.card.why}</p>
                <span className="conf">Med confidence (illustrative)</span>
              </div>
              {rec.lend && (
                <div className="bo__match-card">
                  <p className="name">{rec.lend.name}</p>
                  <p className="why">{rec.lend.est}</p>
                  <span className="conf">Pre-qual · illustrative</span>
                </div>
              )}
            </>
          )}
          {rec.kind === "personal" && (
            <>
              <div className="bo__match-card">
                <p className="name">{rec.card.name}</p>
                <p className="why">{rec.card.why}</p>
                <span className="conf">High confidence (illustrative)</span>
              </div>
              <div className="bo__match-card">
                <p className="name">{rec.bank.name}</p>
                <p className="why">{rec.bank.why}</p>
                <span className="conf">Med confidence (illustrative)</span>
              </div>
              {rec.secondary && (
                <div className="bo__match-card">
                  <p className="name">{rec.secondary.name}</p>
                  <p className="why">{rec.secondary.why}</p>
                  <span className="conf">Life-event signal (illustrative)</span>
                </div>
              )}
            </>
          )}
          {rec.kind === "just" && (
            <div className="bo__match-card">
              <p className="name">{rec.rec.name}</p>
              <p className="why">{rec.rec.why}</p>
              <span className="conf">Nurture (illustrative)</span>
            </div>
          )}
        </>
      )}

      <div style={{marginTop:"auto", paddingTop:18, borderTop:"1px solid var(--line)", marginBottom:0}}>
        <h3 style={{margin:"0 0 6px"}}>Banker routing</h3>
        <p style={{margin:0, fontSize:13}}>
          <b>{(BANKERS[flow] || BANKERS.just).name}</b><br/>
          <span style={{color:"var(--ink-3)", fontSize:12}}>{(BANKERS[flow] || BANKERS.just).role}</span>
        </p>
      </div>
    </div>
  );
}

window.BuyerOverlay = BuyerOverlay;
