// app.jsx — composition racine + machine d'état
// Données réelles : matchs et zones chargés depuis l'API backend.

const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "showPrices": true,
  "palette": ["#0B2545", "#FFD400", "#F6F4EF"],
  "density": "regular"
}/*EDITMODE-END*/;

const { UtilityRibbon, SiteHeader, Breadcrumb, HomeHero, ChantStrip, Filters,
        MatchCard, AtmosphereBand, SidebarPromo, SponsorStrip, SiteFooter } = window.HomeUI;

// ── Vue Home ───────────────────────────────────────────────────────
function HomeView({ matches, matchesLoading, onBuy, cartCount }) {
  const [filter, setFilter] = useState("all");

  const filtered = useMemo(() => (matches || []).filter(m => {
    if (filter === "all")  return true;
    if (filter === "open") return m.status === "open" || m.status === "limited";
    return true;
  }), [filter, matches]);

  const featured = filtered.find(m => m.featured) || filtered[0];
  const others   = filtered.filter(m => m !== featured);

  return (
    <React.Fragment>
      <UtilityRibbon />
      <SiteHeader active="home" cartCount={cartCount} onNav={() => {}} />
      <Breadcrumb items={[{ label: "Accueil" }, { label: "Matchs à Bonal" }]} />
      <HomeHero next={featured} onBuy={onBuy} />
      <Filters filter={filter} setFilter={setFilter} count={filtered.length} matches={matches} />

      <div className="home-main">
        <section className="matches-section">
          {matchesLoading ? (
            <div className="matches-loading">
              <div className="loading-pulse">Chargement des matchs…</div>
            </div>
          ) : (
            <div className="match-grid">
              {featured && <MatchCard m={featured} featured onBuy={onBuy} />}
              {others.map(m => <MatchCard key={m.id} m={m} onBuy={onBuy} />)}
              {!matchesLoading && filtered.length === 0 && (
                <div className="matches-empty">Aucun match à afficher.</div>
              )}
            </div>
          )}
        </section>
        <SidebarPromo onAbo={() => {}} />
      </div>

      <AtmosphereBand />
      <SponsorStrip />
      <SiteFooter />
    </React.Fragment>
  );
}

// ── Vue Stade ──────────────────────────────────────────────────────
function StadiumView({ match, cartCount, onBack, t, setTweak, onCheckout }) {
  const [zones, setZones]           = useState([]);
  const [zonesLoading, setZonesLoading] = useState(true);
  const [zonesError, setZonesError] = useState(null);
  const [selectedId, setSelectedId] = useState(null);
  const [hoveredId, setHoveredId]   = useState(null);
  const [quantities, setQuantities] = useState({});
  const [toast, setToast]           = useState(null);

  useEffect(() => {
    setZones([]);
    setZonesLoading(true);
    setZonesError(null);
    setSelectedId(null);
    setQuantities({});

    API.zones(match.id)
      .then(raw => setZones(raw.map(API.adaptZone)))
      .catch(err => setZonesError(err.message || "Impossible de charger les tribunes."))
      .finally(() => setZonesLoading(false));
  }, [match.id]);

  const selectedZone = useMemo(
    () => selectedId ? zones.find(z => z.id === selectedId) : null,
    [selectedId, zones]
  );

  const select = (id) => { setSelectedId(id); setQuantities({}); };

  const triggerCheckout = () => {
    const totalQty = Object.values(quantities).reduce((s, q) => s + q, 0);
    if (!totalQty || !selectedZone) return;
    onCheckout(match, selectedZone, quantities);
  };

  const addToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 3000);
  };

  return (
    <React.Fragment>
      <UtilityRibbon />
      <SiteHeader active="home" cartCount={cartCount} onNav={onBack} />
      <Breadcrumb items={[
        { label: "Accueil", onClick: onBack, href: "#" },
        { label: "Matchs à domicile", onClick: onBack, href: "#" },
        { label: `FCSM · ${match.awayLong || match.away}` },
      ]} />

      <section className="match-band">
        <div className="match-inner">
          <div className="match-meta">
            <div className="badges">
              <span className="tag tag-yellow">{match.competition || "NATIONAL 1"}</span>
              <span className="tag tag-line tag-pulse">{match.statusLabel}</span>
              <span className="tag tag-line">À domicile</span>
            </div>
            <div className="eyebrow eyebrow-on-navy" style={{marginTop:4}}>Saison 25/26</div>
            <div style={{
              fontFamily:'"Anton", sans-serif', fontSize:28, letterSpacing:".03em",
              textTransform:"uppercase", lineHeight:1, marginTop:6,
            }}>Choisissez votre tribune.</div>
          </div>

          <div className="match-versus">
            <div className="match-team">
              <div className="crest crest-home"><span className="crest-letter">FC</span></div>
              <div className="match-team-name">Sochaux</div>
              <div className="match-team-sub">Domicile</div>
            </div>
            <div className="versus">VS</div>
            <div className="match-team">
              <div className="crest crest-away">
                <span className="crest-letter">
                  {(match.away || "").split(" ").map(w => w[0]).slice(0, 2).join("")}
                </span>
              </div>
              <div className="match-team-name">{match.awayLong || match.away}</div>
              <div className="match-team-sub">Extérieur</div>
            </div>
          </div>

          <div className="match-when">
            <div className="match-when-day">{match.date.day}</div>
            <div className="match-when-date">{match.date.num} {match.date.month} · {match.date.time}</div>
            <div className="match-when-place">
              <strong>{match.venue}</strong><br/>
              Montbéliard · Tribunes ouvertes {match.doorsOpen || "18:30"}
            </div>
          </div>
        </div>
      </section>

      <PageHead step={selectedZone ? 2 : 1} />

      <main className="main">
        <section className="map-card">
          <div className="map-toolbar">
            <div className="map-toolbar-left">
              <div className="map-title">Plan du stade</div>
              <small>Stade Auguste-Bonal · Capacité 20 005</small>
            </div>
            <div className="zoom-toggle">
              <button className={t.showPrices ? "on" : ""}
                onClick={() => setTweak("showPrices", true)}>Tarifs</button>
              <button className={!t.showPrices ? "on" : ""}
                onClick={() => setTweak("showPrices", false)}>Vue épurée</button>
            </div>
          </div>

          {zonesLoading ? (
            <div className="map-loading">
              <div className="loading-pulse">Chargement du plan…</div>
            </div>
          ) : zonesError ? (
            <div className="map-error">{zonesError}</div>
          ) : (
            <Stadium
              zones={zones} selected={selectedId} hovered={hoveredId}
              onSelect={select} onHover={setHoveredId}
              showPrices={t.showPrices}
            />
          )}

          <div className="legend">
            <span className="legend-title">Disponibilité</span>
            <div className="legend-item"><span className="legend-swatch open" /><span>Disponible</span></div>
            <div className="legend-item"><span className="legend-swatch limited" /><span>Dernières places</span></div>
            <div className="legend-item"><span className="legend-swatch sold" /><span>Complet</span></div>
            <span style={{flex:1}} />
            {!zonesLoading && <span className="eyebrow">Données en temps réel</span>}
          </div>
        </section>

        <aside className="panel">
          {selectedZone ? (
            <ZoneDetail zone={selectedZone} quantities={quantities}
              setQuantities={setQuantities}
              onReserve={triggerCheckout}
              onBack={() => { setSelectedId(null); setQuantities({}); }} />
          ) : (
            <ZoneList zones={zones} hovered={hoveredId}
              loading={zonesLoading}
              onSelect={select} onHover={setHoveredId} />
          )}
        </aside>
      </main>

      <SponsorStrip />
      <SiteFooter />

      {toast && (
        <div className="toast">
          <b><Icon name="check" size={12} /></b>
          {toast}
        </div>
      )}
    </React.Fragment>
  );
}

// ── App racine ─────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView]               = useState({ name: "home" });
  const [matches, setMatches]         = useState([]);
  const [matchesLoading, setMatchesLoading] = useState(true);
  const [checkout, setCheckout]       = useState(null); // null | { match, zone, quantities }

  // Appliquer la palette CSS
  useEffect(() => {
    const [navy, yellow, cream] = t.palette;
    const root = document.documentElement;
    root.style.setProperty("--navy",   navy);
    root.style.setProperty("--yellow", yellow);
    root.style.setProperty("--cream",  cream);
  }, [t.palette]);

  // Charger les matchs depuis l'API
  useEffect(() => {
    API.matches("all")
      .then(raw => setMatches(raw.map((m, i) => API.adaptMatch(m, i))))
      .catch(err => console.error("Erreur chargement matchs:", err))
      .finally(() => setMatchesLoading(false));
  }, []);

  const goBuy = (m) => {
    if (!m || m.status === "sold" || m.status === "upcoming" || m.status === "past") return;
    setView({ name: "stadium", match: m });
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const goHome = () => {
    setView({ name: "home" });
    setCheckout(null);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const openCheckout = (match, zone, quantities) => {
    setCheckout({ match, zone, quantities });
  };

  const closeCheckout = () => setCheckout(null);

  return (
    <div className="app">
      {view.name === "home" ? (
        <HomeView
          matches={matches}
          matchesLoading={matchesLoading}
          cartCount={0}
          onBuy={goBuy}
        />
      ) : (
        <StadiumView
          match={view.match}
          cartCount={0}
          onBack={goHome}
          onCheckout={openCheckout}
          t={t} setTweak={setTweak}
        />
      )}

      {/* Overlay de paiement */}
      {checkout && (
        <CheckoutOverlay
          match={checkout.match}
          zone={checkout.zone}
          quantities={checkout.quantities}
          onClose={closeCheckout}
        />
      )}

      <TweaksPanel>
        <TweakSection label="Plan du stade" />
        <TweakToggle label="Afficher les tarifs sur le plan"
          value={t.showPrices} onChange={(v) => setTweak("showPrices", v)} />
        <TweakRadio label="Densité"
          value={t.density} options={["compact", "regular", "comfy"]}
          onChange={(v) => setTweak("density", v)} />
        <TweakSection label="Palette" />
        <TweakColor label="Couleurs"
          value={t.palette}
          options={[
            ["#0B2545", "#FFD400", "#F6F4EF"],
            ["#0F0F0F", "#FFC400", "#F6F4EF"],
            ["#13335C", "#E8B800", "#F6F4EF"],
            ["#FFD400", "#0B2545", "#F6F4EF"],
          ]}
          onChange={(v) => setTweak("palette", v)} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
