/* Page — Marchés : indices + actualités, fiches valeurs, recherche, suivi et alertes.
   Navigation par hash (#article=…, #valeur=…, #cat=…) : partage d'URL et bouton retour fonctionnent.
   Données : site/marches-data.jsx (fictives — voir design_handoff_marches/README.md pour le branchement réel). */
const { Button, Card, Badge, Delta, Icon, AreaChart } = window.NabooDesignSystem_955dca;
const S = window.NabooSite;
const D = window.NabooMarchesData;
const { useState, useEffect, useMemo } = React;
const HOME = "Accueil.html";

const { INDICES, PALMARES, CATS, CAT_TONE, CAT_VISUAL, VALEURS, UNE, ACTUS, CONTINU, CONSULTEES, PEDAGO, BREVES, ALL_ARTICLES } = D;
const findValeur = (sym) => VALEURS.find((v) => v.sym === sym);
const findArticle = (slug) => ALL_ARTICLES.find((a) => a.slug === slug);

/* ---- Routage par hash ---- */
const parseHash = () => {
  const p = new URLSearchParams(window.location.hash.slice(1));
  return { cat: p.get("cat") || "Tout", article: p.get("article") || "", valeur: p.get("valeur") || "" };
};
const setHash = (r) => {
  const p = new URLSearchParams();
  if (r.cat && r.cat !== "Tout") p.set("cat", r.cat);
  if (r.article) p.set("article", r.article);
  if (r.valeur) p.set("valeur", r.valeur);
  const s = p.toString();
  window.location.hash = s ? s : "";
};

/* ---- Suivi de valeurs + alertes (localStorage, maquette) ---- */
const WL_KEY = "naboo:marches:suivies";
const AL_KEY = "naboo:marches:alertes";
const readJson = (k, fb) => { try { return JSON.parse(localStorage.getItem(k)) || fb; } catch (e) { return fb; } };
const getSuivies = () => readJson(WL_KEY, []);
const toggleSuivie = (sym) => { const l = getSuivies(); const n = l.includes(sym) ? l.filter((s) => s !== sym) : l.concat(sym); localStorage.setItem(WL_KEY, JSON.stringify(n)); return n; };
const getAlertes = () => readJson(AL_KEY, {});
const toggleAlerte = (sym) => { const a = getAlertes(); a[sym] = !a[sym]; localStorage.setItem(AL_KEY, JSON.stringify(a)); return Object.assign({}, a); };

const fmtPct = (d) => (d >= 0 ? "+" : "−") + Math.abs(d).toFixed(2).replace(".", ",") + " %";

/* ---------------- Composants ---------------- */
function Visual({ cat, big, style }) {
  const v = CAT_VISUAL[cat] || CAT_VISUAL["Indices"];
  return (
    <div className="mk-visual" style={{ background: v.bg, height: big ? 240 : undefined, borderRadius: big ? "var(--radius-lg, 18px)" : 12, ...style }} aria-hidden="true">
      <span className="mk-visual-ring" style={{ borderColor: v.color }}></span>
      <Icon name={v.icon} size={big ? 54 : 34} color={v.color} />
    </div>
  );
}

function TickerItem({ ix, onOpen }) {
  const pos = ix.d >= 0;
  return (
    <button type="button" className="mk-ticker-item mk-ticker-btn" onClick={() => onOpen(ix.sym)}>
      <span className="mk-ticker-nom">{ix.nom}</span>
      <span className="mk-ticker-val naboo-num">{ix.val}</span>
      <span className="naboo-num" style={{ fontWeight: 700, color: pos ? "#3ED598" : "#FF7A85" }}>{pos ? "▲" : "▼"} {fmtPct(ix.d)}</span>
    </button>
  );
}

function IndexCard({ ix, onOpen }) {
  const pos = ix.d >= 0;
  return (
    <Card padding={16} className="mk-actu-hover mk-clickable" style={{ minWidth: 0 }} onClick={() => onOpen(ix.sym)}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
        <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{ix.nom}</span>
        <Delta value={ix.d} />
      </div>
      <div className="naboo-num" style={{ fontFamily: "var(--font-display)", fontSize: 21, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)", fontVariantNumeric: "tabular-nums", margin: "4px 0 8px" }}>{ix.val}</div>
      <AreaChart data={ix.spark} height={36} color={pos ? "var(--positive)" : "var(--negative)"} fill strokeWidth={2} style={{ width: "100%" }} />
    </Card>
  );
}

function ValeurRow({ sym, nom, val, d, i, onOpen, compact }) {
  const pos = d >= 0;
  return (
    <div className="mk-valeur-row" style={{ borderTop: i ? "1px solid var(--border-subtle)" : "none" }} onClick={() => onOpen(sym)} role="button" tabIndex={0}>
      {!compact ? <span style={{ width: 34, height: 34, borderRadius: 10, flex: "none", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 800, background: pos ? "var(--positive-bg, #E4F6EE)" : "var(--negative-bg, #FDEBEC)", color: pos ? "var(--positive)" : "var(--negative)" }}>{sym.slice(0, 4)}</span> : null}
      <span style={{ flex: 1, fontSize: 13.5, fontWeight: 700, color: "var(--text-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{nom}</span>
      {val ? <span className="naboo-num" style={{ fontSize: 13.5, fontWeight: 700, color: "var(--text-body)", fontVariantNumeric: "tabular-nums" }}>{val}</span> : null}
      <span style={{ width: compact ? 66 : 74, flex: "none", textAlign: "right" }}><Delta value={d} /></span>
    </div>
  );
}

function ConsulteesCard({ onOpen }) {
  return (
    <Card padding={20} style={{ minWidth: 0 }}>
      <p className="mk-overline" style={{ marginBottom: 8 }}>Les plus consultées</p>
      {CONSULTEES.map((v, i) => <ValeurRow key={v.sym} {...v} i={i} onOpen={onOpen} compact />)}
      <p style={{ fontSize: 11.5, color: "var(--text-faint)", margin: "12px 0 0" }}>Cours différés 15 min · données Twelve Data et CoinGecko.</p>
    </Card>
  );
}

/* ---- Recherche ---- */
function SearchBox({ onValeur, onArticle, dark }) {
  const [q, setQ] = useState("");
  const norm = (t) => t.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  const res = useMemo(() => {
    if (q.trim().length < 2) return null;
    const n = norm(q);
    return {
      valeurs: VALEURS.filter((v) => norm(v.nom).includes(n) || norm(v.sym).includes(n)).slice(0, 4),
      articles: ALL_ARTICLES.filter((a) => norm(a.titre).includes(n) || norm(a.chapo).includes(n)).slice(0, 4),
    };
  }, [q]);
  const close = () => setQ("");
  return (
    <div className={"mk-search" + (dark ? " mk-search-dark" : "")}>
      <Icon name="search" size={16} color={dark ? "rgba(255,255,255,0.55)" : "var(--text-faint)"} style={{ flex: "none" }} />
      <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Rechercher une valeur ou une actu…" aria-label="Rechercher" />
      {q ? <button type="button" className="mk-search-x" onClick={close} aria-label="Effacer"><Icon name="x" size={14} color={dark ? "rgba(255,255,255,0.6)" : "var(--text-faint)"} /></button> : null}
      {res ? (
        <div className="mk-search-pop">
          {res.valeurs.length ? <p className="mk-search-lbl">Valeurs</p> : null}
          {res.valeurs.map((v) => (
            <button key={v.sym} type="button" className="mk-search-item" onClick={() => { close(); onValeur(v.sym); }}>
              <span style={{ fontWeight: 700, color: "var(--text-strong)" }}>{v.nom}</span>
              <span className="naboo-num" style={{ marginLeft: "auto", fontVariantNumeric: "tabular-nums", color: "var(--text-body)", fontWeight: 700 }}>{v.val}</span>
              <span style={{ width: 70, textAlign: "right" }}><Delta value={v.d} /></span>
            </button>
          ))}
          {res.articles.length ? <p className="mk-search-lbl">Articles</p> : null}
          {res.articles.map((a) => (
            <button key={a.slug} type="button" className="mk-search-item" onClick={() => { close(); onArticle(a); }}>
              <Badge tone={CAT_TONE[a.cat] || "neutral"}>{a.tag || a.cat}</Badge>
              <span style={{ fontWeight: 600, color: "var(--text-strong)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.titre}</span>
            </button>
          ))}
          {!res.valeurs.length && !res.articles.length ? <p style={{ fontSize: 13, color: "var(--text-faint)", padding: "8px 12px", margin: 0 }}>Aucun résultat pour « {q} ».</p> : null}
        </div>
      ) : null}
    </div>
  );
}

function ActuCard({ a, lead, onOpen }) {
  return (
    <Card padding={lead ? 26 : 20} className={"mk-actu-hover mk-clickable" + (lead ? " mk-actu-lead" : "")} style={{ display: "flex", flexDirection: "column", gap: 10, minWidth: 0 }} onClick={() => onOpen(a)}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <Badge tone={CAT_TONE[a.cat] || "neutral"}>{a.cat}</Badge>
        <span style={{ fontSize: 12, fontWeight: 600, color: "var(--text-faint)" }}>{a.time}</span>
      </div>
      <h3 style={{ fontFamily: "var(--font-display)", fontSize: lead ? 23 : 17.5, fontWeight: 700, letterSpacing: "-0.015em", lineHeight: 1.25, color: "var(--text-strong)", margin: 0, maxWidth: lead ? 640 : "none" }}>{a.titre}</h3>
      <p style={{ fontSize: lead ? 14.5 : 13.5, lineHeight: 1.6, color: "var(--text-body)", margin: 0, maxWidth: lead ? 640 : "none" }}>{a.chapo}</p>
    </Card>
  );
}

/* ---------------- Vue article ---------------- */
function ArticleView({ a, onBack, onValeur, onArticle }) {
  const [copied, setCopied] = useState(false);
  const words = (a.body || []).join(" ").split(/\s+/).length;
  const minutes = Math.max(1, Math.round(words / 200));
  const lies = ALL_ARTICLES.filter((x) => x.slug !== a.slug && (x.cat === a.cat || (x.valeurs || []).some((s) => (a.valeurs || []).includes(s)))).slice(0, 3);
  const share = () => {
    const url = window.location.href;
    if (navigator.clipboard) navigator.clipboard.writeText(url).then(() => { setCopied(true); setTimeout(() => setCopied(false), 2200); });
  };
  return (
    <section style={{ padding: "34px 0 64px" }}>
      <div className="mk-container">
        <button type="button" className="mk-back" onClick={onBack}>
          <Icon name="arrow-left" size={15} color="var(--brand-blue)" /> Retour aux marchés
        </button>
        <div className="mk-article-grid">
          <article style={{ minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", marginBottom: 16 }}>
              <Badge tone={CAT_TONE[a.cat] || "brand"}>{a.tag || a.cat}</Badge>
              <span style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--brand-blue)" }}>{a.src || "Naboo"}</span>
              <span className="naboo-num" style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-faint)" }}>{a.time} · {minutes} min de lecture</span>
              <button type="button" className="mk-share" onClick={share}>
                <Icon name={copied ? "check" : "link"} size={14} color={copied ? "var(--positive)" : "var(--text-muted)"} />
                {copied ? "Lien copié" : "Partager"}
              </button>
            </div>
            <h1 style={{ fontFamily: "var(--font-display)", fontSize: "clamp(27px, 3.4vw, 38px)", fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.12, color: "var(--text-strong)", margin: "0 0 14px", maxWidth: 700 }}>{a.titre}</h1>
            <p style={{ fontSize: 17, lineHeight: 1.6, fontWeight: 600, color: "var(--text-body)", margin: "0 0 22px", maxWidth: 680 }}>{a.chapo}</p>
            <Visual cat={a.cat} big style={{ marginBottom: 26 }} />
            <div style={{ maxWidth: 680 }}>
              {(a.body || []).map((p) => (
                <p key={p.slice(0, 40)} style={{ fontSize: 15.5, lineHeight: 1.75, color: "var(--text-body)", margin: "0 0 18px" }}>{p}</p>
              ))}
            </div>
            {a.impact ? (
              <div style={{ display: "flex", gap: 11, alignItems: "flex-start", background: "#EEF3FF", border: "1px solid var(--brand-blue)", borderRadius: "var(--radius-md)", padding: "13px 16px", margin: "4px 0 22px", maxWidth: 680 }}>
                <Icon name="lightbulb" size={17} color="var(--brand-blue)" style={{ flex: "none", marginTop: 2 }} />
                <p style={{ fontSize: 13.5, lineHeight: 1.6, color: "var(--text-body)", margin: 0 }}>{a.impact}</p>
              </div>
            ) : null}
            {a.valeurs && a.valeurs.length ? (
              <div style={{ maxWidth: 680, marginTop: 6 }}>
                <p className="mk-overline" style={{ marginBottom: 4 }}>Valeurs associées</p>
                {a.valeurs.map(findValeur).filter(Boolean).map((v, i) => <ValeurRow key={v.sym} {...v} i={i} onOpen={onValeur} />)}
              </div>
            ) : null}
            {lies.length ? (
              <div style={{ marginTop: 34 }}>
                <p className="mk-overline" style={{ marginBottom: 12 }}>À lire aussi</p>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(210px, 1fr))", gap: 14 }}>
                  {lies.map((x) => (
                    <Card key={x.slug} padding={16} className="mk-actu-hover mk-clickable" style={{ minWidth: 0 }} onClick={() => onArticle(x)}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                        <Badge tone={CAT_TONE[x.cat] || "neutral"}>{x.tag || x.cat}</Badge>
                        <span style={{ fontSize: 11.5, fontWeight: 600, color: "var(--text-faint)" }}>{x.time}</span>
                      </div>
                      <h3 style={{ fontFamily: "var(--font-display)", fontSize: 15, fontWeight: 700, lineHeight: 1.32, color: "var(--text-strong)", margin: 0 }}>{x.titre}</h3>
                    </Card>
                  ))}
                </div>
              </div>
            ) : null}
            <p style={{ fontSize: 12.5, color: "var(--text-faint)", marginTop: 26, lineHeight: 1.6, maxWidth: 680 }}>
              Article de démonstration (contenu fictif, non contractuel). Ces informations ne constituent pas un conseil en investissement.
            </p>
          </article>
          <aside style={{ display: "flex", flexDirection: "column", gap: 16, minWidth: 0 }}>
            <ConsulteesCard onOpen={onValeur} />
            <Card padding={20}>
              <p className="mk-overline" style={{ marginBottom: 8 }}>Un doute sur vos placements ?</p>
              <p style={{ fontSize: 13.5, lineHeight: 1.6, color: "var(--text-body)", margin: "0 0 14px" }}>Faites relire votre portefeuille par un vrai conseiller, pour 14 €.</p>
              <a href="Analyse.html"><Button block variant="secondary">Faire analyser mon portefeuille</Button></a>
            </Card>
          </aside>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Fiche valeur ---------------- */
function ValeurView({ v, onBack, onValeur, onArticle }) {
  const [suivies, setSuivies] = useState(getSuivies());
  const [alertes, setAlertes] = useState(getAlertes());
  const suivie = suivies.includes(v.sym);
  const alerte = !!alertes[v.sym];
  const pos = v.d >= 0;
  const actus = ALL_ARTICLES.filter((a) => (a.valeurs || []).includes(v.sym));
  return (
    <section style={{ padding: "34px 0 64px" }}>
      <div className="mk-container">
        <button type="button" className="mk-back" onClick={onBack}>
          <Icon name="arrow-left" size={15} color="var(--brand-blue)" /> Retour aux marchés
        </button>
        <div className="mk-article-grid">
          <div style={{ minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 14, flexWrap: "wrap", marginBottom: 6 }}>
              <div style={{ flex: 1, minWidth: 220 }}>
                <p className="mk-overline" style={{ marginBottom: 6 }}>{v.type}</p>
                <h1 style={{ fontFamily: "var(--font-display)", fontSize: "clamp(26px, 3vw, 34px)", fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)", margin: 0 }}>{v.nom}</h1>
              </div>
              <button type="button" className={"mk-follow" + (suivie ? " mk-follow-on" : "")} onClick={() => setSuivies(toggleSuivie(v.sym))}>
                <Icon name="star" size={15} color={suivie ? "#fff" : "var(--brand-blue)"} />
                {suivie ? "Suivie" : "Suivre"}
              </button>
            </div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 14, flexWrap: "wrap", margin: "10px 0 18px" }}>
              <span className="naboo-num" style={{ fontFamily: "var(--font-display)", fontSize: 38, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)", fontVariantNumeric: "tabular-nums" }}>{v.val}</span>
              <span style={{ fontSize: 16, fontWeight: 700, color: pos ? "var(--positive)" : "var(--negative)" }}>{pos ? "▲" : "▼"} {fmtPct(v.d)} <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-faint)" }}>aujourd'hui</span></span>
            </div>
            <Card padding={20} style={{ marginBottom: 16 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
                <p className="mk-overline" style={{ margin: 0 }}>Séance en cours</p>
                <span style={{ fontSize: 11.5, color: "var(--text-faint)" }}>Différé 15 min · Twelve Data / CoinGecko</span>
              </div>
              <AreaChart data={v.spark} height={120} color={pos ? "var(--positive)" : "var(--negative)"} fill strokeWidth={2} style={{ width: "100%" }} />
              <div className="mk-valeur-stats">
                <div><span>Ouverture</span><b className="naboo-num">{v.stats.ouv}</b></div>
                <div><span>Plus haut</span><b className="naboo-num">{v.stats.haut}</b></div>
                <div><span>Plus bas</span><b className="naboo-num">{v.stats.bas}</b></div>
                <div><span>Sur 1 an</span><b style={{ color: v.an >= 0 ? "var(--positive)" : "var(--negative)" }}>{fmtPct(v.an)}</b></div>
              </div>
            </Card>
            <p style={{ fontSize: 14.5, lineHeight: 1.65, color: "var(--text-body)", margin: "0 0 22px", maxWidth: 640 }}>{v.desc}</p>
            {actus.length ? (
              <div>
                <p className="mk-overline" style={{ marginBottom: 12 }}>Actus liées</p>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 14 }}>
                  {actus.map((a) => (
                    <Card key={a.slug} padding={16} className="mk-actu-hover mk-clickable" style={{ minWidth: 0 }} onClick={() => onArticle(a)}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                        <Badge tone={CAT_TONE[a.cat] || "neutral"}>{a.tag || a.cat}</Badge>
                        <span style={{ fontSize: 11.5, fontWeight: 600, color: "var(--text-faint)" }}>{a.time}</span>
                      </div>
                      <h3 style={{ fontFamily: "var(--font-display)", fontSize: 15, fontWeight: 700, lineHeight: 1.32, color: "var(--text-strong)", margin: 0 }}>{a.titre}</h3>
                    </Card>
                  ))}
                </div>
              </div>
            ) : <p style={{ fontSize: 13.5, color: "var(--text-faint)" }}>Pas d'actualité récente sur cette valeur.</p>}
            <p style={{ fontSize: 12.5, color: "var(--text-faint)", marginTop: 26, lineHeight: 1.6, maxWidth: 640 }}>
              Données de démonstration, non contractuelles. Ces informations ne constituent pas un conseil en investissement.
            </p>
          </div>
          <aside style={{ display: "flex", flexDirection: "column", gap: 16, minWidth: 0 }}>
            <Card padding={20}>
              <p className="mk-overline" style={{ marginBottom: 8 }}>Alerte de variation</p>
              <label className="mk-alert-row">
                <span style={{ fontSize: 13.5, lineHeight: 1.5, color: "var(--text-body)", flex: 1 }}>Me prévenir si <b>{v.nom}</b> varie de ±5 % en une séance</span>
                <button type="button" role="switch" aria-checked={alerte} className={"mk-switch" + (alerte ? " mk-switch-on" : "")} onClick={() => setAlertes(toggleAlerte(v.sym))}><span></span></button>
              </label>
              <p style={{ fontSize: 11.5, color: "var(--text-faint)", margin: "10px 0 0" }}>{alerte ? "Alerte activée (démonstration : notification par e-mail au lancement)." : "Aucune alerte sur cette valeur."}</p>
            </Card>
            <ConsulteesCard onOpen={onValeur} />
          </aside>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Page ---------------- */
function PageMarches() {
  const [route, setRoute] = useState(parseHash());
  const [shown, setShown] = useState(6);
  const [suiviesTick, setSuiviesTick] = useState(0);
  useEffect(() => {
    const f = () => setRoute(parseHash());
    window.addEventListener("hashchange", f);
    return () => window.removeEventListener("hashchange", f);
  }, []);
  useEffect(() => { window.scrollTo(0, 0); }, [route.article, route.valeur]);
  useEffect(() => { setShown(6); }, [route.cat]);

  const openArticle = (a) => setHash({ cat: route.cat, article: a.slug });
  const openValeur = (sym) => setHash({ valeur: sym });
  const back = () => setHash({ cat: route.cat });
  const setCat = (c) => setHash({ cat: c });

  const majTime = new Date().toLocaleTimeString("fr-FR", { hour: "numeric", minute: "2-digit" }).replace(":", " h ");
  const majDate = new Date().toLocaleDateString("fr-FR", { weekday: "long", day: "numeric", month: "long" });

  const article = route.article ? findArticle(route.article) : null;
  const valeur = route.valeur ? findValeur(route.valeur) : null;

  if (article || valeur) {
    return (
      <div id="top" data-screen-label={valeur ? "Marchés — fiche valeur" : "Marchés — article"}>
        <S.SiteNav active="marches" home={HOME} />
        {valeur
          ? <ValeurView key={valeur.sym + suiviesTick} v={valeur} onBack={back} onValeur={openValeur} onArticle={openArticle} />
          : <ArticleView a={article} onBack={back} onValeur={openValeur} onArticle={openArticle} />}
        <S.SiteFooter />
      </div>
    );
  }

  const cat = CATS.includes(route.cat) ? route.cat : "Tout";
  const suivies = getSuivies();
  let list;
  if (cat === "Tout") list = ACTUS;
  else if (cat === "Mes valeurs") list = ACTUS.concat(CONTINU).filter((a) => (a.valeurs || []).some((s) => suivies.includes(s)));
  else list = ACTUS.filter((a) => a.cat === cat);

  return (
    <div id="top" data-screen-label="Marchés">
      <S.SiteNav dark active="marches" home={HOME} />

      {/* En-tête sombre + recherche + bandeau défilant des cours */}
      <header className="mk-dark" style={{ position: "relative", overflow: "hidden", padding: "64px 0 0" }}>
        <div className="mk-glow"></div>
        <S.Cosmos />
        <div className="mk-container" style={{ position: "relative", paddingBottom: 42 }}>
          <p className="mk-overline" style={{ color: "rgba(255,255,255,0.6)" }}>Marchés · {majDate}</p>
          <h1 className="mk-h1" style={{ color: "#fff", maxWidth: 640 }}>Les marchés, <span className="mk-marker">en clair</span>.</h1>
          <p className="mk-sub" style={{ color: "rgba(255,255,255,0.72)", maxWidth: 560, marginTop: 12 }}>
            L'essentiel de la séance et les nouvelles qui comptent pour votre épargne —
            sans jargon, sans panique.
          </p>
          <div style={{ maxWidth: 470, marginTop: 22 }}>
            <SearchBox dark onValeur={openValeur} onArticle={openArticle} />
          </div>
          <p style={{ fontSize: 12, color: "rgba(255,255,255,0.45)", margin: "14px 0 0" }}>Mis à jour à {majTime} (Paris) · cours différés 15 min (Twelve Data · CoinGecko)</p>
        </div>
        <div className="mk-ticker">
          <div className="mk-ticker-track">
            {INDICES.concat(INDICES).map((ix, i) => <TickerItem key={ix.nom + i} ix={ix} onOpen={openValeur} />)}
          </div>
        </div>
      </header>

      {/* À la une + palmarès */}
      <section className="mk-section-tight" style={{ paddingTop: 46, paddingBottom: 30 }}>
        <div className="mk-container">
          <div className="mk-marches-une">
            <Card padding={0} className="mk-actu-hover mk-clickable" style={{ overflow: "hidden", display: "flex", flexDirection: "column" }} onClick={() => openArticle(UNE)}>
              <div style={{ background: "var(--brand-gradient)", color: "#fff", padding: "26px 28px", flex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
                  <span style={{ background: "rgba(255,255,255,0.18)", borderRadius: 999, padding: "4px 11px", fontSize: 11.5, fontWeight: 700 }}>À la une · {UNE.cat}</span>
                  <span style={{ fontSize: 12, fontWeight: 600, opacity: 0.75 }}>{UNE.time}</span>
                </div>
                <h2 style={{ fontFamily: "var(--font-display)", fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.18, margin: "0 0 12px", maxWidth: 620, color: "#fff" }}>{UNE.titre}</h2>
                <p style={{ fontSize: 14.5, lineHeight: 1.65, opacity: 0.88, margin: 0, maxWidth: 620, color: "#fff" }}>{UNE.chapo}</p>
              </div>
              <div style={{ display: "flex", gap: 11, alignItems: "flex-start", padding: "15px 28px", background: "var(--surface-card)" }}>
                <Icon name="lightbulb" size={17} color="var(--brand-blue)" style={{ flex: "none", marginTop: 2 }} />
                <p style={{ fontSize: 13.5, lineHeight: 1.6, color: "var(--text-body)", margin: 0 }}>{UNE.impact}</p>
              </div>
            </Card>
            <Card padding={20} style={{ minWidth: 0 }}>
              <p className="mk-overline" style={{ marginBottom: 4 }}>Palmarès CAC 40</p>
              <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--positive)", margin: "10px 0 2px" }}>Plus fortes hausses</div>
              {PALMARES.hausses.map((v, i) => <ValeurRow key={v.sym} {...v} i={i} onOpen={openValeur} />)}
              <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--negative)", margin: "14px 0 2px" }}>Plus fortes baisses</div>
              {PALMARES.baisses.map((v, i) => <ValeurRow key={v.sym} {...v} i={i} onOpen={openValeur} />)}
            </Card>
          </div>
        </div>
      </section>

      {/* L'actu en continu */}
      <section style={{ padding: "10px 0 34px" }}>
        <div className="mk-container">
          <p className="mk-overline" style={{ marginBottom: 14 }}>L'actu en continu</p>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(195px, 1fr))", gap: 16 }}>
            {CONTINU.map((a) => (
              <Card key={a.titre} padding={12} className="mk-actu-hover mk-clickable" style={{ display: "flex", flexDirection: "column", gap: 10, minWidth: 0 }} onClick={() => openArticle(a)}>
                <Visual cat={a.cat} />
                <div style={{ padding: "0 4px 4px" }}>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 6 }}>
                    <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--brand-blue)" }}>{a.src}</span>
                    <span className="naboo-num" style={{ fontSize: 12, fontWeight: 600, color: "var(--text-faint)" }}>{a.time}</span>
                  </div>
                  <h3 style={{ fontFamily: "var(--font-display)", fontSize: 15.5, fontWeight: 700, letterSpacing: "-0.01em", lineHeight: 1.32, color: "var(--text-strong)", margin: 0 }}>{a.titre}</h3>
                </div>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* Indices détaillés + valeurs les plus consultées */}
      <section style={{ padding: "0 0 34px" }}>
        <div className="mk-container">
          <div className="mk-marches-cotes">
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(175px, 1fr))", gap: 14, alignContent: "start" }}>
              {INDICES.slice(0, 4).map((ix) => <IndexCard key={ix.nom} ix={ix} onOpen={openValeur} />)}
            </div>
            <ConsulteesCard onOpen={openValeur} />
          </div>
        </div>
      </section>

      {/* Fil d'actus */}
      <section className="mk-section-tight" style={{ background: "var(--surface-card)", borderTop: "1px solid var(--border-subtle)", borderBottom: "1px solid var(--border-subtle)" }}>
        <div className="mk-container">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 14, marginBottom: 20 }}>
            <div>
              <p className="mk-overline">Le fil</p>
              <h2 className="mk-h2" style={{ margin: 0 }}>Les dernières actualités</h2>
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {CATS.map((c) => (
                <button key={c} type="button" onClick={() => setCat(c)} className={"mk-cat-pill" + (cat === c ? " mk-cat-pill-on" : "")}>
                  {c === "Mes valeurs" ? <Icon name="star" size={13} color={cat === c ? "#fff" : "var(--brand-blue)"} style={{ marginRight: 5, verticalAlign: -2 }} /> : null}{c}
                </button>
              ))}
            </div>
          </div>
          {cat === "Mes valeurs" && !list.length ? (
            <Card padding={26} style={{ textAlign: "center" }}>
              <Icon name="star" size={26} color="var(--brand-blue)" style={{ marginBottom: 10 }} />
              <h3 style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 700, color: "var(--text-strong)", margin: "0 0 8px" }}>{suivies.length ? "Rien de neuf sur vos valeurs" : "Vous ne suivez encore aucune valeur"}</h3>
              <p style={{ fontSize: 13.5, color: "var(--text-body)", lineHeight: 1.6, maxWidth: 440, margin: "0 auto" }}>
                {suivies.length ? "Aucune actualité récente ne concerne les valeurs que vous suivez." : "Ouvrez une fiche valeur (en cliquant un cours ou via la recherche) puis appuyez sur « Suivre » : ses actualités apparaîtront ici."}
              </p>
            </Card>
          ) : (
            <div className="mk-actu-grid">
              {list.slice(0, shown).map((a, i) => <ActuCard key={a.titre} a={a} lead={cat === "Tout" && i === 0} onOpen={openArticle} />)}
            </div>
          )}
          {list.length > shown ? (
            <div style={{ textAlign: "center", marginTop: 22 }}>
              <Button variant="ghost" onClick={() => setShown((s) => s + 6)}>Charger plus d'articles ({list.length - shown})</Button>
            </div>
          ) : null}
        </div>
      </section>

      {/* Pédagogie */}
      <section style={{ padding: "38px 0 6px" }}>
        <div className="mk-container">
          <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginBottom: 14 }}>
            <p className="mk-overline" style={{ margin: 0 }}>Pédagogie</p>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-faint)" }}>Comprendre avant d'investir</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))", gap: 16 }}>
            {PEDAGO.map((p) => (
              <Card key={p.titre} padding={12} className="mk-actu-hover mk-clickable" style={{ display: "flex", flexDirection: "column", gap: 10, minWidth: 0 }} onClick={() => openArticle(p)}>
                <Visual cat="Pédagogie" />
                <div style={{ padding: "0 4px 4px" }}>
                  <Badge tone="brand" style={{ marginBottom: 8 }}>{p.tag}</Badge>
                  <h3 style={{ fontFamily: "var(--font-display)", fontSize: 16.5, fontWeight: 700, letterSpacing: "-0.01em", lineHeight: 1.3, color: "var(--text-strong)", margin: 0 }}>{p.titre}</h3>
                </div>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* Brèves */}
      <section className="mk-section-tight">
        <div className="mk-container">
          <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginBottom: 18 }}>
            <p className="mk-overline" style={{ margin: 0 }}>En bref</p>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-faint)" }}>La matinée en six lignes</span>
          </div>
          <div className="mk-breves">
            {BREVES.map((b) => (
              <div key={b.time} className="mk-breve">
                <span className="mk-breve-time naboo-num">{b.time}</span>
                <span style={{ fontSize: 14, lineHeight: 1.55, color: "var(--text-body)" }}>{b.txt}</span>
              </div>
            ))}
          </div>
          <p style={{ fontSize: 12.5, color: "var(--text-faint)", marginTop: 24, lineHeight: 1.6, maxWidth: 640 }}>
            Maquette de démonstration : cours et articles illustratifs, non contractuels.
            Ces informations ne constituent pas un conseil en investissement.
          </p>
        </div>
      </section>

      {/* Passerelle vers les offres */}
      <section className="mk-section-tight" style={{ background: "var(--surface-card)", borderTop: "1px solid var(--border-subtle)" }}>
        <div className="mk-container" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 18 }}>
          <div style={{ maxWidth: 520 }}>
            <h2 className="mk-h2" style={{ marginBottom: 8 }}>Et pour votre portefeuille ?</h2>
            <p className="mk-sub" style={{ margin: 0 }}>Les marchés bougent ; votre stratégie n'a pas besoin de bouger tous les jours. Parlons-en.</p>
          </div>
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            <a href="Analyse.html"><Button variant="secondary">Faire analyser mon portefeuille</Button></a>
            <a href="Gestion.html"><Button leadingIcon={<Icon name="trending-up" size={16} color="#fff" />}>Découvrir la gestion</Button></a>
          </div>
        </div>
      </section>

      <S.SiteFooter />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("site-root")).render(<PageMarches />);
