// -----------------------------------------------------------------------------
// Author: Simon-Pierre Boucher
// Contact: contact@spboucher.ai
// Project: Toit-Ka
// App.tsx : layout global (header + ticker en direct + footer encre) et routage.
//   L'ACCENT DU SITE SUIT L'UNIVERS AFFICHÉ (html[data-mode]) : lime en mode
//   Louer, rouge en mode Acheter, terracotta (marque) sur les pages neutres.
// -----------------------------------------------------------------------------
import { useEffect, useState } from "react";
import { Link, NavLink, Route, Routes, useLocation } from "react-router-dom";
import { fetchStats, logout, setMode } from "./api";
import { AccountProvider, useAccount } from "./account";
import { Ico, IcoHeart } from "./components/Icons";
import CategoryPage from "./pages/Category";
import Home from "./pages/Home";
import { PrivacyPage, TermsPage } from "./pages/Legal";
import ListingPage from "./pages/Listing";
import ProfilPage from "./pages/Profil";
import StatsPage from "./pages/Stats";

/** L'accent global suit la route : /louer/* -> lime, /acheter/* -> rouge,
 *  accueil -> géré par Home (selon le toggle), ailleurs -> marque terracotta. */
function ModeSync() {
  const location = useLocation();
  useEffect(() => {
    const p = location.pathname;
    if (p.startsWith("/louer")) setMode("louer");
    else if (p.startsWith("/acheter")) setMode("acheter");
    else if (p === "/" || p.startsWith("/annonce/")) { /* géré par la page */ }
    else setMode(null);
  }, [location]);
  return null;
}

function Ticker() {
  const [items, setItems] = useState<string[]>([]);

  useEffect(() => {
    fetchStats()
      .then((stats) => {
        const parts: string[] = [
          `${stats.louer.total.toLocaleString("fr-CA")} logements à louer`,
          `${stats.acheter.total.toLocaleString("fr-CA")} propriétés à vendre`,
        ];
        if (stats.louer.avg_price != null)
          parts.push(`Loyer moyen ${Math.round(stats.louer.avg_price).toLocaleString("fr-CA")} $`);
        if (stats.acheter.avg_price != null)
          parts.push(`Prix moyen ${Math.round(stats.acheter.avg_price).toLocaleString("fr-CA")} $`);
        for (const c of stats.louer.top_cities.slice(0, 5))
          parts.push(`Louer à ${c.city} · ${c.n}`);
        for (const c of stats.acheter.top_cities.slice(0, 5))
          parts.push(`Acheter à ${c.city} · ${c.n}`);
        parts.push("Mise à jour automatique");
        setItems(parts);
      })
      .catch(() => setItems(["Toit-Ka — louer ou acheter un toit au Québec"]));
  }, []);

  if (items.length === 0) return null;
  return (
    <div className="ticker" aria-hidden="true">
      <div className="ticker-track">
        {[...items, ...items].map((t, i) => (
          <span key={i}>{t}</span>
        ))}
      </div>
    </div>
  );
}

function AuthWidget() {
  const { user, enabled, refresh } = useAccount();
  const [open, setOpen] = useState(false);

  if (!user && !enabled) return null;
  if (!user)
    return (
      <a className="auth-btn" href={`/api/auth/ka/login?next=${encodeURIComponent(location.pathname)}`}>
        <span className="auth-kab" aria-hidden="true">KA</span>
        KA ID
      </a>
    );
  return (
    <div className="auth-user">
      <button className="auth-avatar" onClick={() => setOpen(!open)}
              aria-label={`Compte de ${user.name}`} aria-expanded={open}>
        {user.picture
          ? <img src={user.picture} alt="" referrerPolicy="no-referrer" />
          : <span>{(user.name || user.email || "?").slice(0, 1).toUpperCase()}</span>}
      </button>
      {open && (
        <div className="auth-menu" role="menu">
          <div className="auth-id">
            <b>{user.name}</b>
            <span>{user.email}</span>
          </div>
          {user.ka_id && (
            <div className="auth-note" style={{ fontFamily: "monospace", letterSpacing: "0.08em" }}>
              KA-ID : {user.ka_id}
            </div>
          )}
          <div className="auth-note">Compte Groupe KA — le même KA-ID sur toutes les plateformes du groupe</div>
          <Link className="auth-menu-link" to="/profil" onClick={() => setOpen(false)}>
            Mon profil
          </Link>
          <a className="auth-menu-link" href="https://www.groupe-ka.com/compte"
             target="_blank" rel="noopener noreferrer" onClick={() => setOpen(false)}>
            <IcoHeart size={13} filled /> Mes favoris — Mon univers Ka ↗
          </a>
          <button onClick={() => logout().then(() => { refresh(); setOpen(false); })}>
            Se déconnecter
          </button>
        </div>
      )}
    </div>
  );
}

const NAV_LINKS = [
  { to: "/?tx=louer", label: "Louer", icon: "key", dot: "louer" },
  { to: "/?tx=acheter", label: "Acheter", icon: "home", dot: "acheter" },
  { to: "/stats", label: "Stats", icon: "chart", dot: "" },
  { to: "/profil", label: "Mon profil", icon: "people", dot: "" },
];

function Header() {
  const [open, setOpen] = useState(false);
  const location = useLocation();
  const tx = new URLSearchParams(location.search).get("tx") ?? "louer";

  useEffect(() => { setOpen(false); }, [location]);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const navActive = (label: string) => {
    if (label === "Louer") return location.pathname === "/" && tx === "louer";
    if (label === "Acheter") return location.pathname === "/" && tx === "acheter";
    return false;
  };

  return (
    <>
      <header className="header">
        <div className="container header-inner">
          <NavLink to="/" className="brand" aria-label="Toit-Ka — accueil">
            Toit<span className="ka">Ka</span>
            <span className="brand-tag">Louer ou acheter — un seul endroit</span>
          </NavLink>
          <nav className="nav" aria-label="Navigation principale">
            <NavLink to="/?tx=louer" className={navActive("Louer") ? "active" : ""}>
              <span className="nav-dot louer" aria-hidden="true" /> Louer
            </NavLink>
            <NavLink to="/?tx=acheter" className={navActive("Acheter") ? "active" : ""}>
              <span className="nav-dot acheter" aria-hidden="true" /> Acheter
            </NavLink>
            <NavLink to="/stats" className={({ isActive }) => (isActive ? "active" : "")}>
              Stats
            </NavLink>
          </nav>
          <div className="auth-slot">
            <AuthWidget />
          </div>
          <button
            className={`menu-btn ${open ? "open" : ""}`}
            aria-expanded={open}
            aria-label={open ? "Fermer le menu" : "Ouvrir le menu"}
            onClick={() => setOpen(!open)}
          >
            <span /><span /><span />
          </button>
        </div>

        <div className={`mobile-menu ${open ? "open" : ""}`} role="navigation" aria-label="Menu mobile">
          {NAV_LINKS.map((l, i) => (
            <NavLink
              key={l.to}
              to={l.to}
              style={{ transitionDelay: open ? `${60 + i * 45}ms` : "0ms" }}
              className={`mm-link ${navActive(l.label) ? "active" : ""}`}
              onClick={() => setOpen(false)}
            >
              <span className="mm-ico" aria-hidden="true"><Ico name={l.icon} size={19} /></span>
              {l.label}
              <span className="mm-arrow" aria-hidden="true"><Ico name="arrow" size={15} /></span>
            </NavLink>
          ))}
          <div className="mm-foot">
            Agrégateur indépendant — location (Lou-Ka) et vente (Immo-Ka) réunies.
            Chaque fiche renvoie à l'annonce originale de la source.
          </div>
        </div>
      </header>
      {open && <div className="mm-backdrop" onClick={() => setOpen(false)} aria-hidden="true" />}
      <Ticker />
    </>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="fbrand">
          Toit<span className="ka">Ka</span>
        </div>
        <div className="frow">
          <div>
            <b>Agrégateur indépendant</b> des logements à louer et des propriétés à
            vendre dans la province de Québec — la fusion de <b>Lou-Ka</b> (location)
            et d'<b>Immo-Ka</b> (vente). Les annonces proviennent des sites publics des
            gestionnaires immobiliers, agences de courtage et plateformes, rafraîchies
            automatiquement — chaque fiche renvoie vers l'annonce originale.
          </div>
        </div>
        <div className="flegal">
          <NavLink to="/conditions">Conditions d'utilisation</NavLink>
          <span aria-hidden="true"> · </span>
          <NavLink to="/confidentialite">Politique de confidentialité</NavLink>
          <span aria-hidden="true"> · </span>
          <a href="https://www.lou-ka.com" target="_blank" rel="noopener noreferrer">Lou-Ka</a>
          <span aria-hidden="true"> · </span>
          <a href="https://www.immo-ka.com" target="_blank" rel="noopener noreferrer">Immo-Ka</a>
        </div>
        <div className="fmono">
          Toit-Ka est une application du <b>Groupe-Ka</b> ·
          © {new Date().getFullYear()} Groupe-Ka —{" "}
          <a href="mailto:contact@groupe-ka.com">contact@groupe-ka.com</a>
        </div>
      </div>
    </footer>
  );
}

export default function App() {
  return (
    <AccountProvider>
      <ModeSync />
      <Header />
      <main>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/annonce/:uid" element={<ListingPage />} />
          <Route path="/annonce/:uid/:slug" element={<ListingPage />} />
          {/* pages programmatiques SEO — mêmes URL que le rendu serveur */}
          <Route path="/louer/type/:type" element={<CategoryPage tx="louer" />} />
          <Route path="/louer/:ville" element={<CategoryPage tx="louer" />} />
          <Route path="/louer/:ville/:type" element={<CategoryPage tx="louer" />} />
          <Route path="/acheter/type/:type" element={<CategoryPage tx="acheter" />} />
          <Route path="/acheter/:ville" element={<CategoryPage tx="acheter" />} />
          <Route path="/acheter/:ville/:type" element={<CategoryPage tx="acheter" />} />
          <Route path="/stats" element={<StatsPage />} />
          <Route path="/profil" element={<ProfilPage />} />
          <Route path="/conditions" element={<TermsPage />} />
          <Route path="/confidentialite" element={<PrivacyPage />} />
          <Route
            path="*"
            element={
              <div className="notice container">
                <div className="big"><Ico name="alert" size={40} /></div>
                <h2>Page introuvable</h2>
                <p>Le lien demandé n'existe pas.</p>
              </div>
            }
          />
        </Routes>
      </main>
      <Footer />
    </AccountProvider>
  );
}
