// Dashboard — Documents (coffre-fort de pièces). window.OryzeDash.DocumentsView
(function () {
  const { Card, Tag, Button, Input, StatTile, EmptyState } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;
  const TYPES = window.OryzeDocTypes;

  function DocumentsView({ demoState = "normal" }) {
    const ALL = window.OryzeDocuments;
    const [type, setType] = React.useState("all");
    const [q, setQ] = React.useState("");

    // ---- États démo : chargement / vide / erreur (patterns guidelines/states.html) ----
    const { ErrorState, SkelTiles, SkelListCard } = window.OryzeShared;
    if (demoState === "empty") {
      return (
        <EmptyState framed title="Aucune pièce pour l'instant"
          description="Factures, reçus et documents d'entreprise se rangent ici — chaque pièce reliée à son opération."
          action={<Button size="sm" variant="secondary" iconLeft={<Ic.upload size={15} />}>Importer</Button>} />
      );
    }
    if (demoState === "loading") {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <SkelTiles n={4} />
          <SkelListCard rows={6} avatar={false} />
        </div>
      );
    }
    if (demoState === "error") {
      return <ErrorState what="Impossible de charger vos documents" endpoint="GET /documents · 503 · réf. a9c7-…" />;
    }

    const list = ALL
      .filter((d) => (type === "all" ? true : d.type === type))
      .filter((d) => d.name.toLowerCase().includes(q.toLowerCase()) || d.id.toLowerCase().includes(q.toLowerCase()));

    const counts = {}; ALL.forEach((d) => { counts[d.type] = (counts[d.type] || 0) + 1; });

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {/* Type summary tiles */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16 }}>
          {Object.keys(TYPES).map((k) => {
            const TIcon = Ic[TYPES[k].icon] || Ic.folder;
            return (
              <Card key={k} variant="flat" interactive padding="16px" onClick={() => setType(type === k ? "all" : k)}
                style={{ display: "flex", alignItems: "center", gap: 12, ...(type === k ? { boxShadow: "var(--shadow-xs)", borderColor: "var(--oryze-majorelle)" } : {}) }}>
                <span style={{ width: 38, height: 38, flex: "none", borderRadius: "var(--radius-md)", background: TYPES[k].color, border: "var(--border-thin) solid var(--line-keyline)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-strong)" }}><TIcon size={19} /></span>
                <div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 20, fontWeight: 600 }}>{counts[k] || 0}</div>
                  <div style={{ fontSize: 12.5, color: "var(--text-muted)" }}>{TYPES[k].label}</div>
                </div>
              </Card>
            );
          })}
        </div>

        {/* Toolbar */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
          <Input placeholder="Rechercher une pièce…" value={q} onChange={(e) => setQ(e.target.value)} iconLeft={<Ic.search size={18} />} style={{ flex: 1, maxWidth: 380 }} />
          <Button iconLeft={<Ic.plus size={16} />}>Importer</Button>
        </div>

        {/* Filter chips */}
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <Chip active={type === "all"} onClick={() => setType("all")}>Tout</Chip>
          {Object.keys(TYPES).map((k) => (
            <Chip key={k} active={type === k} dot={TYPES[k].color} onClick={() => setType(k)}>{TYPES[k].label}</Chip>
          ))}
        </div>

        {/* Table */}
        <Card variant="flat" padding="0">
          <div style={{ display: "grid", gridTemplateColumns: "minmax(0,2.4fr) 1fr 1fr 1fr 88px", gap: 12, padding: "11px 18px", borderBottom: "1.5px solid var(--line-keyline)", background: "var(--surface-page)" }}>
            {["Pièce", "Type", "Date", "Lié à", "Taille"].map((h, i) => (
              <div key={i} style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)", minWidth: 0, overflow: "hidden", whiteSpace: "nowrap", textAlign: i === 4 ? "right" : "left" }}>{h}</div>
            ))}
          </div>
          {list.map((d) => <Row key={d.id} d={d} />)}
          {list.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--text-muted)", fontSize: 14 }}>Aucune pièce ne correspond.</div>}
        </Card>
      </div>
    );
  }

  function Row({ d }) {
    const [h, setH] = React.useState(false);
    const t = window.OryzeDocTypes[d.type];
    const TIcon = window.OryzeIcons[t.icon] || window.OryzeIcons.folder;
    return (
      <div onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
        style={{ display: "grid", gridTemplateColumns: "minmax(0,2.4fr) 1fr 1fr 1fr 88px", gap: 12, padding: "11px 18px", borderBottom: "1px solid var(--line-divider)", alignItems: "center", background: h ? "var(--surface-page)" : "transparent" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, minWidth: 0 }}>
          <span style={{ width: 34, height: 34, flex: "none", borderRadius: "var(--radius-sm)", background: t.color, border: "var(--border-thin) solid var(--line-keyline)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-strong)" }}><TIcon size={16} /></span>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 600, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.name}</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-subtle)", marginTop: 1 }}>{d.ext} · {d.id}</div>
          </div>
        </div>
        <div><Tag tone="neutral" dot>{t.label}</Tag></div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-muted)" }}>{d.date}</div>
        <div style={{ minWidth: 0 }}>
          {d.linked
            ? <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-body)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", display: "block" }}>{d.linked}</span>
            : <span style={{ fontSize: 12.5, color: "var(--text-subtle)" }}>—</span>}
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 6 }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-subtle)" }}>{d.size}</span>
          <span style={{ color: h ? "var(--text-body)" : "var(--text-subtle)", display: "flex" }}><Ic.download size={16} /></span>
        </div>
      </div>
    );
  }

  function Chip({ active, dot, onClick, children }) {
    return (
      <button onClick={onClick} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 12px", borderRadius: "var(--radius-pill)", border: "1.5px solid var(--line-keyline)", background: active ? "var(--oryze-ink)" : "var(--surface-card)", color: active ? "var(--oryze-paper)" : "var(--text-body)", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, cursor: "pointer" }}>
        {dot && <span style={{ width: 7, height: 7, borderRadius: "50%", background: dot, border: "1px solid " + (active ? "var(--oryze-paper)" : "var(--line-keyline)") }} />}
        {children}
      </button>
    );
  }

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