// Dashboard — Factures table (liste · détail · création via dialog).
// StatusBadge (mapping versionné) · états démo : normal | loading | empty | error.
// window.OryzeDash.FacturesView
(function () {
  const { Card, Amount, Tabs, Button, Avatar, Input, StatusBadge, Skeleton, EmptyState, Dialog } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;
  const BADGE = window.OryzeInvoiceBadge;

  const HEAD = ["Client", "Référence", "Émission", "Échéance", "Montant HT", ""];
  const GRID = "2fr 1fr 1fr 1.1fr 1fr 40px";
  const lbl = { fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" };

  function Header() {
    return (
      <div style={{ display: "grid", gridTemplateColumns: GRID, gap: 12, padding: "11px 18px", borderBottom: "1.5px solid var(--line-keyline)", background: "var(--surface-page)" }}>
        {HEAD.map((h, i) => <div key={i} style={{ ...lbl, textAlign: i === 4 ? "right" : "left" }}>{h}</div>)}
      </div>
    );
  }

  function FacturesView({ onOpen, onCreate, onClients, demoState = "normal" }) {
    const ALL = window.OryzeInvoices;
    const [tab, setTab] = React.useState("all");
    const [q, setQ] = React.useState("");
    const [retrying, setRetrying] = React.useState(false);
    const [rapOpen, setRapOpen] = React.useState(false);
    const [rapCount, setRapCount] = React.useState(4); // suggestions + orphelins (démo)
    const list = ALL
      .filter((f) => (tab === "all" ? true : tab === "late" ? f.status === "late" : tab === "paid" ? f.status === "paid" : f.status === "due" || f.status === "draft"))
      .filter((f) => f.who.toLowerCase().includes(q.toLowerCase()) || f.id.toLowerCase().includes(q.toLowerCase()));

    // ---- États démo : chargement / vide / erreur (patterns guidelines/states.html) ----
    if (demoState === "empty") {
      return (
        <EmptyState framed title="Aucune facture pour l'instant"
          description="Créez votre première facture : le numéro sera attribué automatiquement à la finalisation."
          action={<Button size="sm" iconLeft={<Ic.plus size={15} />} onClick={() => onCreate && onCreate()}>Créer une facture</Button>} />
      );
    }

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
          <Input placeholder="Rechercher un client, une référence…" value={q} onChange={(e) => setQ(e.target.value)} iconLeft={<Ic.search size={18} />} style={{ flex: 1, maxWidth: 380 }} />
          <div style={{ display: "flex", gap: 10, flex: "none" }}>
            <Button variant="secondary" iconLeft={<Ic.users size={16} />} onClick={() => onClients && onClients()}>Clients</Button>
            <Button iconLeft={<Ic.plus size={16} />} onClick={() => onCreate && onCreate()}>Nouvelle facture</Button>
          </div>
        </div>

        {/* P7-3 — bandeau « à rapprocher » : suggestion par règle, confirmation humaine (jamais automatique) */}
        {demoState === "normal" && rapCount > 0 && (
          <Card variant="flat" padding="11px 16px" style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ width: 34, height: 34, borderRadius: "var(--radius-md)", background: "var(--oryze-lilac)", border: "var(--border-thin) solid var(--line-keyline)", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--oryze-lilac-ink)", flex: "none" }}>
              <Ic.link size={17} />
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <span style={{ fontWeight: 600, fontSize: 13.5 }}>{rapCount} encaissement{rapCount > 1 ? "s" : ""} à rapprocher</span>
              <span style={{ fontSize: 12.5, color: "var(--text-muted)", marginLeft: 8 }}>Suggestions prêtes — vous confirmez, rien n'est lié automatiquement.</span>
            </div>
            <Button size="sm" variant="secondary" onClick={() => setRapOpen(true)} style={{ flex: "none" }}>Rapprocher</Button>
          </Card>
        )}

        <Tabs value={tab} onChange={setTab} tabs={[
          { value: "all", label: "Toutes" },
          { value: "late", label: "En retard", count: 1 },
          { value: "due", label: "À échoir", count: 3 },
          { value: "paid", label: "Payées" }]} />

        {demoState === "loading" ? (
          <Card variant="flat" padding="0">
            <Header />
            {[0, 1, 2, 3, 4].map((i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: GRID, gap: 12, padding: "14px 18px", borderBottom: "1px solid var(--line-divider)", alignItems: "center" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <Skeleton variant="circle" size={34} />
                  <Skeleton variant="text" width={120 + (i % 3) * 30} />
                </div>
                <Skeleton variant="text" width={70} />
                <Skeleton variant="text" width={44} />
                <Skeleton variant="text" width={44} />
                <Skeleton variant="text" width={72} style={{ marginLeft: "auto" }} />
                <span />
              </div>
            ))}
          </Card>
        ) : demoState === "error" ? (
          <Card variant="flat" padding="44px 24px" style={{ textAlign: "center" }}>
            <div style={{ width: 44, height: 44, margin: "0 auto 14px", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--oryze-coral)", border: "var(--border-key) solid var(--line-keyline)", borderRadius: "var(--radius-md)", color: "var(--oryze-coral-ink)" }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 9v4M12 17h.01"/><path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/></svg>
            </div>
            <div style={{ fontWeight: 700, fontSize: 17, letterSpacing: "-0.01em" }}>Impossible de charger vos factures</div>
            <div style={{ fontSize: 13.5, color: "var(--text-muted)", marginTop: 5 }}>Vos données sont en sécurité — c'est un problème de connexion, pas de contenu.</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-subtle)", marginTop: 7 }}>GET /factures · 503 · réf. a1f4-…</div>
            <Button variant="secondary" size="sm" loading={retrying} style={{ marginTop: 16 }}
              onClick={() => { setRetrying(true); setTimeout(() => setRetrying(false), 1400); }}>Réessayer</Button>
          </Card>
        ) : (
          <Card variant="flat" padding="0">
            <Header />
            {list.map((f) => <Row key={f.id} f={f} onOpen={onOpen} />)}
            {list.length === 0 && (
              <div style={{ padding: "40px", textAlign: "center", color: "var(--text-muted)", fontSize: 14 }}>Aucune facture ne correspond.</div>
            )}
          </Card>
        )}

        {/* Rapprochement encaissement ↔ facture (P7-3) */}
        <Dialog open={rapOpen} onClose={() => setRapOpen(false)} width={700}
          title="Rapprochement" subtitle="Encaissements ↔ factures — suggestion par règle versionnée, confirmation humaine">
          {rapOpen && React.createElement(window.OryzeShared.RapprochementPanel, { onCountChange: setRapCount })}
        </Dialog>
      </div>
    );
  }

  function Row({ f, onOpen }) {
    const [h, setH] = React.useState(false);
    const b = BADGE[f.status] || BADGE.due;
    const ht = window.OryzeInvoiceCalc(f).ht;
    return (
      <div
        onClick={() => onOpen && onOpen(f)}
        onMouseEnter={() => setH(true)}
        onMouseLeave={() => setH(false)}
        style={{ display: "grid", gridTemplateColumns: GRID, gap: 12, padding: "12px 18px", borderBottom: "1px solid var(--line-divider)", alignItems: "center", cursor: "pointer", background: h ? "var(--surface-page)" : "transparent", transition: "background var(--dur-fast) var(--ease-out)" }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Avatar initials={f.init} tone={f.tone} size={34} />
          <div>
            <div style={{ fontWeight: 600, fontSize: 14 }}>{f.who}</div>
            <div style={{ marginTop: 3 }}><StatusBadge size="sm" status={b.status} label={b.label} /></div>
          </div>
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-muted)", fontStyle: f.numberPending ? "italic" : "normal" }}>
          {f.numberPending ? "n° à la finalisation" : f.id}
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-muted)" }}>{(f.issued || "").slice(0, 5)}</div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: f.status === "late" ? "var(--fin-negative)" : "var(--text-body)" }}>{(f.due || "").slice(0, 5)}</div>
        <div style={{ textAlign: "right" }}><Amount value={ht} size="md" /></div>
        <div style={{ textAlign: "right", color: "var(--text-subtle)" }}><Ic.chevronRight size={18} /></div>
      </div>
    );
  }

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