// Factures — liste · détail · création · annuaire clients (mobile). window.OryzeApp.FacturesScreen
(function () {
  const { Card, Amount, Tabs, Button, Avatar, SegmentedControl, StatusBadge } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;
  const BADGE = window.OryzeInvoiceBadge;

  function shortDate(inv) {
    if (inv.status === "late") return "Retard " + inv.overdueDays + " j";
    if (inv.status === "draft") return "Brouillon";
    if (inv.status === "paid") return "Payée";
    return "Échéance " + (inv.due || "").slice(0, 5);
  }

  function FacturesScreen({ createSignal }) {
    const ALL = window.OryzeInvoices;
    const [tab, setTab] = React.useState("all");
    const [mode, setMode] = React.useState("list"); // list | detail | create | client
    const [selected, setSelected] = React.useState(null);
    const [selectedClient, setSelectedClient] = React.useState(null);
    const [section, setSection] = React.useState("factures"); // factures | relances | clients

    // top-bar "+" deep-link opens the create view
    React.useEffect(() => { if (createSignal) { setMode("create"); } }, [createSignal]);

    const list = ALL.filter((f) =>
      tab === "all" ? true : tab === "late" ? f.status === "late" : tab === "paid" ? f.status === "paid" : tab === "draft" ? f.status === "draft" : f.status === "due"
    );

    // KPI ↔ onglets ↔ liste : tout dérivé du même jeu. Brouillon exclu de « en attente ».
    const dueList = ALL.filter((f) => f.status === "due");
    const lateList = ALL.filter((f) => f.status === "late");
    const draftList = ALL.filter((f) => f.status === "draft");
    const paidList = ALL.filter((f) => f.status === "paid");
    const dueTotal = dueList.reduce((a, f) => a + window.OryzeInvoiceCalc(f).ht, 0);
    const lateTotal = lateList.reduce((a, f) => a + window.OryzeInvoiceCalc(f).ht, 0);

    if (mode === "detail" && selected) {
      return (
        <div style={{ padding: "16px 16px 28px" }}>
          {React.createElement(window.OryzeShared.InvoiceDetail, { inv: selected, onBack: () => setMode("list") })}
        </div>
      );
    }

    if (mode === "create") {
      return (
        <div style={{ padding: "16px 16px 28px", display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <button onClick={() => setMode("list")} aria-label="Retour" style={{ width: 36, height: 36, flex: "none", display: "inline-flex", alignItems: "center", justifyContent: "center", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-md)", background: "var(--surface-card)", cursor: "pointer", color: "var(--text-body)" }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6" /></svg>
            </button>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>Brouillon — n° attribué à la finalisation</div>
              <div style={{ fontWeight: 700, fontSize: 19, letterSpacing: "-0.02em" }}>Nouvelle facture</div>
            </div>
          </div>
          {React.createElement(window.OryzeShared.InvoiceCreateForm, { compact: true, onCancel: () => setMode("list"), onSubmit: () => setMode("list") })}
        </div>
      );
    }

    // Fiche client — même formulaire conforme 2026 que le web (BT-49, SIREN, pays
    // bloquants à l'enregistrement), en format mobile (compact, in-frame).
    if (mode === "client") {
      return (
        <div style={{ padding: "16px 16px 28px", display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <button onClick={() => setMode("list")} aria-label="Retour" style={{ width: 36, height: 36, flex: "none", display: "inline-flex", alignItems: "center", justifyContent: "center", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-md)", background: "var(--surface-card)", cursor: "pointer", color: "var(--text-body)" }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6" /></svg>
            </button>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>Saisie libre — erreurs bloquantes à l'enregistrement</div>
              <div style={{ fontWeight: 700, fontSize: 19, letterSpacing: "-0.02em" }}>{selectedClient ? "Fiche client" : "Nouveau client"}</div>
            </div>
          </div>
          {React.createElement(window.OryzeShared.ClientForm, { compact: true, client: selectedClient, onBack: () => setMode("list"), onSaved: () => setMode("list") })}
        </div>
      );
    }

    return (
      <div style={{ padding: "16px 16px 24px", display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ fontWeight: 700, fontSize: 20, letterSpacing: "-0.02em" }}>{section === "relances" ? "Relances clients" : section === "clients" ? "Clients" : "Factures"}</div>
          {section === "factures" && <Button size="sm" iconLeft={<Ic.plus size={15} />} onClick={() => setMode("create")}>Nouvelle</Button>}
        </div>

        <SegmentedControl value={section} onChange={setSection} options={[{ value: "factures", label: "Factures" }, { value: "relances", label: "Relances" }, { value: "clients", label: "Clients" }]} style={{ alignSelf: "flex-start" }} />

        {section === "relances"
          ? React.createElement(window.OryzeApp.RelancesScreen, { embedded: true })
          : section === "clients"
          ? React.createElement(window.OryzeShared.ClientsDirectory, {
              compact: true,
              onEdit: (c) => { setSelectedClient(c); setMode("client"); },
              onNew: () => { setSelectedClient(null); setMode("client"); },
            })
          : <FacturesList />}
      </div>
    );

    function FacturesList() {
      return (
      <React.Fragment>

        {/* Outstanding summary */}
        <Card variant="elevated" padding="16px" style={{ display: "flex", gap: 14 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" }}>En attente</div>
            <div style={{ marginTop: 6 }}><Amount value={dueTotal} size="lg" /></div>
            <div style={{ fontSize: 11.5, color: "var(--text-subtle)", marginTop: 2 }}>{dueList.length} à échoir</div>
          </div>
          <div style={{ width: 1, background: "var(--line-divider)" }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" }}>En retard</div>
            <div style={{ marginTop: 6 }}><Amount value={lateTotal} size="lg" tone="negative" /></div>
            <div style={{ fontSize: 11.5, color: "var(--text-subtle)", marginTop: 2 }}>{lateList.length} facture{lateList.length > 1 ? "s" : ""}</div>
          </div>
        </Card>

        <Tabs className="hscroll" value={tab} onChange={setTab} tabs={[
          { value: "all", label: "Toutes" },
          { value: "late", label: "En retard", count: lateList.length },
          { value: "due", label: "À échoir", count: dueList.length },
          { value: "draft", label: "Brouillons", count: draftList.length },
          { value: "paid", label: "Payées" }]} />

        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {list.map((f) => {
            const b = BADGE[f.status] || BADGE.due;
            const ht = window.OryzeInvoiceCalc(f).ht;
            return (
              <Card key={f.id} variant="flat" interactive padding="13px" style={{ display: "flex", alignItems: "center", gap: 12 }}
                onClick={() => { setSelected(f); setMode("detail"); }}>
                <Avatar initials={f.init} tone={f.tone} size={40} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 14.5 }}>{f.who}</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 3 }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-subtle)", fontStyle: f.numberPending ? "italic" : "normal" }}>{f.numberPending ? "n° à la finalisation" : f.id}</span>
                    <span style={{ fontSize: 12, color: f.status === "late" ? "var(--fin-negative)" : "var(--text-muted)" }}>· {shortDate(f)}</span>
                  </div>
                </div>
                <div style={{ textAlign: "right", display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 5 }}>
                  <Amount value={ht} size="md" />
                  <StatusBadge size="sm" status={b.status} label={b.label} />
                </div>
              </Card>
            );
          })}
        </div>

        {lateList.length > 0 && (
          <Button variant="secondary" fullWidth iconLeft={<Ic.send size={16} />} onClick={() => setSection("relances")}>Relancer les factures en retard</Button>
        )}
      </React.Fragment>
      );
    }
  }

  window.OryzeApp = window.OryzeApp || {};
  window.OryzeApp.FacturesScreen = FacturesScreen;
})();
