/**
 * ReportSummary — Reusable report summary card (Swift Reports-tab styling).
 *
 * Props:
 *   scans            (array)  — Scans to summarise
 *   title            (string) — Section heading (default: "Report Summary")
 *   properties       (array)  — Properties array (for general summary property count).
 *                                Passing an array (even empty) selects the "general"
 *                                context; omitting it selects "per-property/unassigned".
 *   unassignedCount  (number) — Count of unassigned scans (general summary only)
 *   roomCount        (number) — Override room count (optional — auto-computed if omitted)
 *
 * Computes: total scans, unique rooms, latest scan date, highest severity, average risk.
 * Works for both general (all scans) and per-property (filtered) contexts.
 *
 * Layout (ported from the Swift app's canonical Reports tab):
 *   1. Three stat tiles — Scans, Properties (general) or Rooms (per-property/unassigned),
 *      Avg risk.
 *   2. Centrepiece "Average Risk · Confidence Bands" card: a segmented band bar
 *      (LOW/MODERATE/HIGH/CRITICAL) whose segment widths mirror SeverityConfig's real
 *      thresholds (0-40/40-60/60-80/80-100), with a marker + numeral positioned at the
 *      average-risk percentage. Secondary chips (latest scan date, highest severity) and
 *      the photo-provenance line are folded in beneath so no prior information is lost.
 *
 * rs* local helpers are namespaced to this file per CLAUDE.md (no module system —
 * every top-level var is a window global).
 */

// Band colours for the segmented bar — CLAUDE.md's four design tokens (good/fair/poor/
// very_poor). Kept local rather than added to SeverityConfig because SeverityConfig's
// shared levels intentionally reuse `text-warning` for both high and critical elsewhere
// in the app; this gauge needs all four visually distinct, as in the Swift reference.
var rsBandOrder = ['low', 'moderate', 'high', 'critical'];
var rsBands = {
    low:      { label: 'Low',      widthPct: 40, solid: '#0fbd80', muted: 'rgba(15,189,128,0.55)' },
    moderate: { label: 'Moderate', widthPct: 20, solid: '#d4a373', muted: 'rgba(212,163,115,0.65)' },
    high:     { label: 'High',     widthPct: 20, solid: '#D4836B', muted: 'rgba(212,131,107,0.65)' },
    critical: { label: 'Critical', widthPct: 20, solid: '#c1440e', muted: 'rgba(193,68,14,0.7)' },
};
// Divider colour between bar segments — matches the bio-bg card's base fill so the gap
// reads as a seam rather than a stray line, regardless of which bio-bg-N offset wraps it.
var rsBarDividerColor = '#F7F3E0';

// Inline SVG camera glyph — "photo_camera"/"camera" are not in the Material Symbols
// subset (assets/fonts/symbols.icons.txt); the closest listed icon (add_a_photo) carries
// a misleading "+" badge for a stat count, so this matches the Swift look directly.
var rsCameraIcon = function (className) {
    return (
        <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ width: '20px', height: '20px' }}>
            <path d="M4 8a2 2 0 0 1 2-2h1.2a2 2 0 0 0 1.664-.89l.6-.9A2 2 0 0 1 11.13 3h1.74a2 2 0 0 1 1.664.89l.6.9A2 2 0 0 0 16.8 6H18a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8Z" />
            <circle cx="12" cy="13" r="3.3" />
        </svg>
    );
};

// One stat tile — icon chip (green), big forest numeral, muted uppercase caption.
var rsStatTile = function (iconNode, value, label) {
    return (
        <div className="bio-bg bio-bg-30 rounded-2xl shadow-soft border border-stone-100/50 p-3 flex flex-col items-center text-center gap-1">
            <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                {iconNode}
            </div>
            <p className="text-2xl font-extrabold text-forest leading-none mt-0.5">{value}</p>
            <p className="text-[9px] font-black text-sage uppercase tracking-widest">{label}</p>
        </div>
    );
};

var ReportSummary = function (props) {
    var scans = props.scans || [];
    var title = props.title || 'Report Summary';
    var properties = props.properties !== undefined ? props.properties : null;
    var unassignedCount = props.unassignedCount || 0;

    if (scans.length === 0) return null;

    // Compute stats from the scan array
    var totalScans = scans.length;

    // Unique rooms
    var roomMap = {};
    for (var i = 0; i < scans.length; i++) {
        var rn = scans[i].roomName || 'Unassigned';
        roomMap[rn] = true;
    }
    var roomCount = props.roomCount !== undefined ? props.roomCount : 0;
    if (props.roomCount === undefined) {
        for (var r in roomMap) { roomCount++; }
    }

    // Latest scan
    var latest = scans[0];
    for (var l = 1; l < scans.length; l++) {
        if (scans[l].timestamp > latest.timestamp) latest = scans[l];
    }

    // Highest severity
    var highestSev = 'low';
    for (var h = 0; h < scans.length; h++) {
        if (SeverityConfig.order(scans[h].severity) > SeverityConfig.order(highestSev)) {
            highestSev = scans[h].severity;
        }
    }
    var hSev = SeverityConfig.get(highestSev);

    // Average risk
    var sum = 0;
    for (var a = 0; a < scans.length; a++) { sum += scans[a].percentage; }
    var avgPct = Math.round(sum / scans.length);
    var avgSeverity = SeverityConfig.fromPercentage(avgPct).severity;
    var avgBand = rsBands[avgSeverity] || rsBands.low;
    // Clamp only the marker/numeral's horizontal position so it never clips the card edge
    // at 0% or 100%; segment widths (the actual threshold geometry) are never clamped.
    var markerPct = Math.max(6, Math.min(94, avgPct));

    // Photo provenance. Whether a photo still carries its original camera
    // metadata is an evidential property, not a technical curiosity: an image
    // with an intact capture timestamp, device and location is materially
    // stronger evidence than one re-saved through a messaging app, which strips
    // all three. Counted here so a report states its own evidential strength.
    var withCaptureData = 0;
    if (typeof ExifService !== 'undefined') {
        for (var c = 0; c < scans.length; c++) {
            var ctx = scans[c].captureContext;
            if (!ctx) continue;
            if (ExifService.hasCameraData(ExifService.fieldsFromCaptureContext(ctx))) withCaptureData++;
        }
    }

    // Tile 2 — Properties (general context) or Rooms (per-property/unassigned context)
    var showProperties = properties !== null;
    // A scan always belongs to SOME property, so zero is never the honest count:
    // without MANAGE_PROPERTY (the professional multi-property subscription) the
    // page passes an empty array and everything implicitly lives on one property.
    // Floor at 1; the count only exceeds 1 once the flag unlocks multi-property.
    var propertyCount = showProperties ? Math.max(1, properties.length) : 0;
    var tile2Value = showProperties ? propertyCount : roomCount;
    var tile2Label = showProperties ? (propertyCount === 1 ? 'Property' : 'Properties') : (roomCount === 1 ? 'Room' : 'Rooms');
    var tile2Icon = showProperties ? 'apartment' : 'nest_multi_room';

    return (
        <div className="space-y-3">
            <h3 className="text-[10px] font-black text-forest uppercase tracking-[0.15em]">{title}</h3>

            {/* ── Stat tiles ── */}
            <div className="grid grid-cols-3 gap-3">
                {rsStatTile(rsCameraIcon('text-primary'), totalScans, totalScans === 1 ? 'Scan' : 'Scans')}
                {rsStatTile(<span className="material-symbols-outlined text-lg">{tile2Icon}</span>, tile2Value, tile2Label)}
                {rsStatTile(<span className="material-symbols-outlined text-lg">vitals</span>, avgPct + '%', 'Avg risk')}
            </div>

            {/* ── Centrepiece: Average Risk · Confidence Bands ── */}
            <div className="bio-bg bio-bg-10 rounded-2xl shadow-soft border border-stone-100/50 p-5">
                <h4 className="text-[10px] font-black text-primary uppercase tracking-[0.2em] text-center mb-5">
                    Average Risk · Confidence Bands
                </h4>

                <div className="relative" style={{ height: '38px' }}>
                    <div className="absolute" style={{ top: 0, left: markerPct + '%', transform: 'translateX(-50%)', textAlign: 'center', filter: 'drop-shadow(0 1px 1px rgba(26,67,50,0.18))' }}>
                        <p className="font-extrabold text-xl leading-none whitespace-nowrap" style={{ color: avgBand.solid }}>{avgPct}%</p>
                        <div style={{ width: 0, height: 0, margin: '3px auto 0', borderLeft: '5px solid transparent', borderRight: '5px solid transparent', borderTop: '6px solid ' + avgBand.solid }} />
                    </div>
                </div>

                <div className="flex w-full rounded-full overflow-hidden shadow-clay" style={{ height: '14px' }}>
                    {rsBandOrder.map(function (key, idx) {
                        var band = rsBands[key];
                        return (
                            <div
                                key={key}
                                style={{
                                    flex: '0 0 ' + band.widthPct + '%',
                                    backgroundColor: band.muted,
                                    borderRight: idx < rsBandOrder.length - 1 ? '2px solid ' + rsBarDividerColor : 'none',
                                }}
                            />
                        );
                    })}
                </div>

                <div className="flex w-full mt-1.5">
                    {rsBandOrder.map(function (key) {
                        var band = rsBands[key];
                        return (
                            <p
                                key={key}
                                className="text-[8px] font-black uppercase tracking-wide text-center"
                                style={{ flex: '0 0 ' + band.widthPct + '%', color: band.solid, opacity: 0.85 }}
                            >
                                {band.label}
                            </p>
                        );
                    })}
                </div>

                {/* ── Secondary info: latest scan + highest severity, folded in as chips ── */}
                <div className="flex flex-wrap items-center gap-2 mt-4 pt-3 border-t border-forest/10">
                    <span className="bg-background-light rounded-lg px-2.5 py-1.5 flex items-center gap-1.5">
                        <span className="material-symbols-outlined text-sage text-sm">calendar_month</span>
                        <span className="text-[10px] font-bold text-forest">{FormatUtils.fullDate(latest.timestamp)}</span>
                    </span>
                    <span className="bg-background-light rounded-lg px-2.5 py-1.5 flex items-center gap-1.5">
                        <span className={'material-symbols-outlined text-sm ' + hSev.text}>{hSev.icon}</span>
                        <span className={'text-[10px] font-bold ' + hSev.text}>{'Highest: ' + hSev.labelLong}</span>
                    </span>
                    {unassignedCount > 0 && (
                        <span className="bg-background-light rounded-lg px-2.5 py-1.5 flex items-center gap-1.5">
                            <span className="text-[10px] font-bold text-forest">{'+' + unassignedCount + ' unassigned'}</span>
                        </span>
                    )}
                </div>

                {/* ── Photo provenance — subtle footer row ── */}
                {withCaptureData > 0 && (
                    <div className="flex items-center gap-1.5 mt-2.5">
                        <span className="material-symbols-outlined text-sage text-xs">verified</span>
                        <p className="text-[10px] text-forest/60 font-medium leading-relaxed">
                            <span className="font-bold text-forest/80">{withCaptureData} of {totalScans}</span>
                            {' photo' + (totalScans !== 1 ? 's' : '') + ' retain original camera details.'}
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
};

window.ReportSummary = ReportSummary;
