/* Dulius App UI Kit — My Score page (v3: + Score Insights — confidence, percentile, offer estimate, risk flags) */

const STATUS_TONE = { warn: "#E05C5C", ok: "#F5A623", good: "#7BC67E" };

function RangeBar({ value }) {
  const pct = ((value - SCORE_MIN) / (SCORE_MAX - SCORE_MIN)) * 100;
  return (
    <div className="dmsrange">
      <div className="dmsrange-track">
        <div className="dmsrange-dot" style={{ left: `${pct}%` }}><span className="dnum">{value}</span></div>
      </div>
      <div className="dmsrange-ends dnum"><span>300</span><span>850</span></div>
    </div>
  );
}

function FactorCard({ f }) {
  const c = STATUS_TONE[f.tone];
  const [open, setOpen] = React.useState(false);
  const subs = f.subFactors || [];
  return (
    <Card className="dmsfactor">
      <div className="dmsfactor-head">
        <div>
          <span className="dmsfactor-label">{f.label}</span>
          <span className="dmsfactor-weight">{f.weightPct}% of score{f.verified ? " · verified" : ""}</span>
        </div>
        <span className="dmsfactor-badge" style={{ background: c + "22", color: c }}>{f.status}</span>
      </div>
      <div className="dmsfactor-bar">
        <ProgressBar value={f.contribution} color={c} height={8} />
        <span className="dmsfactor-num dnum" style={{ color: c }}>{f.contribution}<span className="dmsfactor-den">/100</span></span>
      </div>
      <p className="dmsfactor-note">{f.note}</p>
      <div className="dmsfactor-foot">
        <span className="dmsfactor-impact">Impact: <strong>{f.impact}</strong></span>
        {subs.length > 0 && <button className="dmsfactor-toggle" onClick={() => setOpen(!open)}>{open ? "Hide" : "Breakdown"} <Icon name={open ? "chevron-up" : "chevron-down"} size={13} /></button>}
      </div>
      {open && subs.length > 0 && (
        <div className="dmsfactor-subs">
          {subs.map((s, i) => (
            <div key={i} className="dmssub">
              <span className="dmssub-l">{s.label}{s.weight && s.weight !== "—" ? <em> · {s.weight}</em> : null}</span>
              <span className="dmssub-bar"><span className="dmssub-fill" style={{ width: Math.max(3, Math.min(100, s.value)) + "%", background: c }} /></span>
              <span className="dmssub-v dnum">{s.value}</span>
            </div>
          ))}
        </div>
      )}
    </Card>
  );
}

function SimRow({ s, active, onPick }) {
  return (
    <button className={`dsim ${active ? "active" : ""} ${s.id === "both" ? "best" : ""}`} onClick={onPick}>
      <span className="dsim-label">{s.label}</span>
      <span className="dsim-right">
        <span className="dsim-delta dnum">+{s.delta}</span>
        <span className="dsim-arrow"><Icon name="arrow-right" size={15} /></span>
        <span className="dsim-score dnum">{s.score}</span>
      </span>
    </button>
  );
}

function ensureScoreInsightStyles() {
  if (document.getElementById("dulius-scoreinsight-styles")) return;
  var st = document.createElement("style");
  st.id = "dulius-scoreinsight-styles";
  st.textContent = [
    ".dsi-tiles{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:14px}",
    "@media(max-width:640px){.dsi-tiles{grid-template-columns:1fr}}",
    ".dsi-tile{background:#fff;border:1px solid #e6ece8;border-radius:14px;padding:14px 16px}",
    ".dsi-tile-l{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.04em;color:#7a887f}",
    ".dsi-tile-v{font-size:22px;font-weight:800;color:#143222;margin-top:4px;line-height:1.1}",
    ".dsi-tile-s{font-size:12px;color:#6b7a70;margin-top:3px}",
    ".dsi-confbar{height:6px;border-radius:4px;background:#eef3ef;margin-top:8px;position:relative;overflow:hidden}",
    ".dsi-conffill{position:absolute;top:0;bottom:0;background:linear-gradient(90deg,#cfe0d4,#2DBD6E)}",
    ".dsi-offer{background:linear-gradient(135deg,#0f3d23,#1B5C2E);color:#fff;border-radius:16px;padding:18px 20px;margin-bottom:14px}",
    ".dsi-offer-h{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:14px}",
    ".dsi-offer-t{font-size:15px;font-weight:700}",
    ".dsi-offer-odds{font-size:12px;font-weight:700;background:rgba(255,255,255,.16);padding:5px 10px;border-radius:20px}",
    ".dsi-offer-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:14px}",
    "@media(max-width:640px){.dsi-offer-grid{grid-template-columns:repeat(2,1fr)}}",
    ".dsi-offer-k{font-size:11px;text-transform:uppercase;letter-spacing:.04em;opacity:.7}",
    ".dsi-offer-val{font-size:20px;font-weight:800;margin-top:3px}",
    ".dsi-offer-note{font-size:11.5px;opacity:.72;margin-top:12px}",
    ".dsi-flags{background:#fff;border:1px solid #e6ece8;border-radius:16px;padding:16px 18px;margin-bottom:14px}",
    ".dsi-flags-h{font-size:14px;font-weight:700;color:#143222;margin-bottom:10px;display:flex;align-items:center;gap:7px}",
    ".dsi-flag{display:flex;align-items:flex-start;gap:10px;padding:9px 0;border-top:1px solid #f0f4f1}",
    ".dsi-flag:first-of-type{border-top:none}",
    ".dsi-flag-dot{width:9px;height:9px;border-radius:50%;margin-top:4px;flex:none}",
    ".dsi-flag-t{font-weight:600;font-size:13.5px;color:#21402c}",
    ".dsi-flag-d{font-size:12.5px;color:#6b7a70;margin-top:1px}",
    ".dsi-clean{display:flex;align-items:center;gap:8px;font-size:13px;color:#1f7a44;background:#eefaf1;border-radius:10px;padding:10px 12px}",
  ].join("\n");
  document.head.appendChild(st);
}

function ScoreInsights() {
  const [m, setM] = React.useState(null);
  React.useEffect(() => {
    ensureScoreInsightStyles();
    var done = false;
    async function load() {
      try {
        var tok = null;
        if (window.Clerk && window.Clerk.session) tok = await window.Clerk.session.getToken();
        if (!tok) return;
        var r = await fetch("/api/member/score", { headers: { Authorization: "Bearer " + tok }, cache: "no-store" });
        if (!r.ok) return;
        var j = await r.json();
        if (!done) setM(j);
      } catch (e) {}
    }
    var tries = 0;
    var iv = setInterval(function () { tries++; if (window.Clerk && window.Clerk.session) { load(); clearInterval(iv); } else if (tries > 20) clearInterval(iv); }, 400);
    return function () { done = true; clearInterval(iv); };
  }, []);

  if (!m || !m.score) return null;
  var conf = m.score.confidence || {};
  var bench = m.benchmark || {};
  var off = m.offerEstimate || {};
  var flags = m.riskFlags || [];
  var sevColor = { high: "#E05C5C", medium: "#F5A623", low: "#9aa8a0" };
  var confPct = conf.span ? Math.max(20, 100 - conf.span * 1.6) : 60;

  return (
    <div>
      <div className="dsi-tiles">
        <div className="dsi-tile">
          <div className="dsi-tile-l">Confidence</div>
          <div className="dsi-tile-v">{conf.level || "—"}</div>
          <div className="dsi-tile-s">Likely range {conf.low}–{conf.high}</div>
          <div className="dsi-confbar"><div className="dsi-conffill" style={{ width: confPct + "%" }} /></div>
        </div>
        <div className="dsi-tile">
          <div className="dsi-tile-l">Peer ranking</div>
          <div className="dsi-tile-v">{bench.percentile != null ? bench.percentile + "th" : "—"}</div>
          <div className="dsi-tile-s">{bench.vsPeer || ("Among " + (bench.peerGroup || "applicants"))}</div>
        </div>
        <div className="dsi-tile">
          <div className="dsi-tile-l">Profile complete</div>
          <div className="dsi-tile-v">{m.score.completeness != null ? m.score.completeness + "%" : "—"}</div>
          <div className="dsi-tile-s">{m.completeness && m.completeness.missing && m.completeness.missing.length ? "Add: " + m.completeness.missing[0] : "All key inputs in"}</div>
        </div>
      </div>

      {off && off.eligible && off.factorRate && off.factorRate !== "—" && (
        <div className="dsi-offer">
          <div className="dsi-offer-h">
            <div className="dsi-offer-t">What you could qualify for today</div>
            <div className="dsi-offer-odds">{off.approvalOdds} approval odds</div>
          </div>
          <div className="dsi-offer-grid">
            <div><div className="dsi-offer-k">Max advance</div><div className="dsi-offer-val">{off.maxAdvance}</div></div>
            <div><div className="dsi-offer-k">Factor rate</div><div className="dsi-offer-val">{off.factorRate}</div></div>
            <div><div className="dsi-offer-k">Term</div><div className="dsi-offer-val">{off.termMonths}</div></div>
            <div><div className="dsi-offer-k">Est. payback</div><div className="dsi-offer-val">{off.estPayback || "—"}</div></div>
          </div>
          <div className="dsi-offer-note">{off.note}</div>
        </div>
      )}

      <div className="dsi-flags">
        <div className="dsi-flags-h"><Icon name="shield" size={16} /> What a funder will look at</div>
        {flags.length === 0 ? (
          <div className="dsi-clean"><Icon name="check-circle" size={15} /> No major risk flags — your profile reads clean to underwriters.</div>
        ) : flags.map(function (f, i) {
          return (
            <div key={i} className="dsi-flag">
              <span className="dsi-flag-dot" style={{ background: sevColor[f.severity] || "#9aa8a0" }} />
              <div><div className="dsi-flag-t">{f.flag}</div><div className="dsi-flag-d">{f.detail}</div></div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ensureMyScoreGateStyles() {
  if (document.getElementById("dulius-msgate-styles")) return;
  var st = document.createElement("style"); st.id = "dulius-msgate-styles";
  st.textContent = [
    ".dmsupwall{text-align:center;padding:30px 24px;border:1px solid #cfe0d4;background:linear-gradient(180deg,#f6faf7,#fff)}",
    ".dmsupwall-ic{width:54px;height:54px;border-radius:14px;background:#eafaf0;color:#1B5C2E;display:flex;align-items:center;justify-content:center;margin:0 auto 12px}",
    ".dmsupwall-h{font-size:20px;font-weight:800;color:#143222;margin:0 0 6px}",
    ".dmsupwall-p{color:#5b6b62;font-size:14px;max-width:460px;margin:0 auto 16px;line-height:1.5}",
    ".dmsupwall-list{display:inline-flex;flex-direction:column;gap:8px;text-align:left;margin:0 auto 18px}",
    ".dmsupwall-list>div{display:flex;align-items:center;gap:9px;font-size:14px;font-weight:600;color:#21402c}",
    ".dmsupwall-list svg{color:#2DBD6E;flex:none}",
    ".dmsupwall-pro{font-size:12.5px;color:#6b7a70;margin-top:12px}",
    ".dmssim-locked .dmssim-lockbody{text-align:center;padding:16px 8px}",
    ".dmssim-lockp{color:#6b7a70;font-size:13px;margin:8px 0 14px;line-height:1.5}",
  ].join("\n");
  document.head.appendChild(st);
}

function MyScore({ onNav }) {
  const d = DULIUS;
  const [sim, setSim] = React.useState("both");
  const active = d.simulator.find((s) => s.id === sim) || d.simulator[2];
  const pc = d.personalCredit;
  const tp = d.tierPath;
  const plan = (DULIUS.plans && DULIUS.plans.current) || "Free";
  const isPremium = plan !== "Free";
  const isPro = plan === "Pro";
  React.useEffect(function () { ensureMyScoreGateStyles(); }, []);

  return (
    <div className="dscreen">
      {window.ScoreInputs ? React.createElement(window.ScoreInputs) : null}
      {/* Hero */}
      <Card className="dmshero">
        <div className="dmshero-gauge"><ScoreGauge value={d.score.value} size={230} /></div>
        <div className="dmshero-side">
          <div className="dmshero-deltarow"><Delta value={d.score.delta} /> <span className="dmuted">this month</span></div>
          <p className="dmshero-msg">You're in <strong>{d.score.band}</strong>. You're <strong className="dnum">{d.milestone.points} points</strong> from {d.milestone.target} — at your current pace, about {d.milestone.etaDays} days away.</p>
          <RangeBar value={d.score.value} />
        </div>
      </Card>

      {!isPremium && (
        <Card className="dmsupwall">
          <div className="dmsupwall-ic"><Icon name="lock" size={26} /></div>
          <h3 className="dmsupwall-h">Unlock your full score breakdown</h3>
          <p className="dmsupwall-p">You're seeing your live Dulius Score. Upgrade to Premium to see exactly what's driving it — and the fastest moves to raise it.</p>
          <div className="dmsupwall-list">
            <div><Icon name="check" size={15} /> Full breakdown by factor</div>
            <div><Icon name="check" size={15} /> Profile analysis, confidence &amp; peer ranking</div>
            <div><Icon name="check" size={15} /> Your estimated offer &amp; approval odds</div>
            <div><Icon name="check" size={15} /> Debt dashboard &amp; 30/60/90-day score path</div>
            <div><Icon name="check" size={15} /> Unlimited matched offers + daily alerts</div>
          </div>
          <Button variant="accent" iconRight="arrow-right" onClick={() => onNav("plans")}>Upgrade to Premium — $19/mo</Button>
          <div className="dmsupwall-pro">Want the what-if simulator &amp; priority matching? <a className="dlink" href="#" onClick={(e) => { e.preventDefault(); onNav("plans"); }}>See Pro →</a></div>
        </Card>
      )}
      {isPremium && (
      <React.Fragment>

      {/* Score insights — confidence, percentile, offer estimate, risk flags */}
      {window.ScoreInsights ? React.createElement(window.ScoreInsights) : null}

      {/* Breakdown */}
      <div>
        <div className="dpanel-head dpadx"><h3 className="ds-h3">What makes up your score</h3><Badge tone="neutral">5 weighted factors</Badge></div>
        <div className="dmsfactors">
          {d.factors.map((f, i) => <FactorCard key={i} f={f} />)}
        </div>
      </div>

      <div className="dgrid-2">
        {/* Personal credit side-by-side */}
        <Card className="dpanel">
          <div className="dpanel-head"><h3 className="ds-h3">Dulius vs. your credit estimate</h3></div>
          <div className="dmscredit">
            <div className="dmscredit-col">
              <div className="dmscredit-v dnum" style={{ color: bandFor(d.score.value).color }}>{d.score.value}</div>
              <div className="dmscredit-l">Dulius Score</div>
              <ScorePill band={d.score.band} />
            </div>
            <div className="dmscredit-div" />
            <div className="dmscredit-col">
              <div className="dmscredit-v dnum">{pc.range}</div>
              <div className="dmscredit-l">Est. credit · {pc.label}</div>
              <Badge tone="warning">{pc.estimate}</Badge>
            </div>
          </div>
          <div className="dmscredit-note"><Icon name="info" size={13} /> Self-reported — Dulius verifies during underwriting. <a className="dlink" href="#" onClick={e=>e.preventDefault()}>Update estimate</a></div>
          <div className="dmscredit-stats">
            <div><span className="dnum">{pc.utilization}%</span><span>Utilization</span></div>
            <div><span className="dnum">{pc.payHistory}%</span><span>Pay history</span></div>
            <div><span className="dnum">{pc.derogatory}</span><span>Derogatory</span></div>
            <div><span className="dnum">{pc.openAccounts}</span><span>Open accts</span></div>
          </div>
          <div className="dmsinsight"><Icon name="info" size={16} /><span>Your personal utilization of <strong>{pc.utilization}%</strong> is hurting your fundability. Reducing it below 40% could add up to <strong>+35 points</strong>.</span></div>
        </Card>

        {/* Debt utilization */}
        <Card className="dpanel">
          <div className="dpanel-head"><h3 className="ds-h3">Debt utilization</h3><span className="dmuted dnum">{d.debt.ratio}% of revenue</span></div>
          <ProgressBar value={d.debt.ratio} color="#F5A623" height={10} />
          <div className="dmsdebt-list">
            {d.debt.obligations.map((o, i) => (
              <div key={i} className="dmsdebt-row">
                <div><div className="dmsdebt-name">{o.name} · {o.amount}</div><div className="dmsdebt-sub">{o.daily}/day · {o.remaining} left · payoff {o.payoff}</div></div>
                <span className="dmsdebt-impact dnum">payoff {o.impact}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* History + Simulator */}
      <div className="dgrid-2">
        <Card className="dpanel">
          <div className="dpanel-head"><h3 className="ds-h3">Score history</h3><Badge tone="success">+{d.history6mo[5] - d.history6mo[0]} pts · 6 mo</Badge></div>
          <div className="dtrend"><div className="dtrend-now dnum">{d.score.value}</div>{window.Sparkline && <Sparkline points={d.history6mo} w={220} h={64} />}</div>
          <div className="dtrend-labels"><span>Dec</span><span>May</span></div>
        </Card>

        {isPro ? (
        <Card className="dpanel dmssim">
          <div className="dpanel-head"><h3 className="ds-h3">Score simulator</h3><Badge tone="neutral">Pro</Badge></div>
          <div className="dmssim-rows">
            {d.simulator.map((s) => <SimRow key={s.id} s={s} active={sim === s.id} onPick={() => setSim(s.id)} />)}
          </div>
          <div className="dmssim-result">
            <div className="dmssim-result-l">Projected score</div>
            <div className="dmssim-result-v dnum" style={{ color: bandFor(active.score).color }}>{active.score}</div>
            {active.note && <div className="dmssim-result-note"><Icon name="target" size={15} /> {active.note}</div>}
          </div>
        </Card>
        ) : (
        <Card className="dpanel dmssim dmssim-locked">
          <div className="dpanel-head"><h3 className="ds-h3">Score simulator</h3><Badge tone="neutral">Pro</Badge></div>
          <div className="dmssim-lockbody">
            <div className="dmsupwall-ic"><Icon name="lock" size={22} /></div>
            <p className="dmssim-lockp">Test "what-if" moves — connect a bank, pay down a position, raise credit — and see your projected score before you act. A Pro tool.</p>
            <Button variant="accent" iconRight="arrow-right" onClick={() => onNav("plans")}>Upgrade to Pro — $49/mo</Button>
          </div>
        </Card>
        )}
      </div>

      {/* Path to next tier */}
      <Card className="dmspath">
        <div className="dmspath-head">
          <div><div className="ds-overline">Your path to {tp.advanceAt}+</div><h3 className="dmspath-title">Reach {d.milestone.target} faster</h3></div>
          <div className="dmspath-track">
            <span className="dmspath-now dnum">{tp.current}</span>
            <div className="dmspath-line"><div className="dmspath-fill" style={{ width: `${((tp.current - 450) / (tp.advanceAt - 450)) * 100}%` }} /></div>
            <span className="dmspath-target dnum">{tp.advanceAt}</span>
          </div>
        </div>
        <div className="dmspath-actions">
          {tp.actions.map((a, i) => (
            <div key={i} className="dmspath-action">
              <span className="dmspath-num dnum">{i + 1}</span>
              <span className="dmspath-atitle">{a.title}</span>
              <span className="dmspath-effort">{a.effort}</span>
              <span className="dmspath-impact dnum">+{a.impact}</span>
            </div>
          ))}
        </div>
        <div className="dmspath-cta">
          <span className="dmspath-ctatxt">Complete the first two and you'll qualify for {d.milestone.target} in ~40 days.</span>
          <Button variant="accent" iconRight="arrow-right" onClick={() => onNav("offers")}>Start my Score Builder deal</Button>
        </div>
      </Card>
      </React.Fragment>
      )}
    </div>
  );
}
Object.assign(window, { MyScore, ScoreInsights, FactorCard });
