import { useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  API_BASE,
  ExtendedStats,
  fetchExtendedStats,
  formatInt,
  formatPrice,
  formatPriceCompact,
  GrowthPoint,
  ORIGIN_KEYS,
  ORIGIN_LABELS,
} from '../api'
import CountUp from '../components/CountUp'
import EmptyState from '../components/EmptyState'
import { IconDownload } from '../components/Icons'
import OriginBadge from '../components/OriginBadge'
import Skeleton from '../components/Skeleton'
import StoreLogo from '../components/StoreLogo'

const DEFAULT_TITLE = 'Fabri-Ka — Tous les produits québécois. Un seul endroit.'

// ---------------------------------------------------------------------------
// Formatting helpers local to the stats page
// ---------------------------------------------------------------------------

const percentFormatter = new Intl.NumberFormat('fr-CA', {
  style: 'percent',
  maximumFractionDigits: 1,
})

function formatShare(part: number, total: number): string {
  if (!total) return ''
  return percentFormatter.format(part / total)
}

const dayFormatter = new Intl.DateTimeFormat('fr-CA', {
  day: 'numeric',
  month: 'short',
})

function formatDay(day: string): string {
  const d = new Date(`${day}T00:00:00`)
  return Number.isNaN(d.getTime()) ? day : dayFormatter.format(d)
}

const BUCKET_LABELS: Record<string, string> = {
  '0-10': 'Moins de 10 $',
  '10-25': '10 – 25 $',
  '25-50': '25 – 50 $',
  '50-100': '50 – 100 $',
  '100-250': '100 – 250 $',
  '250-1000': '250 – 1 000 $',
  '1000+': '1 000 $ et plus',
}

const REPORT_URL = `${API_BASE}/api/report.pdf`
const REPORT_HINT = 'Rapport de marché complet — PDF, mise à jour en continu'

// Availability keys → French label + CSS slug (pine / muted / border)
const AVAILABILITY_META: Record<
  string,
  { label: string; slug: string; order: number }
> = {
  'en stock': { label: 'En stock', slug: 'stock', order: 0 },
  rupture: { label: 'En rupture', slug: 'rupture', order: 1 },
  inconnu: { label: 'Inconnu', slug: 'inconnu', order: 2 },
}

// ---------------------------------------------------------------------------
// Growth — hand-rolled SVG area chart (terracotta line on sand fill)
// ---------------------------------------------------------------------------

function GrowthChart({ points }: { points: GrowthPoint[] }) {
  // API returns the last 30 days DESC → plot ASC.
  const asc = [...points].sort((a, b) => a.day.localeCompare(b.day))
  const W = 640
  const H = 200
  const PAD_X = 8
  const PAD_TOP = 26
  const PAD_BOTTOM = 26
  const innerW = W - PAD_X * 2
  const innerH = H - PAD_TOP - PAD_BOTTOM
  const baseline = H - PAD_BOTTOM

  const max = Math.max(...asc.map((p) => p.n), 1)
  const min = Math.min(...asc.map((p) => p.n))
  const x = (i: number) =>
    PAD_X + (asc.length > 1 ? (i * innerW) / (asc.length - 1) : innerW / 2)
  const y = (n: number) => PAD_TOP + (1 - n / max) * innerH

  const line = asc
    .map((p, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(1)},${y(p.n).toFixed(1)}`)
    .join(' ')
  const area = `${line} L${x(asc.length - 1).toFixed(1)},${baseline} L${x(0).toFixed(1)},${baseline} Z`

  const maxIdx = asc.findIndex((p) => p.n === max)
  const minIdx = asc.findIndex((p) => p.n === min)
  const clampX = (v: number) => Math.min(W - 30, Math.max(30, v))

  return (
    <figure className="stats-growth-figure">
      <svg
        viewBox={`0 0 ${W} ${H}`}
        className="stats-growth-svg"
        role="img"
        aria-label={`Produits ajoutés par jour, du ${formatDay(asc[0].day)} au ${formatDay(asc[asc.length - 1].day)}. Maximum ${formatInt(max)}, minimum ${formatInt(min)}.`}
      >
        <line
          x1={PAD_X}
          y1={baseline}
          x2={W - PAD_X}
          y2={baseline}
          className="stats-growth-baseline"
        />
        <path d={area} className="stats-growth-area" />
        <path d={line} className="stats-growth-line" />

        {/* min/max direct labels only — no axis machinery */}
        <circle cx={x(maxIdx)} cy={y(max)} r={3.5} className="stats-growth-dot" />
        <text
          x={clampX(x(maxIdx))}
          y={y(max) - 9}
          textAnchor="middle"
          className="stats-growth-label"
        >
          {formatInt(max)}
        </text>
        {minIdx !== maxIdx && (
          <>
            <circle
              cx={x(minIdx)}
              cy={y(min)}
              r={3}
              className="stats-growth-dot stats-growth-dot-min"
            />
            <text
              x={clampX(x(minIdx))}
              y={Math.min(y(min) + 16, baseline - 4)}
              textAnchor="middle"
              className="stats-growth-label"
            >
              {formatInt(min)}
            </text>
          </>
        )}

        <text x={PAD_X} y={H - 8} className="stats-growth-axis">
          {formatDay(asc[0].day)}
        </text>
        <text x={W - PAD_X} y={H - 8} textAnchor="end" className="stats-growth-axis">
          {formatDay(asc[asc.length - 1].day)}
        </text>

        {/* hover layer: one generous hit target per point */}
        {asc.map((p, i) => (
          <circle key={p.day} cx={x(i)} cy={y(p.n)} r={9} fill="transparent">
            <title>{`${formatDay(p.day)} — ${formatInt(p.n)} produit${p.n > 1 ? 's' : ''}`}</title>
          </circle>
        ))}
      </svg>
    </figure>
  )
}

// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------

export default function Stats() {
  const [stats, setStats] = useState<ExtendedStats | null>(null)
  const [error, setError] = useState(false)

  useEffect(() => {
    const controller = new AbortController()
    fetchExtendedStats(controller.signal)
      .then(setStats)
      .catch((err: unknown) => {
        if (err instanceof DOMException && err.name === 'AbortError') return
        setError(true)
      })
    window.scrollTo({ top: 0 })
    return () => controller.abort()
  }, [])

  useEffect(() => {
    document.title = 'Statistiques — Fabri-Ka'
    return () => {
      document.title = DEFAULT_TITLE
    }
  }, [])

  const generatedOn = useMemo(
    () =>
      new Intl.DateTimeFormat('fr-CA', { dateStyle: 'long' }).format(new Date()),
    []
  )

  if (error) {
    return (
      <div className="page stats">
        <EmptyState
          variant="error"
          title="Statistiques indisponibles"
          message="Impossible de charger les statistiques pour le moment. Réessayez dans quelques instants."
        >
          <Link className="btn btn-secondary" to="/">
            Retour à l'accueil
          </Link>
        </EmptyState>
      </div>
    )
  }

  const totals = stats?.totals
  const bucketMax = stats
    ? Math.max(...stats.price_buckets.map((b) => b.n), 1)
    : 1
  const regionMax = stats
    ? Math.max(...stats.by_region.map((r) => r.products), 1)
    : 1
  // fixed A→E order (identity colors follow the entity, never its rank)
  const originRows = stats
    ? ORIGIN_KEYS.flatMap((key) => {
        const stat = stats.by_origin.find((o) => o.key === key)
        return stat && (stat.products > 0 || stat.stores > 0)
          ? [{ key, stat }]
          : []
      })
    : []
  const originTotal = originRows.reduce((sum, r) => sum + r.stat.products, 0)
  const catMax = stats
    ? Math.max(...stats.by_category.map((c) => c.products), 1)
    : 1

  const availabilityRows = stats
    ? [...stats.availability]
        .filter((a) => AVAILABILITY_META[a.key])
        .sort(
          (a, b) => AVAILABILITY_META[a.key].order - AVAILABILITY_META[b.key].order
        )
    : []
  const availabilityTotal = availabilityRows.reduce((sum, a) => sum + a.n, 0)

  const coverageMeters =
    stats && totals
      ? [
          {
            label: 'Produits avec image',
            value: stats.coverage.with_image,
            total: totals.products,
          },
          {
            label: 'Produits avec description',
            value: stats.coverage.with_desc,
            total: totals.products,
          },
          {
            label: 'Boutiques avec logo',
            value: stats.coverage.with_logo,
            total: totals.stores_registry,
          },
          {
            label: 'Boutiques géolocalisées',
            value: stats.coverage.with_region,
            total: totals.stores_registry,
          },
        ].map((m) => ({ ...m, pct: m.total ? m.value / m.total : 0 }))
      : []

  return (
    <div className="page stats">
      {/* 1 — editorial header */}
      <section className="stats-hero">
        <p className="hero-eyebrow">Statistiques</p>
        <h1 className="stats-hero-title">
          Le Québec qui vend en ligne, <em>en chiffres.</em>
        </h1>
        <p className="stats-hero-sub">
          Portrait généré à partir des catalogues publics agrégés par Fabri-Ka —
          données au {generatedOn}, recalculées en continu. Chaque chiffre est
          vivant : il se met à jour à mesure que les boutiques se synchronisent.
          Pour le détail complet, téléchargez le rapport de marché.
        </p>
        <div className="stats-hero-actions">
          <a
            className="btn btn-primary stats-report-btn"
            href={REPORT_URL}
            download
          >
            <IconDownload size={18} />
            Télécharger le rapport PDF
          </a>
          <span className="stats-report-hint">{REPORT_HINT}</span>
        </div>
      </section>

      {/* 2 — KPI tiles */}
      <section className="stats-kpis" aria-label="Chiffres clés">
        {totals ? (
          <>
            <div className="stats-kpi">
              <span className="stats-kpi-value">
                <CountUp value={totals.products} />
              </span>
              <span className="stats-kpi-label">Produits</span>
              <span className="stats-kpi-sub">
                {formatInt(totals.products_priced)} avec prix affiché
              </span>
            </div>
            <div className="stats-kpi">
              <span className="stats-kpi-value">
                <CountUp value={totals.stores_live} />
              </span>
              <span className="stats-kpi-label">Boutiques actives</span>
              <span className="stats-kpi-sub">
                {formatShare(totals.stores_live, totals.stores_registry) ||
                  '—'}{' '}
                du registre
              </span>
            </div>
            <div className="stats-kpi">
              <span className="stats-kpi-value">
                <CountUp value={totals.stores_registry} />
              </span>
              <span className="stats-kpi-label">Boutiques au registre</span>
              <span className="stats-kpi-sub">boutiques suivies</span>
            </div>
            <div className="stats-kpi">
              <span className="stats-kpi-value">
                <CountUp value={totals.regions} />
              </span>
              <span className="stats-kpi-label">Régions</span>
              <span className="stats-kpi-sub">du Québec couvertes</span>
            </div>
            <div className="stats-kpi">
              <span className="stats-kpi-value">
                {formatPrice(totals.price_median) || '—'}
              </span>
              <span className="stats-kpi-label">Prix médian</span>
              <span className="stats-kpi-sub">
                sur {formatInt(totals.products_priced)} produits
              </span>
            </div>
            <div className="stats-kpi">
              <span className="stats-kpi-value">
                {formatPrice(totals.price_avg) || '—'}
              </span>
              <span className="stats-kpi-label">Prix moyen</span>
              <span className="stats-kpi-sub">panier type</span>
            </div>
          </>
        ) : (
          Array.from({ length: 6 }, (_, i) => (
            <div className="stats-kpi" key={i}>
              <Skeleton width="80px" height="2rem" />
              <Skeleton width="110px" height="0.8rem" />
              <Skeleton width="90px" height="0.7rem" />
            </div>
          ))
        )}
      </section>

      {!stats ? (
        <div className="stats-loading" aria-hidden="true">
          <Skeleton height="220px" radius="12px" />
          <Skeleton height="320px" radius="12px" />
          <Skeleton height="220px" radius="12px" />
        </div>
      ) : (
        <>
          {/* 3 — nouveautés du marché */}
          {stats.newest.length > 0 && (
            <section className="stats-section" aria-label="Nouveautés du marché">
              <header className="section-header">
                <h2>Nouveautés du marché</h2>
                <Link className="section-see-all" to="/produits?sort=recent">
                  Voir les récents
                </Link>
              </header>
              <div className="stats-newest-rail">
                {stats.newest.map((p) => (
                  <Link
                    key={p.uid}
                    className="card stats-newest-card"
                    to={`/produits/${encodeURIComponent(p.uid)}`}
                  >
                    <span className="stats-newest-chip">
                      {p.category_label || 'Divers'}
                    </span>
                    <span className="stats-newest-title">{p.title}</span>
                    <span className="stats-newest-foot">
                      <span className="stats-newest-price">
                        {formatPrice(p.price) || 'Prix n.d.'}
                      </span>
                      <span className="stats-newest-store">{p.store_name}</span>
                    </span>
                  </Link>
                ))}
              </div>
            </section>
          )}

          {/* 4 — price histogram */}
          {stats.price_buckets.length > 0 && totals && (
            <section className="stats-section" aria-label="Répartition des prix">
              <header className="section-header">
                <h2>Répartition des prix</h2>
              </header>
              <p className="stats-section-note">
                {formatInt(totals.products_priced)} produits avec prix affiché.
              </p>
              <div className="stats-bars">
                {stats.price_buckets.map((b) => (
                  <div className="stats-bar-row" key={b.bucket}>
                    <span className="stats-bar-name">
                      {BUCKET_LABELS[b.bucket] ?? b.bucket}
                    </span>
                    <span className="stats-bar-track">
                      <span
                        className="stats-bar-fill stats-bar-fill-terracotta"
                        style={{ width: `${(b.n / bucketMax) * 100}%` }}
                      />
                    </span>
                    <span className="stats-bar-value">
                      {formatInt(b.n)}
                      <em>{formatShare(b.n, totals.products_priced)}</em>
                    </span>
                  </div>
                ))}
              </div>
              <p className="stats-hist-caption">
                Prix médian{' '}
                <strong>{formatPrice(totals.price_median) || '—'}</strong> · prix
                moyen <strong>{formatPrice(totals.price_avg) || '—'}</strong>
              </p>
            </section>
          )}

          {/* 4 — categories */}
          {stats.by_category.length > 0 && (
            <section className="stats-section" aria-label="Catégories">
              <header className="section-header">
                <h2>Par catégorie</h2>
                <Link className="section-see-all" to="/produits">
                  Tout le catalogue
                </Link>
              </header>

              {/* desktop table */}
              <div className="stats-cat-table-wrap">
                <table className="stats-cat-table">
                  <thead>
                    <tr>
                      <th>Catégorie</th>
                      <th className="num">Produits ↓</th>
                      <th className="num">Boutiques</th>
                      <th className="num">Prix médian</th>
                      <th className="num">Prix moyen</th>
                      <th className="num">Fourchette</th>
                    </tr>
                  </thead>
                  <tbody>
                    {stats.by_category.map((c) => (
                      <tr key={c.key}>
                        <td>
                          <Link
                            className="stats-cat-link"
                            to={`/produits?category=${encodeURIComponent(c.key)}`}
                          >
                            {c.label}
                          </Link>
                        </td>
                        <td className="num stats-cat-prod">
                          <span className="stats-cat-prod-inner">
                            <span
                              className="stats-cat-prod-bar"
                              aria-hidden="true"
                            >
                              <span
                                className="stats-cat-prod-fill"
                                style={{
                                  width: `${(c.products / catMax) * 100}%`,
                                }}
                              />
                            </span>
                            <span className="stats-cat-prod-n">
                              {formatInt(c.products)}
                            </span>
                          </span>
                        </td>
                        <td className="num">{formatInt(c.stores)}</td>
                        <td className="num">{formatPrice(c.price_median) || '—'}</td>
                        <td className="num">{formatPrice(c.price_avg) || '—'}</td>
                        <td className="num stats-cat-range">
                          {c.price_min !== null && c.price_max !== null
                            ? `${formatPriceCompact(c.price_min)} – ${formatPriceCompact(c.price_max)}`
                            : '—'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* mobile stacked cards */}
              <div className="stats-cat-cards">
                {stats.by_category.map((c) => (
                  <Link
                    key={c.key}
                    className="card stats-cat-card"
                    to={`/produits?category=${encodeURIComponent(c.key)}`}
                  >
                    <div className="stats-cat-card-head">
                      <strong>{c.label}</strong>
                      <span className="stats-cat-card-count">
                        {formatInt(c.products)} produits
                      </span>
                    </div>
                    <dl className="stats-cat-card-grid">
                      <div>
                        <dt>Boutiques</dt>
                        <dd>{formatInt(c.stores)}</dd>
                      </div>
                      <div>
                        <dt>Prix médian</dt>
                        <dd>{formatPrice(c.price_median) || '—'}</dd>
                      </div>
                      <div>
                        <dt>Prix moyen</dt>
                        <dd>{formatPrice(c.price_avg) || '—'}</dd>
                      </div>
                      <div>
                        <dt>Fourchette</dt>
                        <dd>
                          {c.price_min !== null && c.price_max !== null
                            ? `${formatPriceCompact(c.price_min)} – ${formatPriceCompact(c.price_max)}`
                            : '—'}
                        </dd>
                      </div>
                    </dl>
                  </Link>
                ))}
              </div>
            </section>
          )}

          {/* 5 — regions */}
          {stats.by_region.length > 0 && (
            <section className="stats-section" aria-label="Régions">
              <header className="section-header">
                <h2>Par région</h2>
              </header>
              <div className="stats-regions">
                {stats.by_region.map((r) => (
                  <div className="stats-region-row" key={r.key}>
                    <div className="stats-region-head">
                      <Link
                        className="stats-region-name"
                        to={`/produits?region=${encodeURIComponent(r.key)}`}
                      >
                        {r.key}
                      </Link>
                      <span className="stats-region-meta">
                        {formatInt(r.stores)} boutique{r.stores > 1 ? 's' : ''}
                        {r.price_avg !== null &&
                          ` · prix moyen ${formatPriceCompact(r.price_avg)}`}
                      </span>
                    </div>
                    <div className="stats-bar-row stats-bar-row-flat">
                      <span className="stats-bar-track">
                        <span
                          className="stats-bar-fill stats-bar-fill-pine"
                          style={{ width: `${(r.products / regionMax) * 100}%` }}
                        />
                      </span>
                      <span className="stats-bar-value">{formatInt(r.products)}</span>
                    </div>
                  </div>
                ))}
              </div>
            </section>
          )}

          {/* 6 — growth */}
          {stats.growth.length > 1 && (
            <section className="stats-section" aria-label="Croissance">
              <header className="section-header">
                <h2>Produits ajoutés par jour (30 jours)</h2>
              </header>
              <GrowthChart points={stats.growth} />
            </section>
          )}

          {/* 7 — origin distribution */}
          {originRows.length > 0 && originTotal > 0 && (
            <section className="stats-section" aria-label="Origine">
              <header className="section-header">
                <h2>Par origine</h2>
              </header>
              <div
                className="stats-origin-bar"
                role="img"
                aria-label={originRows
                  .map(
                    (r) =>
                      `${ORIGIN_LABELS[r.key]} : ${formatInt(r.stat.products)} produits`
                  )
                  .join(' · ')}
              >
                {originRows
                  .filter((r) => r.stat.products > 0)
                  .map((r) => {
                    const pct = (r.stat.products / originTotal) * 100
                    return (
                      <span
                        key={r.key}
                        className={`stats-origin-seg origin-${r.key}`}
                        style={{ width: `${pct}%` }}
                        title={`${ORIGIN_LABELS[r.key]} — ${formatInt(r.stat.products)} produits (${formatShare(r.stat.products, originTotal)})`}
                      >
                        {pct >= 6 && (
                          <span className="stats-origin-seg-letter">{r.key}</span>
                        )}
                      </span>
                    )
                  })}
              </div>
              <ul className="stats-origin-legend">
                {originRows.map((r) => (
                  <li key={r.key}>
                    <OriginBadge origin={r.key} withLabel />
                    <span className="stats-origin-legend-counts">
                      {formatInt(r.stat.stores)} boutique
                      {r.stat.stores > 1 ? 's' : ''} ·{' '}
                      {formatInt(r.stat.products)} produits
                      {originTotal > 0 &&
                        r.stat.products > 0 &&
                        ` (${formatShare(r.stat.products, originTotal)})`}
                    </span>
                  </li>
                ))}
              </ul>
            </section>
          )}

          {/* 8 — platforms */}
          {stats.by_platform.length > 0 && (
            <section className="stats-section" aria-label="Plateformes">
              <header className="section-header">
                <h2>Plateformes</h2>
              </header>
              <div className="stats-platforms">
                {stats.by_platform.map((p) => (
                  <span className="stats-platform-chip" key={p.key}>
                    <strong>{p.key}</strong> × {formatInt(p.stores)} boutique
                    {p.stores > 1 ? 's' : ''} ({formatInt(p.products)} produits)
                  </span>
                ))}
              </div>
            </section>
          )}

          {/* disponibilité */}
          {availabilityRows.length > 0 && availabilityTotal > 0 && (
            <section className="stats-section" aria-label="Disponibilité">
              <header className="section-header">
                <h2>Disponibilité</h2>
              </header>
              <div
                className="stats-avail-bar"
                role="img"
                aria-label={availabilityRows
                  .map(
                    (a) =>
                      `${AVAILABILITY_META[a.key].label} : ${formatInt(a.n)} produits`
                  )
                  .join(' · ')}
              >
                {availabilityRows
                  .filter((a) => a.n > 0)
                  .map((a) => (
                    <span
                      key={a.key}
                      className={`stats-avail-seg stats-avail-${AVAILABILITY_META[a.key].slug}`}
                      style={{ width: `${(a.n / availabilityTotal) * 100}%` }}
                      title={`${AVAILABILITY_META[a.key].label} — ${formatInt(a.n)} (${formatShare(a.n, availabilityTotal)})`}
                    />
                  ))}
              </div>
              <ul className="stats-avail-legend">
                {availabilityRows.map((a) => (
                  <li key={a.key}>
                    <span
                      className={`stats-avail-dot stats-avail-${AVAILABILITY_META[a.key].slug}`}
                      aria-hidden="true"
                    />
                    <span>
                      {AVAILABILITY_META[a.key].label}{' '}
                      <strong>{formatInt(a.n)}</strong>{' '}
                      <em>{formatShare(a.n, availabilityTotal)}</em>
                    </span>
                  </li>
                ))}
              </ul>
            </section>
          )}

          {/* complétude des données */}
          {coverageMeters.length > 0 && (
            <section
              className="stats-section"
              aria-label="Complétude des données"
            >
              <header className="section-header">
                <h2>Complétude des données</h2>
              </header>
              <div className="stats-coverage">
                {coverageMeters.map((m) => (
                  <div className="stats-meter" key={m.label}>
                    <div className="stats-meter-head">
                      <span className="stats-meter-label">{m.label}</span>
                      <span className="stats-meter-pct">
                        {percentFormatter.format(m.pct)}
                      </span>
                    </div>
                    <span className="stats-meter-track">
                      <span
                        className="stats-meter-fill"
                        style={{ width: `${m.pct * 100}%` }}
                      />
                    </span>
                    <span className="stats-meter-sub">
                      {formatInt(m.value)} / {formatInt(m.total)}
                    </span>
                  </div>
                ))}
              </div>
            </section>
          )}

          <div className="stats-columns">
            {/* 9 — top stores */}
            {stats.top_stores.length > 0 && (
              <section className="stats-section" aria-label="Top boutiques">
                <header className="section-header">
                  <h2>Top boutiques</h2>
                  <Link className="section-see-all" to="/boutiques">
                    Toutes les boutiques
                  </Link>
                </header>
                <ol className="stats-top-stores">
                  {stats.top_stores.map((s, i) => (
                    <li key={s.id}>
                      <span className="stats-rank">{i + 1}</span>
                      <StoreLogo
                        storeId={s.id}
                        name={s.name}
                        logoUrl={s.logo_url}
                        size="sm"
                      />
                      <span className="stats-top-store-id">
                        <Link to={`/boutiques/${encodeURIComponent(s.id)}`}>
                          {s.name}
                        </Link>
                        {s.region && (
                          <span className="stats-top-store-region">{s.region}</span>
                        )}
                      </span>
                      <span className="stats-top-store-count">
                        {formatInt(s.products)}
                      </span>
                    </li>
                  ))}
                </ol>
              </section>
            )}

            {/* 10 — most expensive */}
            {stats.most_expensive.length > 0 && (
              <section className="stats-section" aria-label="Produits les plus chers">
                <header className="section-header">
                  <h2>Les plus chers</h2>
                </header>
                <p className="stats-section-note">
                  Le grand luxe made in Québec — véridique, promis.
                </p>
                <ol className="stats-expensive">
                  {stats.most_expensive.map((p) => (
                    <li key={p.uid}>
                      <Link
                        className="stats-expensive-link"
                        to={`/produits/${encodeURIComponent(p.uid)}`}
                      >
                        <span className="stats-expensive-title">{p.title}</span>
                        <span className="stats-expensive-store">{p.store_name}</span>
                      </Link>
                      <span className="stats-expensive-price">
                        {formatPrice(p.price)}
                      </span>
                    </li>
                  ))}
                </ol>
              </section>
            )}
          </div>
        </>
      )}

      {/* report download — footer */}
      <section className="stats-report-footer" aria-label="Rapport de marché">
        <a
          className="btn btn-secondary stats-report-btn"
          href={REPORT_URL}
          download
        >
          <IconDownload size={18} />
          Télécharger le rapport PDF
        </a>
        <span className="stats-report-hint">{REPORT_HINT}</span>
      </section>
    </div>
  )
}
