/**
 * =============================================================================
 * QWHPI — Quebec Weekly Housing Price Index
 * Author  : Simon-Pierre Boucher
 * Contact : contact@spboucher.ai
 * File    : web/components/Ticker.tsx
 * Purpose : Bloomberg-style infinite ticker tape — regions & cities YoY.
 * =============================================================================
 */
"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { fetchOverview, type OverviewRow } from "../lib/api";

export default function Ticker({ ptype = "all" }: { ptype?: string }) {
  const [rows, setRows] = useState<OverviewRow[]>([]);

  useEffect(() => {
    Promise.all([
      fetchOverview("region", ptype),
      fetchOverview("municipality", ptype),
    ])
      .then(([r, m]) => setRows([...m.rows, ...r.rows]))
      .catch(() => setRows([]));
  }, [ptype]);

  if (!rows.length) return <div className="ticker-shell" aria-hidden />;

  const items = rows.map((r) => (
    <Link
      key={r.geography_id}
      className="ticker-item"
      href={`/explore?geography=${r.geography_id}&type=${ptype}`}
    >
      <span className="ticker-name">{r.geography_name}</span>
      <span className="ticker-val">{r.index.toFixed(1)}</span>
      <span className={r.yoy_pct != null && r.yoy_pct < 0 ? "delta down" : "delta up"}>
        {r.yoy_pct == null ? "—"
          : `${r.yoy_pct >= 0 ? "▲" : "▼"}${Math.abs(r.yoy_pct).toFixed(1)}%`}
      </span>
    </Link>
  ));

  return (
    <div className="ticker-shell" role="marquee"
         aria-label="Latest year-over-year appreciation by geography">
      <div className="ticker-track">
        <div className="ticker-group">{items}</div>
        <div className="ticker-group" aria-hidden>{items}</div>
      </div>
    </div>
  );
}
