// Secondary views — modal overlays opened from the home screen.
// Exposes <ScoreDetailView>, <BreakdownView>, <TileDetailView>, <MoveDetailView>.

const { useEffect } = React;

// ── Shared modal shell ──────────────────────────────────────────────────────
function ModalShell({ open, onClose, eyebrow, title, children, footer }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div className="rbi-modal-scrim" onClick={onClose}>
      <div className="rbi-modal" onClick={(e) => e.stopPropagation()}>
        <div className="rbi-modal-hd">
          <div>
            <div className="rbi-modal-eb">{eyebrow}</div>
            <h2 className="rbi-modal-title">{title}</h2>
          </div>
          <button className="rbi-modal-close" onClick={onClose} aria-label="Close">×</button>
        </div>
        <div className="rbi-modal-body">{children}</div>
        {footer ? <div className="rbi-modal-foot">{footer}</div> : null}
      </div>
    </div>
  );
}

// ── Score detail ────────────────────────────────────────────────────────────
function ScoreDetailView({ open, onClose, profile }) {
  if (!profile) return null;
  const s = profile.score;
  const pct = Math.round((s.value / s.max) * 100);
  return (
    <ModalShell
      open={open}
      onClose={onClose}
      eyebrow="What drives this score"
      title={"Business credit · " + s.value + " of " + s.max}
      footer={(
        <div className="rbi-foot-row">
          <div className="rbi-foot-note">
            Score sourced from the Small Business Financial Exchange (SBFE). Revenued
            reports your tradeline activity to the SBFE every 30 days.
          </div>
          <button className="rbi-btn rbi-btn-ghost" onClick={onClose}>Close</button>
        </div>
      )}
    >
      <div className="rbi-score-detail">
        <div className="rbi-score-detail-summary">
          <div className="rbi-score-bar-wrap">
            <div className="rbi-score-bar">
              <div className="rbi-score-bar-fill" style={{ width: pct + "%" }} />
              <div className="rbi-score-bar-marker" style={{ left: pct + "%" }} />
            </div>
            <div className="rbi-score-bar-ticks">
              <span>0</span><span>100</span><span>150</span><span>200</span><span>250</span><span>300</span>
            </div>
          </div>
          <p className="rbi-score-summary-text">{s.sentence}</p>
        </div>

        <div className="rbi-score-drivers">
          <div className="rbi-score-drivers-hd">
            <span>Driver</span>
            <span>Weight</span>
            <span>Your score</span>
          </div>
          {s.drivers.map((d) => (
            <div key={d.name} className="rbi-driver">
              <div className="rbi-driver-name">
                <div className="rbi-driver-name-top">
                  <b>{d.name}</b>
                  <span className={"rbi-driver-band rbi-band-" + d.band.toLowerCase()}>{d.band}</span>
                </div>
                <p>{d.note}</p>
              </div>
              <div className="rbi-driver-weight">{d.weight}%</div>
              <div className="rbi-driver-meter">
                <div className="rbi-driver-meter-bar">
                  <div className={"rbi-driver-meter-fill rbi-band-fill-" + d.band.toLowerCase()} style={{ width: d.value + "%" }} />
                </div>
                <div className="rbi-driver-meter-val">{d.value}</div>
              </div>
            </div>
          ))}
        </div>

        <div className="rbi-modal-callout">
          <div className="rbi-modal-callout-eb">How we report</div>
          <p>
            Revenued reports your tradeline activity to the SBFE alongside Dun &amp; Bradstreet
            and Experian Business. The score you see here is the SBFE composite — the same one
            most small-business lenders pull when reviewing an application. We update it
            within 24 hours of any new bank or tradeline activity.
          </p>
        </div>
      </div>
    </ModalShell>
  );
}

// ── Cash flow breakdown ─────────────────────────────────────────────────────
function BreakdownView({ open, onClose, profile }) {
  if (!profile) return null;
  const cf = profile.cashflow;
  return (
    <ModalShell
      open={open}
      onClose={onClose}
      eyebrow="Cash flow breakdown · last 30 days"
      title={cf.headline}
      footer={(
        <div className="rbi-foot-row">
          <div className="rbi-foot-note">
            Data sourced via Plaid from {profile.business.bank}. We re-read your account
            every 6 hours and write a snapshot when something changes.
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <button className="rbi-btn rbi-btn-ghost" onClick={onClose}>Close</button>
            <a className="rbi-btn rbi-btn-primary" href="RBI Cash Flow.html" onClick={(e) => { e.preventDefault(); window.RBI_NAV("cashflow"); onClose(); }} style={{ textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6 }}>
              Open full report <span style={{ fontSize: 15, lineHeight: 1 }}>→</span>
            </a>
          </div>
        </div>
      )}
    >
      <div className="rbi-breakdown">
        <p className="rbi-breakdown-narrative">{cf.narrative}</p>

        <div className="rbi-breakdown-metrics">
          {cf.metrics.map((m) => (
            <div key={m.label} className="rbi-bmetric">
              <div className="rbi-bmetric-lab">{m.label}</div>
              <div className="rbi-bmetric-val">{m.value}</div>
              <div className={"rbi-bmetric-delta rbi-tone-" + m.tone}>{m.delta}</div>
            </div>
          ))}
        </div>

        <div className="rbi-breakdown-section">
          <div className="rbi-breakdown-eb">Anomalies we noticed</div>
          {cf.anomalies.map((a, i) => (
            <div key={i} className={"rbi-anomaly-row rbi-anomaly-" + a.kind}>
              <div className="rbi-anomaly-dot" />
              <div className="rbi-anomaly-text">
                <b>{a.label}</b>
                <span>{a.detail}</span>
              </div>
            </div>
          ))}
        </div>

        <div className="rbi-modal-callout">
          <div className="rbi-modal-callout-eb">What we see · what we don't</div>
          <p>
            Through Plaid, we see your transactions and balances on {profile.business.bank}.
            We don't see — and don't store — your login credentials, your card numbers, or
            transactions on any account you haven't connected. You can revoke the
            connection any time from your data settings.
          </p>
        </div>
      </div>
    </ModalShell>
  );
}

// ── Tile detail (eligibility) ───────────────────────────────────────────────
function TileDetailView({ open, onClose, tile }) {
  if (!tile) return null;
  const statusCopy = {
    "recommended": "Available today · recommended fit",
    "available": "Available today",
    "qualify-soon": "Not yet · would qualify with these changes",
    "not-recommended": "Available but not recommended yet",
    "reapproved": "Re-approved · originally declined Jan 2026",
  };
  return (
    <ModalShell
      open={open}
      onClose={onClose}
      eyebrow={statusCopy[tile.status] || "Funding option"}
      title={tile.product}
      footer={(
        <div className="rbi-foot-row">
          {tile.status === "not-recommended" ? (
            <div className="rbi-foot-note">
              We can still place this advance if you'd like. We'd rather you didn't right
              now, and we're telling you that on purpose. "Apply anyway" is two screens away,
              not one click.
            </div>
          ) : tile.status === "qualify-soon" ? (
            <div className="rbi-foot-note">
              We'll let you know the moment your numbers cross the threshold — no need to
              keep checking.
            </div>
          ) : (
            <div className="rbi-foot-note">
              Accepting this offer routes you to the funder's secure form. Revenued sees the
              outcome but never your sensitive submission data.
            </div>
          )}
          <div style={{ display: "flex", gap: 10 }}>
            <button className="rbi-btn rbi-btn-ghost" onClick={onClose}>Not now</button>
            {tile.status === "not-recommended" ? (
              <button className="rbi-btn rbi-btn-muted" onClick={onClose}>Apply anyway</button>
            ) : tile.status === "qualify-soon" ? (
              <button className="rbi-btn rbi-btn-primary" onClick={onClose}>Notify me when eligible</button>
            ) : (
              <button className="rbi-btn rbi-btn-primary" onClick={onClose}>Continue with {tile.funder.split(" ")[0]}</button>
            )}
          </div>
        </div>
      )}
    >
      <div className="rbi-tiledetail">
        <div className="rbi-tiledetail-summary">
          <div className="rbi-tiledetail-amount">{tile.amount}</div>
          <div className="rbi-tiledetail-meta">
            <div><span>Funder</span><b>{tile.funder}</b></div>
            <div><span>Rate</span><b>{tile.rate}</b></div>
            <div><span>Term</span><b>{tile.term}</b></div>
          </div>
        </div>

        <p className="rbi-tiledetail-note">{tile.note}</p>

        {tile.funderType === "financelogic" ? (
          <div className="rbi-fl-callout">
            <div className="rbi-fl-callout-bracket"></div>
            <div>
              <b>Brokered through FinanceLogic</b>
              <p>
                {tile.funder} is one of the funders in FinanceLogic's network — Revenued's
                brokerage arm. We surface it here because they would likely approve you on
                this product. If you continue, you'll fill out their application, not ours,
                and they'll communicate with you directly.
              </p>
            </div>
          </div>
        ) : (
          <div className="rbi-direct-callout">
            <div>
              <b>This is a Revenued product</b>
              <p>You'd be funded by us directly. No third party involved.</p>
            </div>
          </div>
        )}
      </div>
    </ModalShell>
  );
}

// ── Move detail (Why this matters) ──────────────────────────────────────────
function MoveDetailView({ open, onClose, move }) {
  if (!move) return null;
  return (
    <ModalShell
      open={open}
      onClose={onClose}
      eyebrow="Why this matters"
      title={move.title}
      footer={(
        <div className="rbi-foot-row">
          <div className="rbi-foot-note">{move.impact}</div>
          <button className="rbi-btn rbi-btn-ghost" onClick={onClose}>Got it</button>
        </div>
      )}
    >
      <div className="rbi-movedetail">
        <p>{move.detail}</p>
      </div>
    </ModalShell>
  );
}

Object.assign(window, { ScoreDetailView, BreakdownView, TileDetailView, MoveDetailView });
