// Import factures fournisseurs — module partagé web + mobile (frontière C6).
// IMPORT DOCUMENTAIRE uniquement : dépôt d'un fichier déjà reçu par ailleurs
// (Factur-X ou PDF), lecture, rapport d'écarts, rapprochement avec une dépense.
// JAMAIS de « réception » : la réception réglementaire passe par la Plateforme
// Agréée désignée par le client — Oryze n'est pas une PA. Vocabulaire proscrit :
// « recevez vos factures », « réception conforme », « Oryze reçoit vos factures ».
// window.OryzeShared.ImportFournisseurs ({ compact, demoState })
(function () {
  const { Card, Amount, Tag, Button, Select, Dialog, BottomSheet, EmptyState, Skeleton } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;

  const impLbl = { fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" };
  const gapsCount = (imp) => imp.checks.filter((c) => !c.ok).length;
  const fmtCents = (c) => (c / 100).toLocaleString("fr-FR", { minimumFractionDigits: 2 }) + " €";

  function ReadTag({ imp }) {
    if (imp.status === "processing") return <Tag tone="neutral" dot>Analyse en cours</Tag>;
    if (imp.status === "partial") return <Tag tone="butter" dot>Lecture partielle</Tag>;
    if (imp.status === "gaps") { const n = gapsCount(imp); return <Tag tone="butter" dot>{n + (n > 1 ? " écarts" : " écart")}</Tag>; }
    return <Tag tone="mint" dot>Analysée</Tag>;
  }

  // Frontière réglementaire — mention discrète, présente sur chaque rendu du module.
  function BoundaryNote() {
    return (
      <Card variant="flat" padding="14px 16px" background="var(--surface-sunken)">
        <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" style={{ flex: "none", marginTop: 2, color: "var(--text-muted)" }}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10" /></svg>
          <div style={{ fontSize: 12.5, color: "var(--text-muted)", lineHeight: 1.55, minWidth: 0 }}>
            <strong style={{ color: "var(--text-body)" }}>Import documentaire.</strong> Vous déposez ici un fichier déjà reçu par ailleurs (courriel, portail fournisseur…).
            La réception réglementaire de vos factures s'effectue via la Plateforme Agréée désignée par votre entreprise — Oryze n'est pas une Plateforme Agréée.
          </div>
        </div>
      </Card>
    );
  }

  function Dropzone({ compact, uploading, onPick }) {
    return (
      <Card variant="elevated" padding={compact ? "14px" : "18px"}>
        <div style={{ border: "1.5px dashed var(--oryze-ink-20)", borderRadius: "var(--radius-md)", background: "var(--surface-page)", padding: compact ? "20px 14px" : "26px 20px", display: "flex", flexDirection: "column", alignItems: "center", gap: 10, textAlign: "center" }}>
          <span style={{ width: 42, height: 42, display: "flex", alignItems: "center", justifyContent: "center", background: "var(--oryze-lilac)", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-md)" }}>
            <Ic.upload size={20} />
          </span>
          <div>
            <div style={{ fontWeight: 700, fontSize: compact ? 14.5 : 15.5, letterSpacing: "-0.01em" }}>Déposez une facture fournisseur</div>
            <div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 4, maxWidth: 380, lineHeight: 1.5 }}>
              Factur-X (PDF ou XML) ou PDF simple, reçus par ailleurs — lecture, contrôles et rapprochement avec vos dépenses.
            </div>
          </div>
          <Button size="sm" variant="secondary" iconLeft={<Ic.upload size={15} />} loading={uploading} onClick={onPick}>Choisir un fichier</Button>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-subtle)" }}>PDF · XML — 10 Mo max · démo : analyse simulée</div>
        </div>
      </Card>
    );
  }

  const GRIDI = "minmax(0,1.9fr) minmax(0,1.1fr) 0.9fr 1.1fr 1fr 26px";

  function FileIco({ imp, size = 34 }) {
    return (
      <span style={{ width: size, height: size, flex: "none", borderRadius: "var(--radius-sm)", background: imp.kind === "facturx" ? "var(--oryze-mint)" : "var(--oryze-butter)", border: "var(--border-thin) solid var(--line-keyline)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-strong)" }}>
        <Ic.file size={Math.round(size * 0.47)} />
      </span>
    );
  }

  function RowWeb({ imp, onOpen }) {
    const [h, setH] = React.useState(false);
    const processing = imp.status === "processing";
    return (
      <div onClick={processing ? undefined : onOpen} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
        style={{ display: "grid", gridTemplateColumns: GRIDI, gap: 12, padding: "12px 18px", borderBottom: "1px solid var(--line-divider)", alignItems: "center", cursor: processing ? "default" : "pointer", background: h && !processing ? "var(--surface-page)" : "transparent", transition: "background var(--dur-fast) var(--ease-out)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, minWidth: 0 }}>
          <FileIco imp={imp} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{imp.file}</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-subtle)", marginTop: 2 }}>{imp.profile} · {imp.size}</div>
          </div>
        </div>
        <div style={{ fontSize: 13.5, fontWeight: 600, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {processing ? <Skeleton variant="text" lines={1} height={12} width={90} /> : imp.supplier}
        </div>
        <div style={{ textAlign: "right" }}>{processing ? null : <Amount cents={imp.cents.ttc} size="sm" />}</div>
        <div><ReadTag imp={imp} /></div>
        <div>
          {imp.linkedTo
            ? <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-body)" }}>{imp.linkedTo}</span>
            : processing
            ? <span style={{ fontSize: 12.5, color: "var(--text-subtle)" }}>—</span>
            : <Tag tone="neutral">À lier</Tag>}
        </div>
        <div style={{ textAlign: "right", color: "var(--text-subtle)" }}>{!processing && <Ic.chevronRight size={17} />}</div>
      </div>
    );
  }

  function RowCompact({ imp, last, onOpen }) {
    const processing = imp.status === "processing";
    return (
      <div onClick={processing ? undefined : onOpen}
        style={{ display: "flex", alignItems: "center", gap: 11, padding: "12px 14px", borderBottom: last ? "none" : "1px solid var(--line-divider)", cursor: processing ? "default" : "pointer", background: "var(--surface-card)" }}>
        <FileIco imp={imp} size={32} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{imp.file}</div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginTop: 2, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-subtle)" }}>
            {processing
              ? <span>Analyse en cours…</span>
              : <React.Fragment><span style={{ minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{imp.supplier}</span><span>·</span><span>{fmtCents(imp.cents.ttc)}</span></React.Fragment>}
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4, flex: "none" }}>
          <ReadTag imp={imp} />
          {imp.linkedTo && <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-subtle)" }}>{imp.linkedTo}</span>}
        </div>
      </div>
    );
  }

  function Field({ k, v, mono, muted }) {
    return (
      <div style={{ minWidth: 0 }}>
        <div style={impLbl}>{k}</div>
        <div style={{ fontSize: 13, fontWeight: 600, marginTop: 3, fontFamily: mono ? "var(--font-mono)" : "var(--font-sans)", color: muted ? "var(--text-subtle)" : "var(--text-body)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{v}</div>
      </div>
    );
  }

  // Détail — données lues, rapport d'écarts, rapprochement. Web : Dialog ; mobile : BottomSheet.
  function DetailBody({ imp, compact, onLink }) {
    const [manual, setManual] = React.useState(window.OryzeExpenses[0].id);
    const nGaps = gapsCount(imp);
    const expOptions = window.OryzeExpenses.map((e) => ({
      value: e.id,
      label: e.merchant + " · " + fmtCents(Math.round(window.OryzeExpenseCalc(e).ttc * 100)) + " · " + e.date.slice(0, 5),
    }));
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <Tag mono>{imp.profile}</Tag>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-subtle)" }}>{imp.file} · {imp.size} · importé le {imp.importedAt}</span>
        </div>

        {/* Données lues */}
        <div>
          <div style={{ ...impLbl, marginBottom: 8 }}>Données lues dans le fichier</div>
          <div style={{ display: "grid", gridTemplateColumns: compact ? "1fr 1fr" : "1fr 1fr 1fr", gap: "12px 16px", padding: "13px 14px", background: "var(--surface-sunken)", border: "var(--border-hair) solid var(--line-divider)", borderRadius: "var(--radius-md)" }}>
            <Field k="Fournisseur" v={imp.supplier} />
            <Field k="SIREN" v={imp.siren || "non détecté"} mono muted={!imp.siren} />
            <Field k="N° de facture" v={imp.number} mono />
            <Field k="Émise le" v={imp.issued} mono />
            <Field k="Échéance" v={imp.due} mono />
            <Field k="TTC (dont TVA)" v={<span style={{ display: "inline-flex", gap: 7, alignItems: "baseline" }}><Amount cents={imp.cents.ttc} size="sm" /><span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-subtle)" }}>TVA {fmtCents(imp.cents.tva)}</span></span>} />
          </div>
        </div>

        {/* Rapport d'écarts */}
        <div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 8 }}>
            <div style={impLbl}>Rapport d'écarts</div>
            {nGaps === 0
              ? <Tag tone="mint" dot>{imp.checks.length}/{imp.checks.length} contrôles OK</Tag>
              : <Tag tone="butter" dot>{nGaps} point{nGaps > 1 ? "s" : ""} à vérifier</Tag>}
          </div>
          <div style={{ border: "var(--border-hair) solid var(--line-divider)", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
            {imp.checks.map((c, i) => (
              <div key={i} style={{ display: "flex", gap: 10, alignItems: "flex-start", padding: "10px 13px", borderBottom: i < imp.checks.length - 1 ? "1px solid var(--line-divider)" : "none", background: "var(--surface-card)" }}>
                <span style={{ flex: "none", marginTop: 1, color: c.ok ? "var(--fin-positive-text)" : "var(--oryze-warning-ink)" }}>{c.ok ? <Ic.check size={15} /> : <Ic.alert size={15} />}</span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: c.ok ? 500 : 600 }}>{c.label}</div>
                  {c.note && <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 2, lineHeight: 1.45 }}>{c.note}</div>}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Rapprochement */}
        <div>
          <div style={{ ...impLbl, marginBottom: 8 }}>Rapprochement</div>
          {imp.linkedTo ? (
            <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "12px 14px", background: "var(--oryze-mint)", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-md)", flexWrap: "wrap" }}>
              <Ic.link size={16} style={{ flex: "none" }} />
              <div style={{ flex: 1, minWidth: 140, fontSize: 13 }}>
                Liée à la dépense <strong style={{ fontFamily: "var(--font-mono)", fontSize: 12.5 }}>{imp.linkedTo}</strong>
                {imp.match && imp.match.id === imp.linkedTo ? " — " + imp.match.label : ""}
              </div>
              {imp.match && imp.match.id === imp.linkedTo && <Amount cents={imp.match.cents} size="sm" />}
            </div>
          ) : imp.match ? (
            <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", background: "var(--surface-sunken)", border: "var(--border-hair) solid var(--line-divider)", borderRadius: "var(--radius-md)", flexWrap: "wrap" }}>
              <div style={{ flex: 1, minWidth: 160 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>Dépense correspondante : {imp.match.label}</div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-subtle)", marginTop: 2 }}>{imp.match.id} · {imp.match.date} · {fmtCents(imp.match.cents)}</div>
              </div>
              <Button size="sm" iconLeft={<Ic.link size={14} />} onClick={() => onLink(imp, imp.match.id)}>Lier à cette dépense</Button>
            </div>
          ) : (
            <div style={{ display: "flex", gap: 10, alignItems: "flex-end", flexWrap: "wrap" }}>
              <Select label="Aucune correspondance automatique — choisissez la dépense" value={manual} onChange={(e) => setManual(e.target.value)} options={expOptions} style={{ flex: 1, minWidth: 210 }} />
              <Button size="sm" variant="secondary" iconLeft={<Ic.link size={14} />} onClick={() => onLink(imp, manual)}>Lier</Button>
            </div>
          )}
        </div>

        <div style={{ fontSize: 11.5, color: "var(--text-subtle)", lineHeight: 1.5, paddingTop: 10, borderTop: "var(--border-hair) solid var(--line-divider)" }}>
          La pièce est rangée dans Documents et reliée à la dépense. L'import est documentaire — la réception réglementaire relève de la Plateforme Agréée de votre entreprise.
        </div>
      </div>
    );
  }

  function ImportFournisseurs({ compact = false, demoState = "normal" }) {
    const [imports, setImports] = React.useState(() => window.OryzeImportsFournisseurs.slice());
    const [selId, setSelId] = React.useState(null);
    const [uploading, setUploading] = React.useState(false);
    const timer = React.useRef(null);
    React.useEffect(() => () => clearTimeout(timer.current), []);

    // ---- États démo : chargement / vide / erreur (patterns guidelines/states.html) ----
    if (demoState === "empty") {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <EmptyState framed title="Aucune facture fournisseur importée"
            description="Déposez un fichier reçu par ailleurs (Factur-X ou PDF) : lecture, contrôles et rapprochement avec vos dépenses."
            action={<Button size="sm" variant="secondary" iconLeft={<Ic.upload size={15} />}>Choisir un fichier</Button>} />
          <BoundaryNote />
        </div>
      );
    }
    if (demoState === "loading") {
      const SkelListCard = window.OryzeShared.SkelListCard;
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card variant="flat" padding="18px"><Skeleton variant="block" height={150} /></Card>
          <SkelListCard rows={3} avatar={false} />
        </div>
      );
    }
    if (demoState === "error") {
      const ErrorState = window.OryzeShared.ErrorState;
      return <ErrorState what="Impossible de charger vos imports" endpoint="GET /imports-fournisseurs · 503 · réf. c9d1-…" />;
    }

    const sel = imports.find((x) => x.id === selId) || null;

    function pick() {
      if (uploading) return;
      setUploading(true);
      const pending = Object.assign({}, window.OryzeImportDemoResult, { status: "processing", linkedTo: null });
      setImports((l) => [pending].concat(l.filter((x) => x.id !== pending.id)));
      timer.current = setTimeout(() => {
        setUploading(false);
        setImports((l) => l.map((x) => (x.id === pending.id ? Object.assign({}, window.OryzeImportDemoResult) : x)));
      }, 1700);
    }

    function link(imp, depId) {
      setImports((l) => l.map((x) => (x.id === imp.id ? Object.assign({}, x, { linkedTo: depId }) : x)));
    }

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: compact ? 14 : 18 }}>
        <Dropzone compact={compact} uploading={uploading} onPick={pick} />

        <Card variant="flat" padding="0">
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: compact ? "12px 14px" : "13px 18px", borderBottom: "1.5px solid var(--line-keyline)" }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>Documents importés</div>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-subtle)" }}>{imports.length} fichier{imports.length > 1 ? "s" : ""}</span>
          </div>
          {!compact && (
            <div style={{ display: "grid", gridTemplateColumns: GRIDI, gap: 12, padding: "10px 18px", borderBottom: "1px solid var(--line-divider)", background: "var(--surface-page)" }}>
              {["Document", "Fournisseur", "Montant TTC", "Lecture", "Dépense liée", ""].map((h, i) => (
                <div key={i} style={{ ...impLbl, textAlign: i === 2 ? "right" : "left" }}>{h}</div>
              ))}
            </div>
          )}
          {imports.map((imp, i) => compact
            ? <RowCompact key={imp.id} imp={imp} last={i === imports.length - 1} onOpen={() => setSelId(imp.id)} />
            : <RowWeb key={imp.id} imp={imp} onOpen={() => setSelId(imp.id)} />)}
        </Card>

        <BoundaryNote />

        {compact ? (
          <BottomSheet absolute open={!!sel} onClose={() => setSelId(null)}
            title={sel ? sel.supplier : ""} subtitle={sel ? "Facture " + sel.number + " — import documentaire" : ""}>
            {sel && <DetailBody imp={sel} compact onLink={link} />}
          </BottomSheet>
        ) : (
          <Dialog open={!!sel} onClose={() => setSelId(null)} width={620}
            title={sel ? sel.supplier + " — " + sel.number : ""}
            subtitle="Import documentaire : lecture du fichier, rapport d'écarts, rapprochement">
            {sel && <DetailBody imp={sel} onLink={link} />}
          </Dialog>
        )}
      </div>
    );
  }

  window.OryzeShared = window.OryzeShared || {};
  window.OryzeShared.ImportFournisseurs = ImportFournisseurs;
})();
