// Which Card lookup, Insights, My Cards, Card Detail.
// Every screen uses EDScreen/EDHeader/EDBody so chrome, type sizes, and tab-bar placement are identical.

function ScrWhichCard({ onBack, onPay, onPick }) {
  const [query, setQuery] = React.useState("");
  const [selectedCat, setSelectedCat] = React.useState("Dining");
  const cats = ["Dining","Groceries","Travel","Gas","Streaming","Flights"];
  // Filter ranked cards by free-text query — match merchant or category alias.
  const allRanked = rankCards(selectedCat, 50);
  const q = query.trim().toLowerCase();
  const ranked = q
    ? allRanked.filter(r =>
        (r.card.short && r.card.short.toLowerCase().includes(q)) ||
        (r.card.issuer && r.card.issuer.toLowerCase().includes(q)) ||
        (r.rate.cat && r.rate.cat.toLowerCase().includes(q)) ||
        (r.rate.note && r.rate.note.toLowerCase().includes(q))
      )
    : allRanked;

  return (
    <EDScreen>
      <EDHeader back={onBack} title="Which Card?" subtitle="Pick a category — we'll rank your wallet."/>
      <div style={{ flexShrink: 0, padding: `0 ${ED_GUTTER}px 14px` }}>
        <div style={{ position: "relative" }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)" }}>
            <circle cx="11" cy="11" r="7" stroke={ED_FG3} strokeWidth="2"/><path d="M16.5 16.5L21 21" stroke={ED_FG3} strokeWidth="2" strokeLinecap="round"/>
          </svg>
          <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search merchant or category" style={{
            width: "100%", height: 48, padding: "0 14px 0 42px", borderRadius: ED_R_BTN,
            border: `1px solid ${ED_LINE}`, background: "#fff", fontSize: 15, color: ED_FOREST,
            outline: "none", fontFamily: "inherit", boxSizing: "border-box",
          }}/>
        </div>
        <div style={{ display: "flex", gap: 8, marginTop: 12, overflowX: "auto", paddingBottom: 4 }}>
          {cats.map(c => (
            <button key={c} onClick={() => setSelectedCat(c)} style={{
              padding: "8px 14px", borderRadius: ED_R_PILL, border: "none", cursor: "pointer", whiteSpace: "nowrap",
              background: selectedCat === c ? ED_FOREST : "rgba(6,57,50,0.05)",
              color: selectedCat === c ? ED_CREAM : ED_FOREST, fontSize: 13, fontWeight: 600,
              fontFamily: "inherit",
            }}>{c}</button>
          ))}
        </div>
      </div>

      <EDBody style={{ paddingBottom: ED_TAB_HEIGHT + 12 }}>
        <EDEyebrow style={{ marginBottom: 12, paddingTop: 6 }}>Ranked for {selectedCat.toLowerCase()}</EDEyebrow>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {ranked.map((r, i) => {
            const isBest = i === 0;
            return (
              <div key={r.card.id} style={{
                background: isBest ? ED_FOREST : "#fff",
                color: isBest ? ED_CREAM : ED_FOREST,
                borderRadius: ED_R_SURFACE, padding: 16, position: "relative",
                border: isBest ? "none" : `1px solid ${ED_LINE}`,
                display: "flex", alignItems: "center", gap: 14, overflow: "hidden",
                cursor: "pointer",
              }} onClick={() => {
                if (isBest && onPay) onPay(r.card);
                else if (onPick) onPick(r.card);
              }}>
                {isBest && <div style={{ position: "absolute", top: -30, right: -30, width: 140, height: 140, borderRadius: "50%", background: `radial-gradient(circle, ${ED_BILL}33, transparent 70%)` }}/>}
                <div style={{ width: 28, fontSize: 12, fontWeight: 800, color: isBest ? ED_BILL : ED_FG3, position: "relative" }}>#{i+1}</div>
                <EDCardArt card={r.card} w={84} h={54}/>
                <div style={{ flex: 1, position: "relative" }}>
                  <EDEyebrow color={isBest ? ED_ON_DARK_3 : ED_FG3}>{r.card.issuer}</EDEyebrow>
                  <div style={{ fontSize: 16, fontWeight: 800, color: isBest ? "#fff" : ED_FOREST }}>{r.card.short}</div>
                  <div style={{ fontSize: 11, color: isBest ? ED_ON_DARK_3 : ED_FG3 }}>{r.rate.note || r.rate.cat}</div>
                </div>
                <div style={{ textAlign: "right", position: "relative" }}>
                  <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em", color: isBest ? ED_BILL : ED_FOREST }}>{r.multiplier}×</div>
                  <div style={{ fontSize: 11, color: isBest ? ED_ON_DARK_3 : ED_FG3, fontFeatureSettings: '"tnum"' }}>${r.earn.toFixed(2)} / $50</div>
                </div>
              </div>
            );
          })}
        </div>

        <div style={{ marginTop: 24, padding: 16, background: ED_BILL_BG_SUBTLE, borderRadius: ED_R_BTN, display: "flex", alignItems: "center", gap: 12 }}>
          <img src="/assets/icons/discount.png" width="36" height="36" alt=""/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: ED_FOREST }}>Active offer at this merchant</div>
            <div style={{ fontSize: 12, color: ED_FG2 }}>Amex: 10% back, up to $5 · activate in app</div>
          </div>
        </div>
      </EDBody>
    </EDScreen>
  );
}

// ---------- Insights ("Money Left on the Table") ----------
function ScrInsights({ onBack, onScreen }) {
  const earned = 64.20;
  const missed = 41.30;
  const total = earned + missed;
  return (
    <EDScreen>
      <EDHeader back={onBack} eyebrow="April 2026" title={<span>Money left on<br/>the table.</span>}/>
      <EDBody style={{ paddingBottom: ED_TAB_HEIGHT + 12 }}>
        <div style={{
          background: ED_FOREST, color: ED_CREAM, borderRadius: ED_R_HERO, padding: 22, position: "relative", overflow: "hidden", marginTop: 4,
        }}>
          <div style={{ position: "absolute", top: -60, right: -60, width: 200, height: 200, borderRadius: "50%", background: `radial-gradient(circle, ${ED_BILL}26, transparent 70%)` }}/>
          <EDEyebrow color={ED_ON_DARK_3}>You missed</EDEyebrow>
          <div style={{ fontSize: 64, fontWeight: 800, letterSpacing: "-0.04em", lineHeight: 0.95, color: "#fff", marginTop: 4, fontFeatureSettings: '"tnum"' }}>
            <EDCounter value={41.30} duration={1100}/>
          </div>
          <div style={{ marginTop: 22, height: 8, borderRadius: ED_R_XS, background: "rgba(238,230,227,0.18)", overflow: "hidden", display: "flex", position: "relative" }}>
            <div style={{ width: `${(earned/total)*100}%`, background: ED_BILL, transition: "width 900ms cubic-bezier(0.2,0.7,0.2,1)" }}/>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10, fontSize: 12 }}>
            <div><span style={{ color: ED_BILL, fontWeight: 700 }}>● Earned</span> <span style={{ fontFeatureSettings: '"tnum"', color: "#fff", fontWeight: 700, marginLeft: 4 }}>${earned.toFixed(2)}</span></div>
            <div><span style={{ color: "rgba(238,230,227,0.5)" }}>● Missed</span> <span style={{ fontFeatureSettings: '"tnum"', color: "rgba(238,230,227,0.85)", fontWeight: 700, marginLeft: 4 }}>${missed.toFixed(2)}</span></div>
          </div>
        </div>

        <EDSection eyebrow="Top offenders" title="Where it slipped">
          <EDSurface padded={false}>
            {ED_INSIGHTS.topMissed.map((m, i) => (
              <div key={i} style={{ padding: 16, display: "flex", alignItems: "center", gap: 14, borderBottom: i < 2 ? `1px solid ${ED_LINE}` : "none" }}>
                <div style={{ width: 36, height: 36, borderRadius: ED_R_ICON, background: ED_DANGER_BG, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 800, color: ED_DANGER }}>{i+1}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 700, color: ED_FOREST }}>{m.merchant}</div>
                  <div style={{ fontSize: 12, color: ED_FG3 }}>{m.count} swipes · used wrong card</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 16, fontWeight: 800, color: ED_DANGER, fontFeatureSettings: '"tnum"' }}>−${m.missed.toFixed(2)}</div>
                  <div style={{ fontSize: 11, color: ED_FG3 }}>this month</div>
                </div>
              </div>
            ))}
          </EDSurface>
        </EDSection>

        <EDSection eyebrow="Receipt by receipt" title="Every swipe, scored">
          <EDSurface padded={false}>
            {ED_TXNS.slice(0, 5).map((t, i) => {
              const opt = optimize(t);
              const usedCard = ED_CARDS.find(c => c.id === t.used);
              return (
                <div key={t.id} onClick={() => onScreen && onScreen("txn", t)} style={{ padding: 14, borderBottom: i < 4 ? `1px solid ${ED_LINE}` : "none", cursor: onScreen ? "pointer" : "default" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: opt.isOptimal ? 0 : 10 }}>
                    <div style={{ width: 36, height: 36, borderRadius: ED_R_ICON, background: ED_CREAM, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16, fontWeight: 700, color: ED_FOREST }}>{t.logo}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: ED_FOREST }}>{t.merchant}</div>
                      <div style={{ fontSize: 12, color: ED_FG3 }}>{t.date}</div>
                    </div>
                    <div style={{ textAlign: "right" }}>
                      <div style={{ fontSize: 14, fontWeight: 700, color: ED_FOREST, fontFeatureSettings: '"tnum"' }}>${t.amount.toFixed(2)}</div>
                    </div>
                  </div>
                  {!opt.isOptimal && (
                    <div style={{ marginLeft: 48, display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
                      <EDCardChip card={usedCard} size={20}/>
                      <span style={{ color: ED_FG3, textDecoration: "line-through" }}>{usedCard.short} · ${opt.usedEarn.toFixed(2)}</span>
                      <span style={{ color: ED_FG3 }}>→</span>
                      <EDCardChip card={opt.optimal} size={20}/>
                      <span style={{ color: ED_BILL_700, fontWeight: 700 }}>{opt.optimal.short} · ${opt.optimalEarn.toFixed(2)}</span>
                    </div>
                  )}
                </div>
              );
            })}
          </EDSurface>
        </EDSection>

        <EDSection eyebrow="Year to date" title="The full picture">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <EDSurface padded={false} style={{ padding: 16 }}>
              <EDEyebrow>Earned YTD</EDEyebrow>
              <div style={{ fontSize: 24, fontWeight: 800, color: ED_FOREST, fontFeatureSettings: '"tnum"', marginTop: 4 }}>${ED_INSIGHTS.ytd.earned.toFixed(2)}</div>
            </EDSurface>
            <EDSurface padded={false} style={{ padding: 16 }}>
              <EDEyebrow color={ED_DANGER}>Missed YTD</EDEyebrow>
              <div style={{ fontSize: 24, fontWeight: 800, color: ED_DANGER, fontFeatureSettings: '"tnum"', marginTop: 4 }}>${ED_INSIGHTS.ytd.missed.toFixed(2)}</div>
            </EDSurface>
          </div>
        </EDSection>
      </EDBody>
    </EDScreen>
  );
}

// ---------- My Cards ----------
function ScrMyCards({ onBack, onPick, onAdd }) {
  return (
    <EDScreen>
      <EDHeader
        back={onBack} eyebrow="Wallet" title={`${ED_CARDS.length} cards`}
        trailing={<EDPillButton onClick={onAdd}>+ Add</EDPillButton>}
      />
      <EDBody style={{ paddingBottom: ED_TAB_HEIGHT + 12 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {ED_CARDS.map((c) => (
            <div key={c.id} onClick={() => onPick(c)} style={{ cursor: "pointer" }}>
              <EDSurface padded={false} style={{ display: "flex", alignItems: "center", gap: 14, padding: 14 }}>
                <EDCardArt card={c} w={120} h={76}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <EDEyebrow>{c.issuer}</EDEyebrow>
                  <div style={{ fontSize: 17, fontWeight: 800, color: ED_FOREST, letterSpacing: "-0.01em" }}>{c.short}</div>
                  <div style={{ fontSize: 12, color: ED_FG3, fontFeatureSettings: '"tnum"' }}>•••• {c.last4} · ${c.annualFee} AF</div>
                  <div style={{ fontSize: 12, color: ED_BILL_700, fontWeight: 600, marginTop: 4 }}>{c.rates[0].x}× {c.rates[0].cat.toLowerCase()}</div>
                </div>
                <div style={{ fontSize: 22, color: ED_FG3 }}>›</div>
              </EDSurface>
            </div>
          ))}
        </div>

        <EDSection eyebrow="On the clock" title="Welcome bonus">
          <EDSurface>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
              <EDCardChip card={ED_CARDS[0]} size={36}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: ED_FOREST }}>Sapphire Preferred</div>
                <div style={{ fontSize: 12, color: ED_FG3 }}>$1,840 of $4,000 · 47 days left</div>
              </div>
              <div style={{ fontSize: 18, fontWeight: 800, color: ED_BILL_700, fontFeatureSettings: '"tnum"' }}>46%</div>
            </div>
            <div style={{ height: 10, borderRadius: 5, background: "rgba(6,57,50,0.06)", overflow: "hidden" }}>
              <div style={{ width: "46%", height: "100%", background: `linear-gradient(90deg, ${ED_BILL_700}, ${ED_BILL})`, transition: "width 1.4s cubic-bezier(0.2,0.7,0.2,1)" }}/>
            </div>
            <div style={{ marginTop: 12, fontSize: 12, color: ED_FG2, lineHeight: 1.5 }}>
              At your current pace you'll <b style={{ color: ED_BILL_700 }}>just barely</b> hit the bonus by July 12. We'll route extra spend here automatically.
            </div>
          </EDSurface>
        </EDSection>
      </EDBody>
    </EDScreen>
  );
}

function ScrCardDetail({ card, onBack, onScreen }) {
  // Defensive fallback so the side-rail jump-link doesn't crash when no card was selected.
  const c = card || ED_CARDS[0];
  const [removeConfirm, setRemoveConfirm] = React.useState(false);
  return (
    <EDScreen>
      <EDHero back={onBack} bg={c.color} decorative={false}>
        <div style={{ display: "flex", justifyContent: "center" }}>
          <EDCardArt card={c} w={280} h={176}/>
        </div>
        <div style={{ textAlign: "center", marginTop: 18, color: c.accent }}>
          <EDEyebrow color={c.accent} style={{ opacity: 0.7 }}>{c.issuer}</EDEyebrow>
          <div style={{ fontSize: 28, fontWeight: 800, color: "#fff", marginTop: 2, letterSpacing: "-0.025em" }}>{c.name}</div>
        </div>
      </EDHero>

      <EDBody style={{ paddingBottom: ED_TAB_HEIGHT + 12 }}>
        <EDSection eyebrow="Reward rates" title="Where it earns">
          <EDSurface padded={false}>
            {c.rates.map((r, i) => (
              <div key={i} style={{ padding: 14, display: "flex", alignItems: "center", gap: 12, borderBottom: i < c.rates.length - 1 ? `1px solid ${ED_LINE}` : "none" }}>
                <div style={{ width: 44, fontSize: 18, fontWeight: 800, color: ED_FOREST, fontFeatureSettings: '"tnum"' }}>{r.x}×</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: ED_FOREST }}>{r.cat}</div>
                  {r.note && <div style={{ fontSize: 12, color: ED_FG3 }}>{r.note}</div>}
                </div>
              </div>
            ))}
          </EDSurface>
        </EDSection>

        <EDSection eyebrow="The math" title="Annual fee analysis">
          <EDSurface>
            <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0" }}>
              <div style={{ color: ED_FG2 }}>Annual fee</div>
              <div style={{ fontWeight: 700, color: ED_FOREST, fontFeatureSettings: '"tnum"' }}>${c.annualFee}</div>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderTop: `1px solid ${ED_LINE}` }}>
              <div style={{ color: ED_FG2 }}>Rewards earned YTD</div>
              <div style={{ fontWeight: 700, color: ED_BILL_700, fontFeatureSettings: '"tnum"' }}>+$182.40</div>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderTop: `1px solid ${ED_LINE}` }}>
              <div style={{ color: ED_FG2 }}>Credits used YTD</div>
              <div style={{ fontWeight: 700, color: ED_BILL_700, fontFeatureSettings: '"tnum"' }}>+$60.00</div>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", padding: "12px 0 4px", borderTop: `2px solid ${ED_FOREST}`, marginTop: 8 }}>
              <div style={{ fontWeight: 800, color: ED_FOREST }}>Net value</div>
              <div style={{ fontWeight: 800, color: ED_BILL_700, fontFeatureSettings: '"tnum"', fontSize: 18 }}>+$147.40</div>
            </div>
            <div style={{ marginTop: 14, paddingTop: 12, borderTop: `1px solid ${ED_LINE}` }}>
              <EDPillButton tone="ghost" size="sm" onClick={() => onScreen && onScreen("renewal")}>Renewal value analysis ›</EDPillButton>
            </div>
          </EDSurface>
        </EDSection>

        <EDSection eyebrow="Manage" title="This card">
          {removeConfirm ? (
            <EDSurface style={{ background: ED_DANGER_BG_SUBTLE, borderColor: ED_DANGER_BORDER }}>
              <div style={{ fontSize: 14, color: ED_DANGER, fontWeight: 700, marginBottom: 6 }}>
                Remove {c.short} from your wallet?
              </div>
              <div style={{ fontSize: 12, color: ED_FG2, lineHeight: 1.5, marginBottom: 12 }}>
                We'll stop including it in "Which Card?" recommendations and remove it from your insights. Past data is preserved.
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                <EDPillButton tone="ghost" onClick={() => setRemoveConfirm(false)} style={{ flex: 1, color: ED_FG2 }}>Cancel</EDPillButton>
                <EDPillButton onClick={() => { alert(`${c.short} removed from wallet (in production this is persisted).`); setRemoveConfirm(false); onBack && onBack(); }} style={{ flex: 1, background: ED_DANGER, color: "#fff" }}>Remove</EDPillButton>
              </div>
            </EDSurface>
          ) : (
            <EDSurface padded={false}>
              <button onClick={() => alert("Open the manual card-name picker (coming soon).")} style={{
                width: "100%", padding: 14, background: "transparent", border: "none",
                display: "flex", alignItems: "center", gap: 12, cursor: "pointer",
                textAlign: "left", fontFamily: "inherit", borderBottom: `1px solid ${ED_LINE}`,
              }}>
                <div style={{ flex: 1, fontSize: 14, fontWeight: 600, color: ED_FOREST }}>This isn't the right card</div>
                <span style={{ fontSize: 13, color: ED_BILL_700, fontWeight: 600 }}>Override ›</span>
              </button>
              <button onClick={() => setRemoveConfirm(true)} style={{
                width: "100%", padding: 14, background: "transparent", border: "none",
                display: "flex", alignItems: "center", gap: 12, cursor: "pointer",
                textAlign: "left", fontFamily: "inherit",
              }}>
                <div style={{ flex: 1, fontSize: 14, fontWeight: 600, color: ED_DANGER }}>Remove from wallet</div>
                <span style={{ fontSize: 13, color: ED_DANGER, fontWeight: 600 }}>Remove ›</span>
              </button>
            </EDSurface>
          )}
        </EDSection>
      </EDBody>
    </EDScreen>
  );
}

Object.assign(window, { ScrWhichCard, ScrInsights, ScrMyCards, ScrCardDetail });
