// overview.jsx — "Overview" page (window.OverviewApp).
//
// Redesigned to match the "Overview 2" mockup: an editorial greeting, a
// two-card centerpiece (Business Credit + Cash Flow), a "Your Insights"
// benchmark strip, and a funding next-step banner.
//
// Data sources, by section:
//   - Business Credit card: LIVE — same window.RBI_API.getCreditScore() call
//     as the Business Credit page. Shows the real score/band/reason, or the
//     mockup's "no score yet" empty state when there's no DUNS on file.
//   - Cash Flow card: illustrative — there's no live cash-flow API yet, so
//     this reuses the same demo profile (window.RBI_PROFILES.declined) that
//     the Cash Flow page itself renders today. The "See the full breakdown"
//     CTA goes to that real page.
//   - Your Insights strip: illustrative — representative industry-average
//     figures (not a live comparison, since we don't have per-user cash
//     flow data to compare against). Matches the anon/"what the industry
//     looks like" variant of the mockup. The industry switcher lets you
//     preview any of the 9 industries; "View Industry Insights" goes to the
//     full page.

const { useState: useOvState, useEffect: useOvEffect } = React;

// ── Profile helpers (mirrors app.jsx's useProfile so both pages agree on
//    who's signed in, without importing across files) ─────────────────────
function getStoredProfileOv() {
    return (window.RBI_API && window.RBI_API.profile()) || {};
}
function useProfileOv() {
    const [state, setState] = useOvState(() => {
        const p = getStoredProfileOv();
        return { profile: p, settled: !!p.email };
    });
    useOvEffect(() => {
        let alive = true;
        function onProfile(e) {
            if (alive) setState({ profile: (e.detail && e.detail.profile) || {}, settled: true });
        }
        window.addEventListener("rbi:profile", onProfile);
        if (window.RBI_API && window.RBI_API.ensureProfile) {
            window.RBI_API.ensureProfile()
                .then((p) => { if (alive) setState({ profile: p || {}, settled: true }); })
                .catch(() => { if (alive) setState({ profile: {}, settled: true }); });
        } else {
            setState({ profile: {}, settled: true });
        }
        return () => { alive = false; window.removeEventListener("rbi:profile", onProfile); };
    }, []);
    return [state.profile, state.settled];
}

// ── Risk-band lookup (same 706–999 SBFE ranges as the Business Credit page) ─
const OV_SCORE_RANGES = [
    { min: 706, max: 799, label: "High Risk", dot: "#EF4444" },
    { min: 800, max: 839, label: "Moderate – High Risk", dot: "#F97316" },
    { min: 840, max: 879, label: "Moderate Risk", dot: "#F5C13D" },
    { min: 880, max: 899, label: "Low – Moderate Risk", dot: "#4CB782" },
    { min: 900, max: 999, label: "Low Risk", dot: "#2AA96B" },
];
function ovRangeMeta(v) {
    return OV_SCORE_RANGES.find(r => v >= r.min && v <= r.max) || OV_SCORE_RANGES[0];
}

// ── Greeting ────────────────────────────────────────────────────────────────
function Ov2Greeting({ businessName, ownerFirst, hasScore }) {
    return (
        <div className="rbi-greeting rbi-greeting-serif">
            <div>
                <p className="rbi-greeting-eb">
                    {hasScore ? "Today · Business Intelligence" : "Business Intelligence · connect to see your own numbers"}
                </p>
                {hasScore ? (
                    <h1>{ownerFirst} — here's <span className="accent">where {businessName} stands</span> today.</h1>
                ) : (
                    <h1>See where your business stands <span className="accent">before you apply.</span></h1>
                )}
            </div>
        </div>
    );
}

// ── Business Credit card (live) ─────────────────────────────────────────────
function Ov2ScoreCard() {
    const [user, profileLoaded] = useProfileOv();
    const duns = user.duns || "";
    const noDuns = profileLoaded && !duns;
    const [creditData, setCreditData] = useOvState(null);
    const [loading, setLoading] = useOvState(true);
    const [error, setError] = useOvState(false);

    useOvEffect(() => {
        if (!duns && !profileLoaded) { setLoading(true); setError(false); return; }
        if (!duns) { setLoading(false); setError(false); return; }
        setLoading(true);
        setError(false);
        const loginDate = new Date().toISOString().slice(0, 10);
        window.RBI_API.getCreditScore({ duns, loginDate })
            .then((res) => {
                if (res.ok && res.data && res.data.power_score != null) setCreditData(res.data);
                else setError(true);
            })
            .catch(() => setError(true))
            .finally(() => setLoading(false));
    }, [duns, profileLoaded]);

    const goFull = () => window.RBI_NAV("creditscore");
    const hasScore = !!creditData && !error;

    if (loading) {
        return (
            <div className="rbi-cp-card score">
                <div className="rbi-cp-eb">Business credit · SBFE</div>
                <div className="cs-skel cs-skel-line" style={{ width: 110, height: 44, marginBottom: 16, borderRadius: 8 }} />
                <div className="cs-skel cs-skel-line" style={{ width: "70%", marginBottom: 8 }} />
                <div className="cs-skel cs-skel-line" style={{ width: "45%" }} />
            </div>
        );
    }

    if (!hasScore) {
        return (
            <div className="rbi-cp-card score">
                <div className="rbi-cp-eb">Business credit · SBFE</div>
                <div className="ov2-empty">
                    {duns ? (
                        <div className="ov2-locked-num"><b>—</b><span>out of 999<br />SBFE composite score</span></div>
                    ) : null}
                    <h3>No score yet — we need a DUNS match first.</h3>
                    <p>We pull your D&amp;B SBFE score from public business records. Once we can match your business, your score and its history appear here.</p>
                    <span className="ov2-duns">{duns ? <>DUNS on file <b>{duns}</b></> : <>No DUNS on file yet</>}</span>
                    <button className="rbi-cp-action" onClick={goFull} style={{ marginTop: 4 }}>View Business Credit <span className="arrow">→</span></button>
                </div>
            </div>
        );
    }

    const score = Number(creditData.power_score);
    const meta = ovRangeMeta(score);
    const pct = Math.round(((score - 706) / (999 - 706)) * 100);
    const reason = creditData.reason_1;

    return (
        <div className="rbi-cp-card score">
            <div className="rbi-cp-eb">Business credit · SBFE</div>
            <div className="rbi-score-block">
                <div className="rbi-score-numwrap">
                    <span className="rbi-score-num">{score}</span>
                    <span className="rbi-score-num-of">
                        <span className="of-num">out of 999</span>
                        <span className="of-meta">SBFE composite score</span>
                    </span>
                </div>
                <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
                    <span className="rbi-score-band" style={{ background: meta.dot + "1F", color: meta.dot }}>
                        <span className="dot" style={{ background: meta.dot }} />{meta.label}
                    </span>
                </div>
                <div className="rbi-score-meter">
                    <div className="rbi-score-meter-fill" style={{ width: Math.max(0, Math.min(100, pct)) + "%" }} />
                </div>
                <div className="rbi-score-meter-ticks"><span>706</span><span>840</span><span>999</span></div>
                {reason ? <p className="rbi-score-sentence">{reason}</p> : null}
                <button className="rbi-cp-action" onClick={goFull}>What's behind this score? <span className="arrow">→</span></button>
            </div>
        </div>
    );
}

// ── Cash Flow card (illustrative — mirrors the Cash Flow page's own demo data) ─
function Ov2AnomalyRow({ anomaly, onClick }) {
    return (
        <button className={"rbi-anomaly " + anomaly.kind} onClick={onClick}>
            <span className="rbi-anomaly-dot" />
            <span className="rbi-anomaly-label">{anomaly.label}</span>
            <span className="rbi-anomaly-detail">{anomaly.detail}</span>
        </button>
    );
}

function Ov2CashFlowCard() {
    const profile = (window.RBI_PROFILES && window.RBI_PROFILES.declined) || null;
    const goBreakdown = () => window.RBI_NAV("cashflow");
    if (!profile) return null;

    return (
        <div className="rbi-cp-card narrative">
            <div className="rbi-cp-eb">Cash flow · last 30 days</div>
            <div className="rbi-narrative-block">
                <h3 className="rbi-narrative-headline serif">{profile.cashflow.headline}</h3>
                <div className="rbi-anomalies">
                    {profile.cashflow.anomalies.slice(0, 2).map((a, i) => (
                        <Ov2AnomalyRow key={i} anomaly={a} onClick={goBreakdown} />
                    ))}
                </div>
                <button className="rbi-cp-action" onClick={goBreakdown}>See the full breakdown <span className="arrow">→</span></button>
            </div>
        </div>
    );
}

// ── Your Insights strip (illustrative industry snapshot) ───────────────────
const OV_IND_ANCHORS = {
    restaurant: { label: "Restaurant & Food Services", avgRev: 42000, growth: "8.4", cohortN: 3184 },
    retail: { label: "Retail", avgRev: 55000, growth: "9.1", cohortN: 4210 },
    contractor: { label: "Contractor & Construction", avgRev: 68000, growth: "11.2", cohortN: 1860 },
    healthcare: { label: "Healthcare & Wellness", avgRev: 72000, growth: "7.8", cohortN: 1420 },
    auto: { label: "Auto Services", avgRev: 38000, growth: "6.5", cohortN: 2260 },
    beauty: { label: "Beauty & Personal Care", avgRev: 28000, growth: "10.3", cohortN: 1980 },
    logistics: { label: "Transportation & Logistics", avgRev: 85000, growth: "12.1", cohortN: 1540 },
    professional: { label: "Professional Services", avgRev: 60000, growth: "8.9", cohortN: 2040 },
    other: { label: "Other", avgRev: 45000, growth: "7.5", cohortN: 2600 },
};

function iiUSD(n, short) {
    const v = Math.abs(n);
    if (short && v >= 1000) return "$" + (n / 1000).toFixed(n % 1000 === 0 ? 0 : 1) + "K";
    return "$" + Math.round(n).toLocaleString("en-US");
}

function buildOv2Snapshot(industryValue) {
    const a = OV_IND_ANCHORS[industryValue] || OV_IND_ANCHORS.other;
    const inflow = a.avgRev;
    const outflow = Math.round(inflow * 0.905);
    const balance = Math.round(inflow * 0.34);
    const mk = (key, label, ind) => ({
        key, label, ind,
        med: Math.round(ind * 0.96),
        range: [Math.round(ind * 0.55), Math.round(ind * 1.75)],
        trend: a.growth + "%",
    });
    return [
        mk("inflow", "Monthly Cash Inflow", inflow),
        mk("outflow", "Monthly Cash Outflow", outflow),
        mk("balance", "Avg Starting Balance", balance),
    ];
}

function ovIndustryForUser(user) {
    if (window.RBI_API && window.RBI_API.isDeclinedUser && window.RBI_API.isDeclinedUser(user)) {
        return (window.RBI_ENV && window.RBI_ENV.declinedDefaultIndustry) || "restaurant";
    }
    const raw = String((user && user.industry) || "").trim().toLowerCase();
    if (OV_IND_ANCHORS[raw]) return raw;
    const byLabel = Object.keys(OV_IND_ANCHORS).find((k) => OV_IND_ANCHORS[k].label.toLowerCase() === raw);
    return byLabel || "restaurant";
}

function Ov2Insights() {
    const [user] = useProfileOv();
    const [industry, setIndustry] = useOvState(() => ovIndustryForUser(user));
    useOvEffect(() => {
        setIndustry(ovIndustryForUser(user));
    }, [user && user.industry, user && user.isDeclinedUser, user && user.email]);
    const anchor = OV_IND_ANCHORS[industry] || OV_IND_ANCHORS.restaurant;
    const rows = buildOv2Snapshot(industry);
    const goFull = () => window.RBI_NAV("insights");

    return (
        <section className="ov2-ins">
            <div className="ov2-ins-hd" style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
                <div>
                    <p className="ov2-eb"><i />Your insights · last 12 months</p>
                    <h2 className="serif">What the industry looks like</h2>
                    <p>{anchor.label}</p>

                    {/* Hidden for now */}
                    {/*<p>{anchor.label} averages, n = {anchor.cohortN.toLocaleString("en-US")}. Connect your bank to see your own figures beside them.</p> */}
                </div>
                {/* <div className="ov-select">
                    <select value={industry} onChange={e => setIndustry(e.target.value)} aria-label="Choose industry">
                        {Object.keys(OV_IND_ANCHORS).map(k => <option key={k} value={k}>{OV_IND_ANCHORS[k].label}</option>)}
                    </select>
                </div> */}
            </div>
            <div className="ov2-ins-grid">
                {rows.map(m => (
                    <div key={m.key} className="ov2-kpi">
                        <div className="ov2-kpi-lab">{m.label}</div>
                        <div className="ov2-kpi-val">{iiUSD(m.ind)}</div>
                        <div className="ov2-kpi-row"><span>Industry median</span><b>{iiUSD(m.med, true)}</b></div>
                        <div className="ov2-kpi-row"><span>Typical range</span><b>{iiUSD(m.range[0], true)}–{iiUSD(m.range[1], true)}</b></div>
                        <div className="ov2-kpi-foot">
                            <span className="ov2-badge near">Industry trend</span>
                            <span className="ov2-delta up">▴ +{m.trend}</span>
                        </div>
                    </div>
                ))}
            </div>
            <button className="rbi-cp-action" style={{ marginTop: 14 }} onClick={goFull}>View Industry Insights <span className="arrow">→</span></button>
        </section>
    );
}

// ── Next-step banner ─────────────────────────────────────────────────────────
function Ov2NextStep() {
    const [user] = useProfileOv();
    const isDeclinedUser = !!(window.RBI_API && window.RBI_API.isDeclinedUser && window.RBI_API.isDeclinedUser(user));
    const [isExpanded, setIsExpanded] = useState(false);
    const [expandedIndex, setExpandedIndex] = React.useState(null);
    const points = [
        { t: "teal", b: "Benefits", s: "We connect you to the full range of small business financing: SBA loans, term loans, business lines of credit, equipment financing, invoice factoring, commercial real estate loans, revenue-based financing, and more. Because we work with 50+ lenders, you're matched to the product that actually fits your situation — not a one-size-fits-all loan." },
        { t: "teal", b: "About Pre-qualification", s: "Pre-qualification takes just a few minutes. Once you're matched with a lender, decisions often come within hours, and many lenders fund in as little as 24 hours after approval. Faster products like equipment financing and invoice factoring can fund in 24–48 hours." },
        { t: "teal", b: "What is Finance Logic?", s: "FinanceLogic is a small business funding marketplace. Instead of applying to lenders one at a time, you complete a single application and we match you with vetted lenders from our network who actively fund businesses like yours — based on your revenue, time in business, and goals. You compare real offers and choose what fits, all in one place." },
        { t: "teal", b: "Check options", s: "Checking your options through FinanceLogic is free and uses a soft credit pull, which doesn't impact your score. A hard inquiry only happens later — and only with your consent — if you move forward with a specific lender's offer." },
    ];
    return (
        <section className="ov2-partner">
            <div className="ov2-partner-top">
                <div>
                    <p className="ov2-eb"><i />Next step</p>
                    <h2 className="serif">
                        {isDeclinedUser
                            ? <>Ready to explore your <em>funding options?</em></>
                            : <>Explore your <em>eligibility</em>?</>
                        }
                    </h2>
                    <p>
                        {isDeclinedUser
                            ? <>If you're ready to explore funding options, see what you may qualify for through FinanceLogic — checking your eligibility is a soft review and does not affect your credit.</>
                            : <>Check funding eligibility whenever you're ready — checking is a soft review and doesn't affect your credit.</>
                        }
                    </p>
                    <div className="ov2-actions">
                        {isDeclinedUser
                            ? (<a className="ov2-btn primary" href="https://financelogic.com/apply/" target="_blank" rel="noreferrer">Apply with financelogic <span>→</span></a>)
                            : (<a className="ov2-btn primary" href="https://info.revenued.com/apply" target="_blank" rel="noreferrer">Apply with Revenued <span>→</span></a>)}

                        {/* <button className="ov2-btn ghost" onClick={() => window.RBI_NAV("creditscore")}>View Full Credit Report</button> */}
                    </div>
                </div>
                <div className="ov2-points">
                    {points.map((p, index) => {
                        const isExpanded = expandedIndex === index;
                        return (
                            <div key={p.b} className={"ov2-point " + p.t}>
                                <div className="ov2-point-ic">✓</div>
                                <div>
                                    {/* <b>{p.b}</b> */}
                                    <span className={isExpanded ? "" : "ov2-point-truncated-text"}>{p.s}</span>
                                    <span className="ii-tile-cta ov2-point-cta" onClick={() => setExpandedIndex(isExpanded ? null : index)}>
                                        {isExpanded ? 'View Less' : 'View More'}
                                    </span>
                                </div>
                            </div>
                        )
                    })}
                </div>
            </div>
            <div className="ov2-partner-foot">
                <b>FinanceLogic is an affiliate of Revenued.</b> Checking eligibility is a soft review and does not affect your business or personal credit.
            </div>
        </section>
    );
}

// ── Page footer (same look as the other RBI pages) ─────────────────────────
function OvFooter() {
    return (
        <footer className="cs-page-footer">
            <div className="cs-footer-left">
                <span>+1 877-662-3489 (M-F 9am – 7pm)</span>
            </div>
            <div className="cs-footer-center">
                <span>©2026 Revenued (Business Intelligence)</span>
                <span className="cs-footer-sep">|</span>
                <a href="#">All Rights Reserved</a>
                <span className="cs-footer-sep">|</span>
                <a href="#">Terms of Service</a>
                <span className="cs-footer-sep">|</span>
                <a href="#" onClick={(e) => { e.preventDefault(); window.RBI_NAV("privacy"); }}>Privacy Policy</a>
            </div>
            <div className="cs-footer-social">
                <a href="https://www.youtube.com/@revenuedcard" aria-label="YouTube" className="cs-footer-icon" target="_blank" rel="noopener noreferrer">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M22.54 6.42a2.78 2.78 0 0 0-1.95-1.96C18.88 4 12 4 12 4s-6.88 0-8.59.46A2.78 2.78 0 0 0 1.46 6.42 29 29 0 0 0 1 12a29 29 0 0 0 .46 5.58a2.78 2.78 0 0 0 1.95 1.96C5.12 20 12 20 12 20s6.88 0 8.59-.46a2.78 2.78 0 0 0 1.95-1.96A29 29 0 0 0 23 12a29 29 0 0 0-.46-5.58z" />
                        <polygon points="9.75 15.02 15.5 12 9.75 8.98 9.75 15.02" fill="#00122B" />
                    </svg>
                </a>
                <a href="https://www.facebook.com/revenued/" aria-label="Facebook" className="cs-footer-icon" target="_blank" rel="noopener noreferrer">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" />
                    </svg>
                </a>
                <a href="https://www.linkedin.com/company/revenued" aria-label="LinkedIn" className="cs-footer-icon" target="_blank" rel="noopener noreferrer">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z" />
                        <rect x="2" y="9" width="4" height="12" /><circle cx="4" cy="4" r="2" />
                    </svg>
                </a>
                <a href="https://www.instagram.com/revenuedcard/" aria-label="Instagram" className="cs-footer-icon" target="_blank" rel="noopener noreferrer">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <rect x="2" y="2" width="20" height="20" rx="5" /><circle cx="12" cy="12" r="4" />
                        <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none" />
                    </svg>
                </a>
                <a href="https://twitter.com/revenuedcard" aria-label="X / Twitter" className="cs-footer-icon" target="_blank" rel="noopener noreferrer">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.746l7.73-8.835L2.25 2.25H8.08l4.253 5.622zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                    </svg>
                </a>
            </div>
        </footer>
    );
}

// ── Root ────────────────────────────────────────────────────────────────────
function OverviewApp() {
    const [user, profileLoaded] = useProfileOv();
    const [hasScore, setHasScore] = useOvState(false);

    // Lightweight, non-blocking peek so the greeting copy can match the score
    // card's state without a second full fetch cycle driving the render.
    useOvEffect(() => {
        let alive = true;
        const duns = user.duns || "";
        if (!duns) { setHasScore(false); return; }
        const loginDate = new Date().toISOString().slice(0, 10);
        window.RBI_API.getCreditScore({ duns, loginDate })
            .then((res) => { if (alive && res.ok && res.data && res.data.power_score != null) setHasScore(true); })
            .catch(() => { });
        return () => { alive = false; };
    }, [user.duns]);

    const businessName = (user.business_name && user.business_name.trim()) || "Your Business";
    const ownerFull = (user.owner_name || [user.first_name, user.last_name].filter(Boolean).join(" ")).trim();
    const ownerFirst = ownerFull ? ownerFull.split(" ")[0] : "Welcome";

    return (
        <div className="rbi-app">
            <window.RBITopbar
                business={{
                    name: businessName,
                    owner: ownerFull || "Your Account",
                    city: (user.city && user.city.trim()) || "",
                    duns: user.duns || "",
                    dunsLoading: !profileLoaded,
                    bank: "",
                }}
                activeView="home"
            />

            <div className="rbi-body">
                <Ov2Greeting businessName={businessName} ownerFirst={ownerFirst} hasScore={hasScore} />

                <div className="rbi-centerpiece">
                    <div className="rbi-cp-single">
                        <Ov2ScoreCard />
                        {/* <Ov2CashFlowCard /> */}
                    </div>
                </div>

                <Ov2Insights />
                <Ov2NextStep />

                <div className="rbi-footer">
                    <div className="rbi-footer-links">
                        <span className="plaid-status">
                            <span className="dot" /> {hasScore ? "Live credit score connected" : "Sample figures shown until your DUNS is matched"}
                        </span>
                    </div>
                </div>
            </div>

            <OvFooter />
        </div>
    );
}

window.OverviewApp = OverviewApp;