var _Link_HP = ReactRouterDOM.Link;

/**
 * _FreemiumPanel_HP — the dashboard's sign-up / account promo card.
 *
 * Module scope, deliberately. It used to be declared inside HomePage's body,
 * which gave it a fresh function identity on every HomePage render — and
 * HomePage re-renders whenever the scan store or Clerk auth context changes, so
 * React tore this card down and rebuilt it each time instead of updating it.
 * Its signed-out and signed-in variants are different heights, so every rebuild
 * moved the content below it.
 *
 * The _HP suffix follows this codebase's convention for file-local globals:
 * every top-level var here becomes a window property, and "FreemiumPanel" is
 * too generic a name to own globally.
 */
var _FreemiumPanel_HP = function (props) {
    var auth = props.auth;
    var subscriptionsEnabled = props.subscriptionsEnabled;

    // Signed in -- show welcome / account card
    if (subscriptionsEnabled && auth.isSignedIn && auth.user) {
        var u = auth.user;
        var displayName = [u.firstName, u.lastName].filter(Boolean).join(' ') || u.username || 'there';
        return (
            <section className="mb-4">
                <div className="bg-gradient-to-br from-forest to-forest/80 rounded-2xl p-5 text-white shadow-2xl overflow-hidden relative">
                    <span className="material-symbols-outlined absolute -right-3 -bottom-3 text-[100px] opacity-5">verified_user</span>
                    <div className="relative z-10 flex items-center gap-4">
                        <div className="w-12 h-12 rounded-full overflow-hidden bg-primary/20 ring-2 ring-primary/40 flex items-center justify-center shrink-0">
                            {u.imageUrl ? (
                                <img src={u.imageUrl} alt={displayName} className="w-full h-full object-cover" referrerPolicy="no-referrer" />
                            ) : (
                                <span className="material-symbols-outlined text-primary text-2xl">person</span>
                            )}
                        </div>
                        <div className="flex-1 min-w-0">
                            <p className="text-[10px] font-black text-primary uppercase tracking-widest mb-0.5">Signed In</p>
                            <p className="font-extrabold text-white truncate">Welcome back, {displayName}!</p>
                            <p className="text-xs text-accent/60 font-medium mt-0.5">Your scans are saved to your account.</p>
                        </div>
                    </div>
                </div>
            </section>
        );
    }

    // SUBSCRIPTIONS flag off -- hide panel entirely
    if (!subscriptionsEnabled) return null;

    // Guest + SUBSCRIPTIONS on -- show upsell
    return (
        <section className="mb-4">
            <div className="bg-gradient-to-br from-forest to-forest/80 rounded-2xl p-6 text-white shadow-2xl overflow-hidden relative">
                <span className="material-symbols-outlined absolute -right-3 -bottom-3 text-[100px] opacity-5">workspace_premium</span>
                <div className="relative z-10">
                    <div className="flex items-center gap-2 mb-3">
                        <span className="material-symbols-outlined text-primary text-lg">workspace_premium</span>
                        <span className="text-[10px] font-black text-primary uppercase tracking-widest">Unlock Premium</span>
                    </div>
                    <h3 className="text-lg font-black tracking-tight mb-1">Get the full picture</h3>
                    <p className="text-sm text-accent/70 font-medium leading-relaxed mb-5">
                        Sign up free to access detailed reports, multi-property management, and expert mycological AI advice.
                    </p>
                    <div className="space-y-2 mb-5">
                        {[
                            { icon: 'finance',         label: 'Detailed Reports & Analytics' },
                            { icon: 'nest_multi_room', label: 'Multi-Property Management' },
                            { icon: 'auto_awesome',    label: 'In-Depth Mycological AI Advice' },
                            { icon: 'support_agent',   label: 'Find a Local Specialist' },
                        ].map(function (f) {
                            return (
                                <div key={f.icon} className="flex items-center gap-3">
                                    <span className="material-symbols-outlined text-primary text-base">{f.icon}</span>
                                    <span className="text-sm font-semibold text-accent/80">{f.label}</span>
                                </div>
                            );
                        })}
                    </div>
                    <button
                        onClick={function () { AnalyticsService.signUpInitiated({ trigger_location: 'home_panel' }); auth.openSignUp(); }}
                        className="w-full bg-primary text-white font-extrabold py-3 rounded-xl shadow-clay flex items-center justify-center gap-2 btn-nature hover:brightness-110 transition-all"
                    >
                        <span className="material-symbols-outlined text-lg">person_add</span>
                        Sign Up Free -- No Credit Card
                    </button>
                    <button
                        onClick={function () { AnalyticsService.signInInitiated({ trigger_location: 'home_panel' }); auth.openSignIn(); }}
                        className="w-full mt-2 text-accent/60 font-bold py-2 text-sm btn-nature hover:text-white transition-colors"
                    >
                        Already have an account? Sign in
                    </button>
                </div>
            </div>
        </section>
    );
};

var HomePage = function () {
    var navigate = ReactRouterDOM.useNavigate();
    var store = useScanStore();
    var auth  = useClerkAuth();
    var subscriptionsEnabled = useFeatureFlag('SUBSCRIPTIONS');
    var scanCount = store.getScanCount();
    var scans = store.scans;
    var latest = store.getLatestScan();
    var avgRisk = store.getAverageRisk();

    var lastScanText = latest ? FormatUtils.timeAgo(latest.timestamp) : 'No scans yet';
    var riskLevel = avgRisk.label;

    // Map risk label to hero gradient class
    var heroGradientMap = {
        'Unrated': 'hero-gradient-unrated',
        'Low': 'hero-gradient-low',
        'Moderate': 'hero-gradient-moderate',
        'High': 'hero-gradient-high',
        'Critical': 'hero-gradient-critical',
    };
    var heroClass = heroGradientMap[riskLevel] || 'hero-gradient-unrated';

    // CR-12: Extracted sparkline renderer
    var renderSparkline = function () {
        var sorted = scans.slice().sort(function (a, b) { return a.timestamp - b.timestamp; });
        var len = sorted.length;
        var w = 100, h = 32;
        // Inset the plot area so the end-point dot (r 2.5 + stroke) renders whole:
        // a point at 0%/100% or at the newest-scan edge otherwise lands on the
        // viewBox boundary and the SVG viewport crops the circle.
        var p = 4;
        var pts = [];
        for (var i = 0; i < len; i++) {
            // len === 1 would divide by zero (NaN cx → dot collapses to the left
            // edge, half-cropped) — a single scan plots as one centred point.
            var fx = len === 1 ? 0.5 : i / (len - 1);
            pts.push({ x: p + fx * (w - p * 2), y: p + (1 - sorted[i].percentage / 100) * (h - p * 2) });
        }
        var line = pts.map(function (p, j) { return (j === 0 ? 'M' : 'L') + p.x.toFixed(1) + ' ' + p.y.toFixed(1); }).join(' ');
        var fill = line + ' L' + pts[len - 1].x.toFixed(1) + ' ' + h + ' L' + pts[0].x.toFixed(1) + ' ' + h + ' Z';
        return (
            <svg className="w-full mb-3" viewBox={'0 0 ' + w + ' ' + h} preserveAspectRatio="xMidYMid meet" style={{ height: '32px' }}>
                <path d={fill} fill="rgba(15,189,128,0.15)" className="group-hover:fill-primary/20" />
                <path d={line} fill="none" stroke="#0fbd80" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" />
                <circle cx={pts[len - 1].x} cy={pts[len - 1].y} r="2.5" fill="#0fbd80" stroke="white" strokeWidth="1.5" />
            </svg>
        );
    };


    return (
        <Layout>
            <main className="flex-1 overflow-y-auto overflow-x-hidden">
                <PageHeader title="Home" showBack={false} showMenu={true} />
                <div className="px-6 pb-36">
                    {/* Status Hero */}
                    <section className="relative mt-4 mb-4">
                        <div className={heroClass + ' bg-forest rounded-2xl p-8 text-white shadow-2xl overflow-hidden group'}>
                            {/* icon-natural-width: decorative watermark, the one icon in the app whose
                                glyph is wider than 1em (142px at 120px type). Opts out of the
                                global icon box reservation in index.html so it is not clipped. */}
                            <span className="material-symbols-outlined icon-natural-width absolute -right-4 -top-4 text-[120px] opacity-5 rotate-12 transition-transform group-hover:rotate-45 duration-1000">eco</span>

                            <div className="relative z-10">
                                <div className="flex justify-between items-start mb-12">
                                    <div>
                                        <h2 className="text-accent/60 text-xs font-bold uppercase tracking-widest mb-2">Ecosystem Rating</h2>
                                        <div className="flex items-baseline gap-2">
                                            <span className="text-5xl font-black tracking-tighter">{riskLevel}</span>
                                            {scanCount > 0 && <span className="w-3 h-3 rounded-full bg-primary animate-pulse"></span>}
                                        </div>
                                    </div>

                                    <div className="bg-white/10 backdrop-blur-md rounded-2xl min-w-[70px] p-3 text-center border border-white/5">
                                        <p className="text-[10px] font-black opacity-50 uppercase mb-1">Scans</p>
                                        <p className="text-3xl font-black">{scanCount}</p>
                                    </div>
                                </div>

                                <div className="flex items-center justify-between pt-6 border-t border-white/10">
                                    <p className="text-xs font-medium text-accent/80 flex items-center gap-2">
                                        <span className="material-symbols-outlined text-sm">schedule</span>
                                        {lastScanText}
                                    </p>
                                    <_Link_HP to="/scans" className="text-sm font-bold flex items-center gap-1 hover:gap-3 transition-all">
                                        View Details <span className="material-symbols-outlined text-base">arrow_forward</span>
                                    </_Link_HP>
                                </div>
                            </div>
                        </div>
                    </section>

                    {/* Recent Scans — directly under the rating hero (user-testing
                        feedback): the empty state points new users at photo upload,
                        which the bottom-nav FAB alone didn't surface well enough. */}
                    <RecentScans limit={10} />

                    {/* Freemium Promo Panel */}
                    <_FreemiumPanel_HP auth={auth} subscriptionsEnabled={subscriptionsEnabled} />

                    {/* Feature Grid */}
                    <section className="grid grid-cols-2 gap-4 mb-4">
                        {/* Miss Mould — spans both columns; leads the grid deliberately. */}
                        <MissMouldPanel />

                        {/* Weather — also full width, directly beneath her. Humidity is the
                            variable that actually drives mould, so it earns the space. */}
                        <WeatherPanel />

                        {/* Air Quality — sibling of Weather, same full-width treatment.
                            Outdoor air quality decides whether opening windows to manage
                            humidity is actually a good idea right now. */}
                        <AirQualityPanel />

                        {/* Severity Trend */}
                        <div
                            onClick={function () { navigate('/reports'); }}
                            className="bio-bg bio-bg-10 p-6 rounded-xl shadow-soft border border-stone-100/50 btn-nature cursor-pointer group hover:bg-forest transition-all duration-300"
                        >
                            <div className="w-12 h-12 rounded-2xl bg-background-light flex items-center justify-center mb-4 group-hover:bg-primary/20">
                                <span className="material-symbols-outlined text-forest group-hover:text-primary transition-colors">monitoring</span>
                            </div>
                            <h4 className="font-extrabold text-sm text-forest group-hover:text-white">Severity Trend</h4>
                            <p className="text-[10px] font-bold text-muted uppercase tracking-wider group-hover:text-accent/60">Detailed Analysis of Inspection Data</p>
                            {scans.length >= 2 ? renderSparkline() : (
                                <div className="w-full flex items-center justify-center mb-3" style={{ height: '32px' }}>
                                    <p className="text-[10px] text-muted group-hover:text-accent/60">2+ scans needed</p>
                                </div>
                            )}
                        </div>

                        {/* Mould Edu */}
                        <div
                            onClick={function () { navigate('/edu'); }}
                            className="bio-bg bio-bg-20 p-6 rounded-xl shadow-soft border border-stone-100/50 btn-nature cursor-pointer group hover:bg-forest transition-all duration-300"
                        >
                            <div className="w-12 h-12 rounded-2xl bg-background-light flex items-center justify-center mb-4 group-hover:bg-primary/20">
                                <span className="material-symbols-outlined text-forest group-hover:text-primary transition-colors">school</span>
                            </div>
                            <h4 className="font-extrabold text-sm text-forest group-hover:text-white">Mould Edu</h4>
                            <p className="text-[10px] font-bold text-muted uppercase tracking-wider group-hover:text-accent/60">Learn to Identify, Clean and Prevent Mould</p>
                        </div>

                        {/* Mould FAQ */}
                        <div
                            onClick={function () { navigate('/faq'); }}
                            className="bio-bg bio-bg-30 p-6 rounded-xl shadow-soft border border-stone-100/50 btn-nature cursor-pointer group hover:bg-forest transition-all duration-300"
                        >
                            <div className="w-12 h-12 rounded-2xl bg-background-light flex items-center justify-center mb-4 group-hover:bg-primary/20">
                                <span className="material-symbols-outlined text-forest group-hover:text-primary transition-colors">menu_book</span>
                            </div>
                            <h4 className="font-extrabold text-sm text-forest group-hover:text-white">Mould FAQ</h4>
                            <p className="text-[10px] font-bold text-muted uppercase tracking-wider group-hover:text-accent/60">Common Quesitons with Health and Safety Tips</p>
                        </div>

                        {/* Find a Specialist */}
                        <div
                            onClick={function () { navigate('/specialists'); }}
                            className="bio-bg bio-bg-40 p-6 rounded-xl shadow-soft border border-stone-100/50 btn-nature cursor-pointer group hover:bg-forest transition-all duration-300"
                        >
                            <div className="w-12 h-12 rounded-2xl bg-background-light flex items-center justify-center mb-4 group-hover:bg-primary/20">
                                <span className="material-symbols-outlined text-forest group-hover:text-primary transition-colors">support_agent</span>
                            </div>
                            <h4 className="font-extrabold text-sm text-forest group-hover:text-white">Find a Specialist</h4>
                            <p className="text-[10px] font-bold text-muted uppercase tracking-wider group-hover:text-accent/60">Access Mould Experts and Professional Remediators</p>
                        </div>
                    </section>

                    {/* Tip of the Week — restyled with reference design */}
                    <TipOfTheWeek />
                </div>
            </main>
        </Layout>
    );
};

window.HomePage = HomePage;
