// ─────────────────────────────────────────────────────────────
// Dashboard — saved card history + latest plan + regenerate CTA.
// ─────────────────────────────────────────────────────────────
function Dashboard({ user, onNewPlan, onViewPlan, onUpdateHistory, onLogout }) {
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState("");
  const [cards, setCards] = React.useState([]);
  const [plan, setPlan] = React.useState(null);
  const fmt = window.fmt;

  React.useEffect(() => {
    let alive = true;
    (async () => {
      if (!user) return;
      setLoading(true); setError("");
      try {
        const [ch, lp] = await Promise.all([
          window.Store.loadCardHistory(user.id),
          window.Store.loadLatestPlan(user.id),
        ]);
        if (!alive) return;
        setCards(ch); setPlan(lp);
      } catch (e) {
        if (alive) setError(e.message || "Couldn't load your data.");
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, [user]);

  const fmtDate = (d) => d ? new Date(d).toLocaleDateString("en-AU", { month: "short", year: "numeric" }) : "—";

  // Pull headline figures out of a stored plan result, defensively.
  function planSummary(p) {
    const r = p && p.result;
    if (!r) return {};
    const t = r.totals || {};
    const first = (r.plan && r.plan[0]) || null;
    return {
      nextCard: first && first.card ? first.card.name : "—",
      points: t.totalPoints != null ? t.totalPoints : (t.bonusPoints || 0),
      net: t.netEarnings != null ? t.netEarnings : (t.net || 0),
    };
  }
  const ps = planSummary(plan);

  return (
    <div className="step-pane">
      <div className="step-header" style={{ marginBottom: 28 }}>
        <div className="step-eyebrow">Dashboard</div>
        <h1>Your Point Maxing <span className="accent">dashboard.</span></h1>
        <p className="lede">Signed in as <strong>{user.email}</strong>.</p>
      </div>

      {error && <div className="modal-error" style={{ marginBottom: 20 }}>{error}</div>}
      {loading ? (
        <div className="empty-results"><p>Loading your saved data…</p></div>
      ) : (
        <>
          {/* Section 1 — Card history */}
          <div className="section-title">
            <h2>Your credit card history</h2>
            <button className="btn btn-soft" style={{ padding: "10px 18px", fontSize: "0.9rem" }} onClick={onUpdateHistory}>Update card history</button>
          </div>
          {cards.length === 0 ? (
            <div className="history-empty" style={{ marginBottom: 0 }}>No cards saved yet.</div>
          ) : (
            <div className="dash-table">
              <div className="dash-row dash-head">
                <span>Provider</span><span>Card</span><span>Opened</span><span>Closed</span><span>Eligible again</span>
              </div>
              {cards.map(c => (
                <div className="dash-row" key={c.id}>
                  <span>{c.provider}</span>
                  <span>{c.card_name || "—"}</span>
                  <span>{fmtDate(c.opened_date)}</span>
                  <span>{fmtDate(c.closed_date)}</span>
                  <span>{fmtDate(c.eligible_again_date)}</span>
                </div>
              ))}
            </div>
          )}

          {/* Section 2 — Latest plan */}
          <div className="section-title"><h2>Your latest plan</h2>
            {plan && <span className="pill">Saved {fmtDate(plan.created_at)}</span>}
          </div>
          {!plan ? (
            <div className="history-empty" style={{ marginBottom: 0 }}>No saved plan yet — generate one below.</div>
          ) : (
            <div className="result-card" style={{ marginBottom: 0 }}>
              <div className="rc-body" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
                <div className="rc-stat">
                  <div className="rc-stat-label">Recommended next card</div>
                  <div className="rc-stat-value coral">{ps.nextCard}</div>
                </div>
                <div className="rc-stat">
                  <div className="rc-stat-label">Estimated total points</div>
                  <div className="rc-stat-value mint">{fmt.points(ps.points)}</div>
                </div>
                <div className="rc-stat">
                  <div className="rc-stat-label">Estimated net value</div>
                  <div className="rc-stat-value">{fmt.money(ps.net)}</div>
                </div>
              </div>
              <div className="rc-active-note" style={{ justifyContent: "flex-end" }}>
                <button className="btn btn-primary" style={{ padding: "10px 20px", fontSize: "0.9rem" }} onClick={() => onViewPlan(plan)}>View full plan</button>
              </div>
            </div>
          )}

          {/* Section 3 — Regenerate */}
          <div className="section-title"><h2>Generate an updated plan</h2></div>
          <div className="result-card" style={{ padding: "24px 26px", marginBottom: 0 }}>
            <p style={{ margin: "0 0 18px", color: "var(--ink-dim)" }}>
              Credit card offers and eligibility rules change often. Generate a fresh plan using your saved card history.
            </p>
            <button className="btn btn-primary" onClick={onNewPlan}>Generate new plan</button>
          </div>

          <div className="btn-row" style={{ justifyContent: "flex-end" }}>
            <button className="btn btn-ghost" onClick={onLogout}>Log out</button>
          </div>
        </>
      )}
    </div>
  );
}

window.Dashboard = Dashboard;
