var _useNavigate = ReactRouterDOM.useNavigate;

/**
 * ReportsPage — Multi-property reporting dashboard.
 *
 * Information Architecture:
 *   1. General Report Summary (all scans)
 *   2. General Severity Over Time chart (all scans)
 *   3. Per-property sections (primary first), each containing:
 *      - Property header with icon, name, address, badge, scan count
 *      - <Property> Report Summary
 *      - <Property> Severity Over Time chart
 *      - Alert banner (if high/critical severity detected)
 *      - Room bento grid (top 4 rooms)
 *   4. Unassigned scans section (if any)
 *
 * Visual demarcation: each property section is wrapped in a bordered card
 * with a left accent stripe (primary for main residence, forest for others).
 * Pattern drawn from insurance/banking/property portal dashboards.
 */
var ReportsPage = function () {
    var manageProperty = useFeatureFlag('MANAGE_PROPERTY');
    var navigate = _useNavigate();
    var store = useScanStore();
    var scans = store.scans;
    var properties = store.getProperties();

    React.useEffect(function () {
        AnalyticsService.reportsViewed({ scan_count: scans.length, property_count: properties.length });
    }, []);

    // ─── Upgrade panel config ─────────────────────────────────────────────────────
    const REPORTS_UPGRADE_FEATURES = [
    { icon: 'apartment',      label: 'Per-property severity charts & room grids' },
    { icon: 'nest_multi_room',label: 'Track mould across multiple properties' },
    { icon: 'notifications',  label: 'High & critical severity alert banners' },
    { icon: 'history',        label: 'Longitudinal trend tracking over time' },
    ];

    // --- Shared helpers (delegates to GroupingUtils) ---

    var groupByRoom = function (scanList) {
        return GroupingUtils.groupByRoom(scanList);
    };

    var totalFromRooms = function (rooms) {
        var total = 0;
        for (var i = 0; i < rooms.length; i++) { total += rooms[i].count; }
        return total;
    };

    // --- Build per-property data (primary first) ---
    var propertySections = [];
    for (var p = 0; p < properties.length; p++) {
        var prop = properties[p];
        var propScans = store.getScansForProperty(prop.id);
        if (propScans.length === 0) continue;
        propertySections.push({ property: prop, scans: propScans, rooms: groupByRoom(propScans) });
    }
    // Sort: primary property first
    propertySections.sort(function (a, b) {
        if (a.property.isPrimary && !b.property.isPrimary) return -1;
        if (!a.property.isPrimary && b.property.isPrimary) return 1;
        return 0;
    });

    var unassigned = [];
    for (var u = 0; u < scans.length; u++) {
        if (!scans[u].propertyId) unassigned.push(scans[u]);
    }
    var unassignedRooms = unassigned.length > 0 ? groupByRoom(unassigned) : [];

    // --- Render: Room bento grid ---
    var renderRoomGrid = function (rooms, keyPrefix) {
        var displayRooms = rooms.slice(0, 4);
        var emptySlots = 4 - displayRooms.length;

        return (
            <div className="grid grid-cols-2 grid-rows-2 gap-3 w-full aspect-square">
                {displayRooms.map(function (room) {
                    var sev = SeverityConfig.get(room.highestSeverity);
                    var badgeText = SeverityConfig.badgeText(room.highestSeverity);
                    var latestScan = room.scans[0];
                    for (var s = 1; s < room.scans.length; s++) {
                        if (room.scans[s].timestamp > latestScan.timestamp) latestScan = room.scans[s];
                    }
                    return (
                        <div key={keyPrefix + '-' + room.roomName} onClick={function () { navigate('/scan/' + latestScan.id); }} className="group cursor-pointer bg-surface rounded-xl shadow-soft overflow-hidden flex flex-col border border-stone-100/50 btn-nature hover:bg-forest transition-all duration-300">
                            <div className="flex-1 bg-background-light relative min-h-0">
                                {latestScan.thumbnail ? (
                                    <img alt={room.roomName} className="w-full h-full object-cover" src={latestScan.thumbnail} />
                                ) : (
                                    <div className="w-full h-full flex items-center justify-center">
                                        <span className="material-symbols-outlined text-sage text-3xl">image</span>
                                    </div>
                                )}
                                <div className={'absolute top-2 right-2 backdrop-blur-sm px-2 py-1 rounded-sm flex items-center gap-1 shadow-sm ' + sev.badgeBg}>
                                    <span className={'material-symbols-outlined text-[12px] ' + badgeText}>{sev.icon}</span>
                                    <span className={'text-[10px] font-bold ' + badgeText}>{sev.label}</span>
                                </div>
                            </div>
                            <div className="p-2.5">
                                <p className="text-xs font-extrabold text-forest truncate group-hover:text-white transition-colors">{room.roomName}</p>
                                <p className="text-[10px] font-semibold text-muted group-hover:text-accent/60 transition-colors">{room.count} Scan{room.count > 1 ? 's' : ''} • {FormatUtils.timeAgo(room.latestTimestamp)}</p>
                            </div>
                        </div>
                    );
                })}
                {emptySlots > 0 && Array.apply(null, Array(emptySlots)).map(function (_, i) {
                    return (
                        <div key={keyPrefix + '-empty-' + i} className="bg-background-light rounded-xl flex flex-col items-center justify-center border border-dashed border-forest/70 opacity-60">
                            <span className="material-symbols-outlined text-sage text-2xl mb-1">add_a_photo</span>
                            <p className="text-[10px] font-bold text-forest">Scan a room</p>
                        </div>
                    );
                })}
            </div>
        );
    };

    // --- Render: Alert banner ---
    var renderAlertBanner = function (rooms) {
        var alertRoom = rooms.length > 0 && (SeverityConfig.order(rooms[0].highestSeverity) >= 2) ? rooms[0] : null;
        if (!alertRoom) return null;
        return (
            <div className="bg-warning-light rounded-xl p-4 flex items-start gap-3 border border-warning/20">
                <span className="material-symbols-outlined text-warning mt-0.5">warning</span>
                <div className="flex-1">
                    <p className="text-sm font-extrabold text-warning mb-0.5">Attention Required</p>
                    <p className="text-sm text-forest/80 font-medium leading-relaxed">
                        {alertRoom.roomName} has {SeverityConfig.get(alertRoom.highestSeverity).labelLong.toLowerCase()} severity across {alertRoom.count} scan{alertRoom.count > 1 ? 's' : ''}.
                    </p>
                </div>
            </div>
        );
    };

    // --- Render: Property section header ---
    var renderPropertyHeader = function (prop, scanTotal) {
        var displayName = prop.name || 'Unnamed Property';
        var displayAddr = prop.address || '';
        return (
            <div className="flex items-center gap-3 p-4 bg-background-light rounded-t-xl -mx-5 -mt-5 mb-4 border-b border-sage/10">
                <div className="w-10 h-10 rounded-2xl bg-surface flex items-center justify-center text-forest shrink-0 shadow-sm">
                    <span className="material-symbols-outlined text-lg">{prop.isPrimary ? 'home' : 'apartment'}</span>
                </div>
                <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                        <p className="text-sm font-extrabold text-forest truncate">{displayName}</p>
                        {prop.isPrimary && (<span className="bg-primary/15 text-primary text-[9px] px-1.5 py-0.5 rounded-full font-black uppercase shrink-0">Primary</span>)}
                    </div>
                    {displayAddr && <p className="text-[11px] font-semibold text-muted truncate">{displayAddr}</p>}
                </div>
                <div className="text-right shrink-0">
                    <p className="text-lg font-extrabold text-forest">{scanTotal}</p>
                    <p className="text-[10px] font-black text-sage uppercase tracking-widest">Scan{scanTotal !== 1 ? 's' : ''}</p>
                </div>
            </div>
        );
    };

    return (
        <Layout>
            <main className="flex-1 overflow-y-auto overflow-x-hidden pb-36">
                <PageHeader title="Reports" showMenu={true} titleClass="font-extrabold text-xl text-forest tracking-tight" />
                {scans.length === 0 ? (
                    <div className="px-6 mt-8">
                        <div className="bio-bg bio-bg-20 rounded-xl shadow-soft p-8 border border-stone-100/50 text-center">
                            <div className="w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center mx-auto mb-4">
                                <span className="material-symbols-outlined text-primary text-3xl">assessment</span>
                            </div>
                            <h3 className="font-extrabold text-forest text-lg mb-2">No Reports Yet</h3>
                            <p className="text-sm font-medium text-forest leading-relaxed">Scan areas of your property to build your mould risk report. Each scan is grouped by room.</p>
                        </div>
                    </div>
                ) : (
                    <div className="px-6 space-y-6 mt-4">

                        {/* ── General Overview ── */}
                        <ReportSummary
                            scans={scans}
                            title="General Report Summary"
                            properties={manageProperty ? propertySections.map(function (s) { return s.property; }) : []}
                            unassignedCount={manageProperty ? unassigned.length : 0}
                            roomCount={store.getScansByRoom().length}
                        />

                        <SeverityChart scans={scans} title="General Severity Report" />

                        <HealthRiskInfo />
                        
                        <UpgradePanel
                            title="Unlock Per-Property Reports"
                            description="Sign up free to see detailed reports broken down by property and room, with severity trend charts and health alerts."
                            features={REPORTS_UPGRADE_FEATURES}
                            ctaLabel="Sign Up Free — No Credit Card"
                        />

                        {/* ── Per-Property Sections — gated by MANAGE_PROPERTY flag ── */}
                        {manageProperty && propertySections.map(function (section) {
                            var prop = section.property;
                            var scanTotal = totalFromRooms(section.rooms);
                            var accentClass = prop.isPrimary ? 'border-l-primary' : 'border-l-forest/40';

                            return (
                                <section key={prop.id} className={'bio-bg bio-bg-20 rounded-xl shadow-soft border border-stone-100/50 border-l-4 p-5 space-y-4 ' + accentClass}>
                                    {renderPropertyHeader(prop, scanTotal)}

                                    <ReportSummary
                                        scans={section.scans}
                                        title={prop.name + ' Report Summary'}
                                    />

                                    <SeverityChart
                                        scans={section.scans}
                                        title={(prop.name || 'Property') + ' Severity Report'}
                                    />

                                    {renderAlertBanner(section.rooms)}
                                    {renderRoomGrid(section.rooms, prop.id)}
                                    <FindSpecialistPanel context="reports" />
                                </section>
                            );
                        })}

                        {/* ── Unassigned / All Scans ── */}
                        {(manageProperty ? unassigned.length > 0 : scans.length > 0) && (
                            <section className="bio-bg bio-bg-20 rounded-xl shadow-soft border border-stone-100/50 border-l-4 border-l-sage/40 p-5 space-y-4">
                                <div className="flex items-center gap-3 p-4 bg-background-light rounded-t-xl -mx-5 -mt-5 mb-4 border-b border-sage/10">
                                    <div className="w-10 h-10 rounded-2xl bg-surface flex items-center justify-center text-sage shrink-0 shadow-sm">
                                        <span className="material-symbols-outlined text-lg">help_outline</span>
                                    </div>
                                    <div className="flex-1">
                                        <p className="text-sm font-extrabold text-forest">{manageProperty ? 'Unassigned Scans' : 'All Scans'}</p>
                                        <p className="text-[11px] font-semibold text-muted">{manageProperty ? 'Not linked to a property yet' : 'All scans grouped by room'}</p>
                                    </div>
                                    <div className="text-right shrink-0">
                                        <p className="text-lg font-extrabold text-forest">{totalFromRooms(unassignedRooms)}</p>
                                        <p className="text-[10px] font-black text-sage uppercase tracking-widest">Scan{totalFromRooms(unassignedRooms) !== 1 ? 's' : ''}</p>
                                    </div>
                                </div>

                                <ReportSummary scans={manageProperty ? unassigned : scans} title={manageProperty ? 'Unassigned Report Summary' : 'Report Summary'} />
                                <SeverityChart scans={manageProperty ? unassigned : scans} title={manageProperty ? 'Unassigned Severity Report' : 'Severity Report'} />
                                {renderRoomGrid(manageProperty ? unassignedRooms : GroupingUtils.groupByRoom(scans), manageProperty ? 'unassigned' : 'all')}
                                <FindSpecialistPanel context="reports" />
                            </section>
                        )}
                    </div>
                )}
            </main>
        </Layout>
    );
};

window.ReportsPage = ReportsPage;
