// Dashboard variations — all use EDScreen / EDHeader / EDBody for consistent chrome.

function ScrDashboard({ variant = "A", onTab, onScreen }) {
  if (variant === "B") return <DashB onTab={onTab} onScreen={onScreen}/>;
  if (variant === "C") return <DashC onTab={onTab} onScreen={onScreen}/>;
  return <DashA onTab={onTab} onScreen={onScreen}/>;
}

// Shared bell-icon SVG used by DashHeader + DashC.
function BellIcon({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <path d="M6 8a6 6 0 0112 0c0 7 3 9 3 9H3s3-2 3-9z" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"/>
      <path d="M10 21a2 2 0 004 0" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
    </svg>
  );
}

// Avatar circle (initial inside) — light or dark variant. Sized like EDIconButton (36×36).
function DashAvatar({ initial = "J", onClick, variant = "light" }) {
  const isDark = variant === "dark";
  return (
    <button onClick={onClick} aria-label="Profile" style={{
      width: 36, height: 36, borderRadius: ED_R_PILL,
      background: isDark ? "rgba(238,230,227,0.18)" : ED_FOREST,
      color: isDark ? ED_CREAM : ED_CREAM,
      border: "none", cursor: "pointer", fontFamily: "inherit",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontWeight: 700, fontSize: 14,
    }}>{initial}</button>
  );
}

// Shared dashboard header — date + greeting + bell + avatar (locked position).
function DashHeader({ eyebrow = "Wednesday, April 29", title = "Hi Jordan", onNotif, onProfile }) {
  return (
    <div style={{ padding: `${ED_SAFE_TOP}px ${ED_GUTTER}px 16px`, flexShrink: 0 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div>
          <div style={{ fontSize: 13, color: ED_FG3, marginBottom: 2 }}>{eyebrow}</div>
          <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: "-0.025em", color: ED_FOREST, lineHeight: 1.1 }}>{title}</div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <EDIconButton onClick={onNotif} ariaLabel="Notifications" badge>
            <BellIcon/>
          </EDIconButton>
          <DashAvatar initial="J" onClick={onProfile}/>
        </div>
      </div>
    </div>
  );
}

// First-run banner — shown on the dashboard once after onboarding completes.
// Acknowledges that displayed numbers are still being computed from a fresh Plaid sync.
function FirstRunBanner() {
  const [dismissed, setDismissed] = React.useState(() => {
    try { return sessionStorage.getItem("ed.firstRunDismissed") === "1"; }
    catch { return false; }
  });
  if (dismissed) return null;
  const close = () => {
    try { sessionStorage.setItem("ed.firstRunDismissed", "1"); } catch {}
    setDismissed(true);
  };
  return (
    <div style={{
      background: ED_FOREST_900, color: ED_CREAM, borderRadius: ED_R_SURFACE,
      padding: 14, marginBottom: 14, display: "flex", alignItems: "flex-start", gap: 12, position: "relative",
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: "50%", background: ED_BILL,
        display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
      }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
          <path d="M12 6v6l4 2" stroke={ED_FOREST_900} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
          <circle cx="12" cy="12" r="9" stroke={ED_FOREST_900} strokeWidth="2.4"/>
        </svg>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: "#fff", marginBottom: 2 }}>Crunching your last 90 days</div>
        <div style={{ fontSize: 12, color: ED_ON_DARK_2, lineHeight: 1.45 }}>
          The numbers below are sample data. Real insights will appear here as your transactions sync — usually within 60 seconds.
        </div>
      </div>
      <button onClick={close} aria-label="Dismiss" style={{
        background: "rgba(255,255,255,0.10)", border: "none", width: 24, height: 24, borderRadius: "50%",
        cursor: "pointer", color: ED_CREAM, display: "flex", alignItems: "center", justifyContent: "center",
        flexShrink: 0, fontFamily: "inherit",
      }}>
        <svg width="10" height="10" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/></svg>
      </button>
    </div>
  );
}

// ---------- Variant A: Action-first ----------
function DashA({ onScreen }) {
  return (
    <EDScreen>
      <DashHeader onNotif={() => onScreen("notifications")} onProfile={() => onScreen("profile")}/>
      <EDBody style={{ paddingBottom: ED_TAB_HEIGHT + 12 }}>
        <FirstRunBanner/>
        {/* Hero: Best card right now */}
        <div style={{
          background: ED_FOREST, borderRadius: ED_R_HERO, padding: 20, color: ED_CREAM,
          position: "relative", overflow: "hidden", marginBottom: 14,
        }}>
          <div style={{ position: "absolute", top: -40, right: -40, width: 200, height: 200, borderRadius: "50%",
            background: `radial-gradient(circle, ${ED_BILL}33, transparent 70%)`}}/>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8, position: "relative" }}>
            <div style={{ width: 8, height: 8, borderRadius: "50%", background: ED_BILL, animation: "edPulse 1.4s infinite" }}/>
            <EDEyebrow color={ED_BILL}>Right now · Trader Joe's nearby</EDEyebrow>
          </div>
          <div style={{ fontSize: 14, color: ED_ON_DARK_2, marginBottom: 14, position: "relative" }}>Use this for groceries</div>
          <div style={{ display: "flex", gap: 14, alignItems: "center", position: "relative" }}>
            <EDCardArt card={ED_CARDS[1]} w={132} h={84}/>
            <div>
              <EDEyebrow color={ED_ON_DARK_3}>Amex</EDEyebrow>
              <div style={{ fontSize: 22, fontWeight: 800, color: "#fff", letterSpacing: "-0.02em" }}>Gold</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginTop: 4 }}>
                <span style={{ fontSize: 26, fontWeight: 800, color: ED_BILL, letterSpacing: "-0.02em" }}>4×</span>
                <span style={{ fontSize: 12, color: ED_ON_DARK_2 }}>MR points</span>
              </div>
            </div>
          </div>
          <button onClick={() => onScreen("pay")} style={{
            marginTop: 16, width: "100%", height: 46, borderRadius: ED_R_BTN, border: "none",
            background: ED_BILL, color: ED_FOREST_900, fontWeight: 700, fontSize: 15, cursor: "pointer", position: "relative",
            fontFamily: "inherit",
          }}>Use Amex Gold here →</button>
        </div>

        {/* Quick stats */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 20 }}>
          <EDSurface onClick={() => onScreen("insights")} padded={false} style={{ padding: 14 }}>
            <EDEyebrow>Earned · April</EDEyebrow>
            <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "-0.02em", color: ED_FOREST, marginTop: 4, fontFeatureSettings: '"tnum"' }}>$64.20</div>
            <EDSpark data={[5,8,7,12,11,18,22,28,35,42,48,55,60,64]} w={120} h={22}/>
          </EDSurface>
          <EDSurface onClick={() => onScreen("insights")} padded={false} style={{ padding: 14, background: ED_DANGER_BG_SUBTLE, borderColor: ED_DANGER_BORDER }}>
            <EDEyebrow color={ED_DANGER}>Left on table</EDEyebrow>
            <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "-0.02em", color: ED_DANGER, marginTop: 4, fontFeatureSettings: '"tnum"' }}>$41.30</div>
            <div style={{ fontSize: 11, color: ED_FG3 }}>See where →</div>
          </EDSurface>
        </div>

        <EDSection eyebrow="Don't forget" title="Expires soon">
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {ED_BENEFITS.filter(b => b.urgent).map((b, i) => {
              const card = ED_CARDS.find(c => c.id === b.card);
              return (
                <EDSurface key={i} style={{ padding: 12, display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ width: 40, height: 40, borderRadius: ED_R_ICON, background: "rgba(242,220,59,0.32)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <img src="/assets/icons/dollar-coin.png" width="26" height="26" alt=""/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: ED_FOREST }}>${b.value} {b.name}</div>
                    <div style={{ fontSize: 12, color: ED_FG3 }}>{card.issuer} {card.short}</div>
                  </div>
                  <EDPill tone="warn">{b.expires}</EDPill>
                </EDSurface>
              );
            })}
          </div>
        </EDSection>

        <EDSection
          eyebrow="Recent"
          title="What you swiped"
          action={
            <button onClick={() => onScreen("insights")} style={{ background: "none", border: "none", color: ED_BILL_700, fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>See all →</button>
          }
        >
          <EDSurface padded={false}>
            {ED_TXNS.slice(0, 4).map((t, i) => {
              const opt = optimize(t);
              const usedCard = ED_CARDS.find(c => c.id === t.used);
              return (
                <div key={t.id} onClick={() => onScreen("txn", t)} style={{
                  display: "flex", alignItems: "center", gap: 12, padding: 12,
                  borderBottom: i < 3 ? `1px solid ${ED_LINE}` : "none",
                  cursor: "pointer",
                }}>
                  <div style={{ width: 34, height: 34, borderRadius: ED_R_ICON, background: ED_CREAM, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16, fontWeight: 700, color: ED_FOREST, flexShrink: 0 }}>{t.logo}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: ED_FOREST, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.merchant}</div>
                    <div style={{ fontSize: 12, color: ED_FG3, display: "flex", alignItems: "center", gap: 6 }}>
                      <span>{t.category}</span>
                      <span>·</span>
                      <EDCardChip card={usedCard} size={18}/>
                    </div>
                  </div>
                  <div style={{ textAlign: "right", flexShrink: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: ED_FOREST, fontFeatureSettings: '"tnum"' }}>${t.amount.toFixed(2)}</div>
                    {opt.isOptimal
                      ? <div style={{ fontSize: 11, color: ED_BILL_700, fontWeight: 600 }}>+${opt.usedEarn.toFixed(2)} ✓</div>
                      : <div style={{ fontSize: 11, color: ED_DANGER, fontWeight: 600, fontFeatureSettings: '"tnum"' }}>−${opt.missed.toFixed(2)}</div>}
                  </div>
                </div>
              );
            })}
          </EDSurface>
        </EDSection>
      </EDBody>
    </EDScreen>
  );
}

// ---------- Variant B: Insight-first ----------
function DashB({ onScreen }) {
  return (
    <EDScreen>
      <DashHeader eyebrow="For You · April" onNotif={() => onScreen("notifications")} onProfile={() => onScreen("profile")}/>
      <EDBody style={{ paddingBottom: ED_TAB_HEIGHT + 12 }}>
        <div style={{ marginBottom: 18 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: ED_FG2, marginBottom: 6 }}>You've earned this month</div>
          <div style={{ fontSize: 72, fontWeight: 800, letterSpacing: "-0.04em", lineHeight: 0.95, color: ED_FOREST, fontFeatureSettings: '"tnum"' }}>
            <EDCounter value={64.20} duration={1100}/>
          </div>
          <div style={{ marginTop: 14, padding: "12px 14px", background: ED_DANGER_BG_SUBTLE, borderRadius: ED_R_ICON, display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ width: 5, height: 36, borderRadius: ED_R_XS, background: ED_DANGER }}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, color: ED_DANGER, fontWeight: 700 }}>You also left $41.30 on the table</div>
              <div style={{ fontSize: 12, color: ED_FG3 }}>Mostly groceries on your Sapphire</div>
            </div>
            <button onClick={() => onScreen("insights")} style={{ background: "none", border: "none", color: ED_DANGER, fontWeight: 700, cursor: "pointer", fontSize: 18 }}>→</button>
          </div>
        </div>

        <EDSection eyebrow="Right now" title="Trader Joe's, 0.2 mi">
          <EDSurface style={{ display: "flex", alignItems: "center", gap: 14, padding: 12 }} onClick={() => onScreen("which")}>
            <EDCardArt card={ED_CARDS[1]} w={86} h={54}/>
            <div style={{ flex: 1 }}>
              <EDEyebrow>Use this</EDEyebrow>
              <div style={{ fontSize: 16, fontWeight: 700, color: ED_FOREST }}>Amex Gold</div>
              <div style={{ fontSize: 12, color: ED_BILL_700, fontWeight: 700 }}>4× on groceries</div>
            </div>
            <div style={{ fontSize: 22, color: ED_FG3 }}>›</div>
          </EDSurface>
        </EDSection>

        <EDSection eyebrow="Where it slipped" title="Most-missed merchants">
          <EDSurface padded={false}>
            {ED_INSIGHTS.topMissed.map((m, i) => (
              <div key={i} onClick={() => onScreen("insights")} style={{ padding: 12, display: "flex", alignItems: "center", gap: 12, borderBottom: i < 2 ? `1px solid ${ED_LINE}` : "none", cursor: "pointer" }}>
                <div style={{ fontSize: 14, fontWeight: 800, color: ED_FG3, width: 18 }}>{i+1}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: ED_FOREST }}>{m.merchant}</div>
                  <div style={{ fontSize: 12, color: ED_FG3 }}>{m.count} swipes this month</div>
                </div>
                <div style={{ fontSize: 14, fontWeight: 700, color: ED_DANGER, fontFeatureSettings: '"tnum"' }}>−${m.missed.toFixed(2)}</div>
              </div>
            ))}
          </EDSurface>
        </EDSection>
      </EDBody>
    </EDScreen>
  );
}

// ---------- Variant C: Story-first ----------
function DashC({ onScreen }) {
  return (
    <EDScreen>
      <EDBody noGutter style={{ paddingBottom: ED_TAB_HEIGHT + 12 }}>
        <EDHero
          bg={`linear-gradient(180deg, ${ED_FOREST} 0%, ${ED_FOREST_900} 100%)`}
          bottomRadius={ED_R_HERO}
          paddingBottom={32}
          decorative={true}
        >
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24 }}>
            <EDLogo tone="bill" height={18}/>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <EDIconButton onClick={() => onScreen("notifications")} ariaLabel="Notifications" variant="dark" badge>
                <BellIcon size={17}/>
              </EDIconButton>
              <DashAvatar initial="J" onClick={() => onScreen("profile")} variant="dark"/>
            </div>
          </div>
          <div style={{ fontSize: 27, fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.18, color: "#fff" }}>
            You're <span style={{ color: ED_BILL, fontWeight: 800 }}>$22.90 ahead</span> of where you'd be without us this month.
          </div>
          <div style={{ marginTop: 18, display: "flex", gap: 24 }}>
            <div>
              <EDEyebrow color={ED_ON_DARK_3}>Earned</EDEyebrow>
              <div style={{ fontSize: 22, fontWeight: 800, color: ED_BILL, fontFeatureSettings: '"tnum"', marginTop: 2 }}>$64.20</div>
            </div>
            <div style={{ width: 1, background: "rgba(238,230,227,0.2)" }}/>
            <div>
              <EDEyebrow color={ED_ON_DARK_3}>Missed</EDEyebrow>
              <div style={{ fontSize: 22, fontWeight: 800, color: "rgba(238,230,227,0.85)", fontFeatureSettings: '"tnum"', marginTop: 2 }}>$41.30</div>
            </div>
          </div>
          <div style={{ marginTop: 20 }}>
            <EDPillButton onClick={() => onScreen("insights")} tone="bill" size="lg">See the story →</EDPillButton>
          </div>
        </EDHero>

        <div style={{ padding: `4px ${ED_GUTTER}px 0` }}>
          <EDSection eyebrow="Right now" title="Pull this card">
            <EDSurface style={{ padding: 14, display: "flex", flexDirection: "column", gap: 12 }} onClick={() => onScreen("which")}>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <EDCardArt card={ED_CARDS[1]} w={110} h={70}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 17, fontWeight: 800, color: ED_FOREST }}>Amex Gold</div>
                  <div style={{ fontSize: 12, color: ED_FG3 }}>at Trader Joe's, 0.2 mi away</div>
                  <div style={{ fontSize: 12, color: ED_BILL_700, fontWeight: 700, marginTop: 4 }}>4× points · $0.80 / $20</div>
                </div>
              </div>
              <div style={{ height: 1, background: ED_LINE }}/>
              <div style={{ fontSize: 12, color: ED_FG3 }}>
                Beats your Sapphire Preferred by <b style={{ color: ED_DANGER }}>$0.60</b> on a typical $20 spend.
              </div>
            </EDSurface>
          </EDSection>

          <EDSection eyebrow="This week's story" title="Coffee changed">
            <EDSurface style={{ background: ED_CREAM, border: "none", padding: 16, cursor: "pointer" }} onClick={() => onScreen("insights")}>
              <div style={{ fontSize: 15, fontWeight: 600, color: ED_FOREST, lineHeight: 1.5 }}>
                You spent <b>$84 on coffee</b> this week. Last week you used your Sapphire — this week the Amex Gold caught it. That's <b style={{ color: ED_BILL_700 }}>+$2.52</b> for doing nothing different.
              </div>
            </EDSurface>
          </EDSection>

          <EDSection eyebrow="Don't forget" title="Expiring credits">
            <EDSurface padded={false}>
              {ED_BENEFITS.filter(b => b.urgent).map((b, i) => {
                const card = ED_CARDS.find(c => c.id === b.card);
                return (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: 12, borderBottom: i < 1 ? `1px solid ${ED_LINE}` : "none" }}>
                    <EDCardChip card={card} size={32}/>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 700, color: ED_FOREST }}>${b.value} {b.name}</div>
                      <div style={{ fontSize: 12, color: ED_FG3 }}>{card.short} · expires {b.expires}</div>
                    </div>
                    <EDPillButton tone="forest" size="sm" onClick={() => onScreen("offers")}>Use it</EDPillButton>
                  </div>
                );
              })}
            </EDSurface>
          </EDSection>
        </div>
      </EDBody>
    </EDScreen>
  );
}

Object.assign(window, { ScrDashboard, DashA, DashB, DashC });
