// Dashboard — Trésorerie dédiée (prospectif : projection + échéancier). window.OryzeDash.TresorerieView
(function () {
  const { Card, Amount, Tag, Button, StatTile, SegmentedControl, MiniBars, StatusBadge, EmptyState, CashTensionRing } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;

  // Projection de solde — semaine par semaine. Constaté puis prévisionnel.
  // Seuil de sécurité : 2 000 €.
  const THRESHOLD = 2000;
  const weeks = [
    { d: "01/04", v: 7860, past: true },
    { d: "08/04", v: 8460, past: true },
    { d: "15/04", v: 8920, past: true, today: true },
    { d: "22/04", v: 8114 },
    { d: "29/04", v: 9698 },
    { d: "06/05", v: 8558 },
    { d: "13/05", v: 8160 },
    { d: "20/05", v: 7380 },
    { d: "27/05", v: 6310 },
    { d: "03/06", v: 4870 },
    { d: "10/06", v: 3240 },
    { d: "17/06", v: 1880 },
  ];

  // Échéancier groupé par période — impact cumulé sur le solde.
  const schedule = [
    {
      period: "Cette semaine · 15–21 avr", start: 8920, items: [
        { label: "Loyer — Atelier", date: "18/04", amount: -720, icon: "building", bg: "var(--oryze-lilac)", tag: ["neutral", "Prévu"] },
        { label: "Abonnements SaaS", date: "20/04", amount: -86, icon: "settings", bg: "var(--oryze-lilac)", tag: ["neutral", "Prévu"] },
      ],
    },
    {
      period: "Semaine du 28 avr", start: 8114, items: [
        { label: "Boulangerie Lou — FAC-2044", date: "30/04", amount: 1584, icon: "arrowUpRight", bg: "var(--oryze-mint)", tag: ["due", "Attendu"] },
        { label: "Atelier Rivoli — FAC-2046", date: "02/05", amount: 1238.4, icon: "arrowUpRight", bg: "var(--oryze-mint)", tag: ["due", "Attendu"] },
        { label: "URSSAF — cotisations", date: "05/05", amount: -1140, icon: "percent", bg: "var(--oryze-butter)", tag: ["neutral", "Prévu"] },
      ],
    },
    {
      period: "Plus tard", start: 9796.4, items: [
        { label: "TVA — provision T2", date: "31/07", amount: -2480, icon: "percent", bg: "var(--oryze-butter)", tag: ["brand", "De côté"] },
      ],
    },
  ];

  const fmt = (v) => v.toLocaleString("fr-FR", { minimumFractionDigits: 2 }) + " €";
  const fmtK = (v) => v.toLocaleString("fr-FR") + " €";

  // Barres hebdomadaires — même vocabulaire que le reste du système : aplats
  // pastel + keyline 1.5px. Constaté en mint plein, prévisionnel en hachures
  // lavande, sous le seuil en coral. Seuil = ligne pointillée rouge.
  function ProjectionChart({ horizon }) {
    const data = horizon === "30 j" ? weeks.slice(0, 7) : weeks;
    const H = 185, max = 11000;
    const yTh = (THRESHOLD / max) * H;

    return (
      <div style={{ position: "relative", paddingTop: 22 }}>
        {/* seuil de sécurité — ligne seule; le libellé vit dans la légende */}
        <div style={{ position: "absolute", left: 0, right: 0, bottom: 24 + yTh, borderTop: "1.5px dashed var(--fin-negative)", zIndex: 1, pointerEvents: "none" }}></div>

        <div style={{ display: "flex", alignItems: "stretch", gap: 10, height: H + 24 }}>
          {data.map((w, i) => {
            const under = w.v < THRESHOLD + 500 && !w.past;
            const showVal = w.today || i === data.length - 1;
            return (
              <React.Fragment key={w.d}>
                <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "flex-end", gap: 6 }}>
                  {showVal && (
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, color: under ? "var(--fin-negative)" : "var(--text-strong)", whiteSpace: "nowrap" }}>{fmtK(w.v)}</span>
                  )}
                  <div style={{
                    width: "100%", maxWidth: 44,
                    height: Math.max(6, (w.v / max) * H - (showVal ? 20 : 0)),
                    background: w.past
                      ? "var(--oryze-mint)"
                      : under
                      ? "var(--oryze-coral)"
                      : "repeating-linear-gradient(45deg, var(--oryze-lavender) 0 5px, var(--oryze-paper) 5px 10px)",
                    border: "1.5px solid var(--line-keyline)",
                    borderRadius: "4px 4px 0 0",
                    boxSizing: "border-box",
                  }} />
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: w.today ? "var(--text-strong)" : "var(--text-subtle)", fontWeight: w.today ? 700 : 400, whiteSpace: "nowrap" }}>{w.d}</span>
                </div>
                {w.today && (
                  <div aria-hidden="true" style={{ flex: "none", width: 0, borderLeft: "1.5px dashed var(--line-keyline)", position: "relative", margin: "0 2px" }}>
                    <span style={{ position: "absolute", top: -20, left: -32, fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-subtle)", whiteSpace: "nowrap" }}>Aujourd'hui</span>
                  </div>
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>
    );
  }

  function TresorerieView({ demoState = "normal" }) {
    const [horizon, setHorizon] = React.useState("60 j");
    const [ct, setCt] = React.useState("vigilance"); // démo — scénario cash_tension

    // ---- États démo : chargement / vide / erreur (patterns guidelines/states.html) ----
    const { ErrorState, SkelTiles, SkelListCard, SkelBlockCard } = window.OryzeShared;
    if (demoState === "empty") {
      return (
        <EmptyState framed title="Pas encore de trésorerie à projeter"
          description="La projection se construit à partir de vos mouvements et de vos échéances — elle apparaît dès vos premières opérations."
          action={<Button size="sm" variant="secondary" iconLeft={<Ic.plus size={15} />}>Ajouter une échéance</Button>} />
      );
    }
    if (demoState === "loading") {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <SkelTiles n={4} />
          <SkelBlockCard height={230} />
          <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16, alignItems: "start" }}>
            <SkelListCard rows={5} avatar={false} />
            <SkelBlockCard height={160} />
          </div>
        </div>
      );
    }
    if (demoState === "error") {
      return <ErrorState what="Impossible de charger votre trésorerie" endpoint="GET /tresorerie/projection · 503 · réf. b7c2-…" />;
    }

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {/* KPI row — prospectif */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16 }}>
          <StatTile label="Solde · aujourd'hui" value={<Amount value={8920} size="lg" />} hint="Compte pro · 15 avr" />
          <StatTile label="Prévisionnel · 30 j" value={<Amount value={8990} size="lg" />} accent="var(--oryze-mint)" hint="+ 2 encaissements attendus" />
          <StatTile label="Point bas prévu" value={<Amount value={1880} size="lg" tone="negative" />} accent="var(--oryze-coral)" hint="semaine du 17 juin — sous le seuil" />
          <StatTile label="Autonomie" value={<span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 26, letterSpacing: "-0.02em" }}>2,9 <span style={{ fontSize: 15, fontWeight: 600, color: "var(--text-muted)" }}>mois</span></span>} accent="var(--oryze-butter)" hint="au rythme de dépenses actuel" />
        </div>

        {/* Santé de trésorerie — cash_tension v1 (barème figé 13/07) : Sain ≥1,3 · Vigilance 1,0–1,3 · Tendu <1,0 · « En cours » tant que les socles manquent. Jamais de boîte noire : trace + détail du calcul. */}
        <Card variant="flat" padding="20px">
          {(() => {
            const st = window.OryzeShared.cashTensionState(ct);
            return (
              <React.Fragment>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div style={{ fontWeight: 700, fontSize: 15, letterSpacing: "-0.01em" }}>Santé de trésorerie · 30 jours</div>
                    <Tag tone="butter" style={{ fontSize: 10.5, padding: "3px 8px" }}>Estimation</Tag>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-subtle)" }}>démo</span>
                    <SegmentedControl size="sm" value={ct} onChange={setCt} options={[
                      { value: "pending", label: "En cours" }, { value: "sain", label: "Sain" },
                      { value: "vigilance", label: "Vigilance" }, { value: "tendu", label: "Tendu" },
                    ]} />
                  </div>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "auto minmax(0,1.1fr) minmax(0,1fr)", gap: 24, alignItems: "center", marginTop: 16 }}>
                  <CashTensionRing size={116} thickness={15} state={st.key} days={st.days} />
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 17, letterSpacing: "-0.01em", lineHeight: 1.35 }}>{st.message}</div>
                    <div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 8, lineHeight: 1.5 }}>
                      Ratio de couverture sur 30 jours : (solde + encaissements pondérés) / décaissements prévus.
                    </div>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8, borderLeft: "1px solid var(--line-divider)", paddingLeft: 22 }}>
                    {st.rows.map((r) => (
                      <div key={r.label} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12, fontSize: 12.5 }}>
                        <span style={{ color: "var(--text-muted)" }}>{r.label}</span>
                        {r.text != null
                          ? <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 600, color: "var(--text-strong)" }}>{r.text}</span>
                          : r.value == null
                          ? <span style={{ fontFamily: "var(--font-mono)", color: "var(--text-subtle)" }}>—</span>
                          : <Amount value={r.value} size="sm" tone={r.value < 0 ? "negative" : undefined} />}
                      </div>
                    ))}
                  </div>
                </div>
                <div style={{ marginTop: 14, paddingTop: 11, borderTop: "1px solid var(--line-divider)", fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-subtle)" }}>{st.trace}</div>
              </React.Fragment>
            );
          })()}
        </Card>

        {/* Projection de solde */}
        <Card variant="elevated" padding="20px">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 10 }}>
            <div>
              <div style={{ fontWeight: 700, fontSize: 16, letterSpacing: "-0.01em" }}>Projection de solde</div>
              <div style={{ fontSize: 13, color: "var(--text-muted)", marginTop: 2 }}>Semaine par semaine · prévisionnel d'après vos échéances</div>
            </div>
            <SegmentedControl size="sm" value={horizon} onChange={setHorizon} options={["30 j", "60 j"]} />
          </div>
          <ProjectionChart horizon={horizon} />
          <div style={{ display: "flex", alignItems: "center", gap: 18, marginTop: 14, paddingTop: 12, borderTop: "1px solid var(--line-divider)", fontSize: 12.5, color: "var(--text-muted)" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><span style={{ width: 12, height: 12, background: "var(--oryze-mint)", border: "1.5px solid var(--line-keyline)", borderRadius: 2 }} /> Constaté</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><span style={{ width: 12, height: 12, background: "repeating-linear-gradient(45deg, var(--oryze-lavender) 0 3px, var(--oryze-paper) 3px 6px)", border: "1.5px solid var(--line-keyline)", borderRadius: 2 }} /> Prévisionnel</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 7, whiteSpace: "nowrap" }}><span style={{ width: 16, height: 0, borderTop: "1.5px dashed var(--fin-negative)", flex: "none" }} /> Seuil 2 000 €</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><span style={{ width: 12, height: 12, background: "var(--oryze-coral)", border: "1.5px solid var(--line-keyline)", borderRadius: 2 }} /> Sous le seuil</span>
            {horizon === "60 j" && (
              <span style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 8 }}>
                <Tag tone="butter" dot>À surveiller</Tag>
                <span>Passage sous le seuil estimé <strong style={{ color: "var(--text-body)" }}>mi-juin</strong></span>
              </span>
            )}
          </div>
        </Card>

        {/* Échéancier + rythme mensuel */}
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16, alignItems: "start" }}>
          <Card variant="flat" padding="0">
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 18px", borderBottom: "1.5px solid var(--line-keyline)" }}>
              <div style={{ fontWeight: 700, fontSize: 15 }}>Échéancier</div>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-subtle)" }}>Impact cumulé</span>
            </div>
            {schedule.map((g, gi) => {
              let running = g.start;
              return (
                <div key={gi}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "9px 18px", background: "var(--surface-page)", borderBottom: "1px solid var(--line-divider)", borderTop: gi > 0 ? "1px solid var(--line-divider)" : "none" }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)", fontWeight: 600 }}>{g.period}</span>
                  </div>
                  {g.items.map((u, i) => {
                    const UIcon = Ic[u.icon] || Ic.wallet;
                    running += u.amount;
                    return (
                      <div key={i} style={{ display: "flex", alignItems: "center", gap: 13, padding: "11px 18px", borderBottom: "1px solid var(--line-divider)" }}>
                        <span style={{ flex: "none", width: 34, height: 34, borderRadius: "var(--radius-md)", background: u.bg, border: "1.5px solid var(--line-keyline)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                          <UIcon size={16} />
                        </span>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13.5, fontWeight: 600 }}>{u.label}</div>
                          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-subtle)", marginTop: 1 }}>{u.date}</div>
                        </div>
                        <Tag tone={u.tag[0]} dot>{u.tag[1]}</Tag>
                        <div style={{ textAlign: "right", minWidth: 128 }}>
                          <Amount value={u.amount} size="sm" sign tone={u.amount > 0 ? "positive" : "default"} />
                          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-subtle)", marginTop: 1 }}>→ {fmt(running)}</div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              );
            })}
            <div style={{ padding: "10px 18px", display: "flex", justifyContent: "flex-end" }}>
              <Button size="sm" variant="ghost" iconRight={<Ic.plus size={14} />}>Ajouter une échéance</Button>
            </div>
          </Card>

          <div style={{ display: "flex", flexDirection: "column", gap: 16, minWidth: 0 }}>
          {/* Rythme mensuel compact — MiniBars toneBySign */}
          <Card variant="flat" padding="20px">
            <div style={{ fontWeight: 700, fontSize: 15, letterSpacing: "-0.01em" }}>Rythme mensuel</div>
            <div style={{ fontSize: 13, color: "var(--text-muted)", marginTop: 2, marginBottom: 16 }}>Net encaissé − décaissé, 6 derniers mois</div>
            <MiniBars values={[1170, 1350, -270, 2070, 900, 2520]} toneBySign width={260} height={92} gap={10} style={{ width: "100%" }} />
            <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-subtle)", marginTop: 6 }}>
              {["Nov", "Déc", "Jan", "Fév", "Mar", "Avr"].map((m) => <span key={m}>{m}</span>)}
            </div>
            <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--line-divider)", display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
                <span style={{ color: "var(--text-muted)" }}>Encaissé / mois (moy.)</span>
                <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600 }}>5 713 €</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
                <span style={{ color: "var(--text-muted)" }}>Décaissé / mois (moy.)</span>
                <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600 }}>3 123 €</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
                <span style={{ color: "var(--text-muted)" }}>Net moyen</span>
                <Amount value={2590} size="sm" sign tone="positive" />
              </div>
            </div>
          </Card>

          {/* Virements — machine à états visible (pending → executed | failed). Démo : rien n'est émis. */}
          <Card variant="flat" padding="0">
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "13px 18px", borderBottom: "1.5px solid var(--line-keyline)" }}>
              <div style={{ fontWeight: 700, fontSize: 15 }}>Virements</div>
              <Tag tone="butter" mono>IBAN MOCK</Tag>
            </div>
            {[
              { label: "URSSAF — cotisations", date: "05/05", amount: -1140, status: "pending" },
              { label: "Print Pro — impression", date: "11/04", amount: -312, status: "executed" },
              { label: "Test IBAN invalide", date: "10/04", amount: -50, status: "failed", note: "Virement rejeté — IBAN invalide" },
            ].map((v, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 18px", borderBottom: i < 2 ? "1px solid var(--line-divider)" : "none" }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{v.label}</div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: v.status === "failed" ? "var(--fin-negative)" : "var(--text-subtle)", marginTop: 1 }}>{v.date}{v.note ? " · " + v.note : ""}</div>
                </div>
                <Amount value={v.amount} size="sm" />
                <StatusBadge size="sm" status={v.status} />
              </div>
            ))}
            <div style={{ padding: "9px 18px", borderTop: "1px solid var(--line-divider)", fontSize: 11.5, color: "var(--text-subtle)" }}>
              Mode démo : aucun virement réel n'est émis.
            </div>
          </Card>
          </div>
        </div>
      </div>
    );
  }

  window.OryzeDash = window.OryzeDash || {};
  window.OryzeDash.TresorerieView = TresorerieView;
})();
