/* MatchPlan.ai — Dashboard, Upgrade, Settings (MatchIQ style). */

function relTime(iso) {
  const d = new Date(iso), now = new Date();
  const days = Math.floor((now - d) / 86400000);
  if (days <= 0) return "Today";
  if (days === 1) return "Yesterday";
  if (days < 7) return days + " days ago";
  return d.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
const confTone = { high: "green", medium: "gold", low: "red" };
const confLabel = { high: "High match", medium: "Medium match", low: "Low match" };
const confIcon = { high: "TrendingUp", medium: "Minus", low: "TrendingDown" };

function greetWord() {
  const h = new Date().getHours();
  return h < 12 ? "Good morning" : h < 18 ? "Good afternoon" : "Good evening";
}

// pitchiq#511 — the copy of the page drawn when the shell script (and so its ErrorSlot) is absent; the slot itself carries
// "Couldn't load content." / "Try again" (spec DwabVFr7XU rev 8 L16-L17). app.jsx keeps its own pair for the first-load frame.
const BRIEFS_OUTAGE_TEXT = "Couldn't load content.";
const BRIEFS_OUTAGE_RETRY_LABEL = "Try again";

/**
 * pitchiq#511 — the Detailed Error Slot for a briefs-list-only #399 platform outage (store.js `MP.briefsOutage`), drawn by
 * the page IN PLACE of the content that failed to load (spec L20), never as "No briefs yet". "Try again" re-reads the list
 * only (`MP.retryBriefs`) and returns its promise, so the slot stays busy until it settles (L30); on success the page shows
 * the list or its real empty state (L31), on failure the flag stays and so does this slot (L32).
 */
function BriefsOutageSlot() {
  const ErrorSlot = window.EvolveShell && window.EvolveShell.ErrorSlot;
  const retry = () => MP.retryBriefs();
  if (ErrorSlot) return <ErrorSlot variant="detailed" onRetry={retry} />;
  return (
    <div className="mp-fade" style={{ textAlign: "center", color: "var(--fg-2)", padding: "48px 16px" }}>
      <p>{BRIEFS_OUTAGE_TEXT}</p>
      <button type="button" className="tm-btn tm-btn--primary" onClick={retry}>{BRIEFS_OUTAGE_RETRY_LABEL}</button>
    </div>
  );
}

function DashboardPage({ path }) {
  useStoreTick();
  const st = MP.get();
  const preps = st.preps;
  // "there" now covers a signed-in user with no name as well as no user at all (#121). Before
  // this, an empty name rendered "Good afternoon, ." — and the reason it never showed up is that
  // onboarding persisted the literal "You" instead of leaving the field empty, so the empty case
  // was unreachable. Removing that placeholder makes it reachable, so it needs an answer.
  // "there" is reused rather than invented: it is this line's own existing fallback.
  const first = (st.user && st.user.name ? st.user.name.split(" ")[0] : "") || "there";
  const empty = preps.length === 0;
  const completed = preps.filter(p => p.done).length;
  const highCount = preps.filter(p => p.confidence === "high").length;
  // #315 — what THIS member can spend, the same number the sidebar shows: /api/shell's
  // `compactAvailability.remaining`, which the platform resolves as the lowest of the pool, the
  // workspace monthly limit and the member or group limit. Taken from the answer this page's <Shell>
  // already loaded, never fetched again. Not loaded yet, no answer, or not a number → unknown (never
  // 0, design doc §1.3) — and NEVER the workspace pool, which a limit can put out of reach.
  const shellCtx = useCachedShellContext();
  const availability = shellCtx && shellCtx.compactAvailability;
  const credits = availability && Number.isFinite(availability.remaining) ? availability.remaining : null;
  const creditsKnown = credits != null;
  // Guarded like app.jsx's `refusalNow` (pitchiq#443): a browser can run this file against an older cached store.js.
  const briefsOutage = typeof MP.briefsOutage === "function" && MP.briefsOutage();

  return (
    <Shell path={path}>
      <div className="mp-pagehead mp-fade">
        <h1 className="text-heading-1">{greetWord()}, {first}.</h1>
        <p className="mp-pagehead__sub">Here's where things stand with your pipeline today.</p>
      </div>

      {/* pitchiq#511 — the briefs list could not be read (a #399 platform outage). Spec DwabVFr7XU rev 8 L26: "If an
          essential Overview widget cannot load, replace the entire dashboard content area with one Detailed slot." The stat
          tiles, the draft card, the quick start and "Recent briefs" are all computed from or about that list — kept, they
          would read 0 and "Generate your first brief", the same lie as "No briefs yet". The nav (Shell) and the header
          above stay (L19). */}
      {briefsOutage ? <BriefsOutageSlot /> : <>

      {/* stat strip */}
      <div className="mp-stats mp-fade" style={{ marginBottom: 22 }}>
        <div className="mp-stat">
          <div className="mp-stat__body">
            <div className="mp-stat__head"><span className="mp-dot" style={{ background: "var(--gold-3)" }}></span> Briefs generated</div>
            <div>
              <div className="text-number-1 mp-stat__value">{st.briefsToDate}</div>
              <div className="mp-stat__sub">To date</div>
            </div>
          </div>
        </div>
        <div className="mp-stat">
          <div className="mp-stat__body">
            <div className="mp-stat__head"><span className="mp-dot" style={{ background: "var(--blue-4)" }}></span> Completed</div>
            <div><div className="text-number-1 mp-stat__value">{completed}</div><div className="mp-stat__sub">Calls done</div></div>
          </div>
        </div>
        <div className="mp-stat">
          <div className="mp-stat__body">
            <div className="mp-stat__head"><span className="mp-dot" style={{ background: "var(--purple-1)" }}></span> Strong matches</div>
            <div><div className="text-number-1 mp-stat__value">{highCount}</div><div className="mp-stat__sub">High-fit prospects</div></div>
          </div>
        </div>
        <div className="mp-stat">
          <div className="mp-stat__body">
            <div className="mp-stat__head"><span className="mp-dot" style={{ background: "var(--green-3)" }}></span> Briefs to use</div>
            <div>
              <div className="text-number-1 mp-stat__value">{creditsKnown ? credits : CREDITS_UNKNOWN.value}</div>
              <div className="mp-stat__sub">
                {creditsKnown ? `${credits} prepaid credit${credits === 1 ? "" : "s"}` : CREDITS_UNKNOWN.text}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* resume in-progress draft */}
      {(() => {
        const draft = MP.getDraft();
        if (!draft) return null;
        const co = (draft.draft && draft.draft.prospect) || "Untitled prospect";
        return (
          <button onClick={() => navigate("/prepare/new")} className="mp-resume-card mp-fade">
            <span className="mp-resume-card__icon"><Icon name="PencilLine" size={18} /></span>
            <span className="mp-resume-card__body">
              <span className="mp-resume-card__t">Continue your brief for {co}</span>
              <span className="mp-resume-card__s">Draft saved {relTime(draft.updatedAt).toLowerCase()} · pick up where you left off</span>
            </span>
            <span className="mp-resume-card__cta">Resume <Icon name="ArrowRight" size={16} /></span>
          </button>
        );
      })()}

      {/* quick start */}
      <Card className="mp-quickstart mp-fade" accent="gold" style={{ marginBottom: 22 }}>
        <div className="mp-quickstart__bg"></div>
        <div className="mp-card__pad" style={{ position: "relative" }}>
          <div className="mp-eyebrow is-gold" style={{ marginBottom: 12 }}><Icon name="Sparkles" size={14} /> Quick start</div>
          <h2 className="text-heading-2" style={{ margin: 0, maxWidth: "20ch" }}>{empty ? "Generate your first brief" : "Got a call coming up?"}</h2>
          <p style={{ margin: "10px 0 0", color: "var(--fg-2)", fontSize: "var(--fs-body-1)", maxWidth: "54ch", lineHeight: 1.5 }}>
            Drop in a prospect and Evolve Edge researches them across the web, then writes a ready-to-use Game Day Brief that matches what you sell to what they need. About a minute, not 3–4 hours.
          </p>
          <div style={{ marginTop: 18, display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
            <Button size="lg" icon="Sparkles" onClick={() => navigate("/prepare/new")}>Generate a brief</Button>
            <span style={{ fontSize: "var(--fs-body-3)", color: "var(--fg-3)" }}>
              {creditsKnown ? `${credits} prepaid credit${credits === 1 ? "" : "s"} ready` : CREDITS_UNKNOWN.text}
            </span>
          </div>
        </div>
      </Card>

      {/* recent preps */}
      <div className="mp-tablewrap mp-fade">
        <div className="mp-tablehead">
          <h2 className="text-heading-3">Recent briefs</h2>
          <button className="mp-link" onClick={() => navigate("/briefs")}>View all <Icon name="ArrowRight" size={14} /></button>
        </div>
        {empty ? (
          <div className="mp-empty">
            <div className="mp-empty__icon"><Icon name="Inbox" size={24} /></div>
            <p style={{ margin: 0 }}>No briefs yet. Generate one — it takes about a minute.</p>
          </div>
        ) : (
          <table className="tm-table">
            <thead><tr>
              <th>Prospect</th><th style={{ width: 150 }}>Status</th><th>Key insight</th><th style={{ width: 110 }}>Prepped</th><th style={{ width: 40 }}></th>
            </tr></thead>
            <tbody>
              {preps.slice(0, 8).map(p => (
                <tr key={p.id} className="mp-prep-row" onClick={() => navigate("/prepare/" + p.id)}>
                  <td>
                    <div className="mp-cellflex">
                      <Avatar name={p.prospect} color="blue" size={36} soft />
                      <div style={{ minWidth: 0 }}>
                        <div className="mp-prospect-name">{p.prospect}</div>
                        <div className="mp-prospect-sub">{p.stage} · {p.url}</div>
                      </div>
                    </div>
                  </td>
                  <td>{p.done ? <Chip tone="neutral" icon="Check">Done</Chip> : <Chip tone={confTone[p.confidence]} icon={confIcon[p.confidence]}>{confLabel[p.confidence]}</Chip>}</td>
                  <td className="mp-td-insight">{p.insight}</td>
                  <td style={{ color: "var(--fg-2)", fontSize: "var(--fs-body-3)" }}>{relTime(p.createdAt)}</td>
                  <td><span style={{ color: "var(--fg-3)" }}><Icon name="ChevronRight" size={18} /></span></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
      </>}
    </Shell>
  );
}

// ---- Credits (/upgrade) ----
// The UpgradePage component lives in pages-billing.jsx: the credit balance and
// the link to buy credits in Evolve Suite — no plan catalog (#286).

// ---- Settings lives in pages-settings.jsx ----

Object.assign(window, { DashboardPage, BriefsOutageSlot, relTime, confTone, confLabel, confIcon, greetWord });
