// Shared invoice creation form — conforme facturation 2026.
// Série + n° ATTRIBUÉ À LA FINALISATION · mentions 2026 (SIREN client,
// catégorie d'opération, adresse de livraison, option TVA sur les débits) ·
// multi-taux PAR LIGNE · validation bloquante à la finalisation (les brouillons,
// eux, acceptent tout). Machine à états : brouillon → finalisée (immuable).
// Used inside a Dialog (web) and a full-screen view (mobile).
// window.OryzeShared.InvoiceCreateForm
(function () {
  const { Select, Input, Button, Amount, InvoiceLineRow, SegmentedControl, Toggle, StatusBadge } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;
  const CLIENTS = window.OryzeClients;
  const SERIES = window.OryzeInvoiceSeries;

  const lbl = { fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" };
  const err = { fontSize: 12.5, color: "var(--fin-negative)", fontWeight: 600, marginTop: 6 };

  function InvoiceCreateForm({ onCancel, onSubmit, compact = false }) {
    const [series, setSeries] = React.useState("fac");
    const [client, setClient] = React.useState("dupont");
    const [due, setDue] = React.useState("28/04/2026");
    const [category, setCategory] = React.useState(null); // biens | services | mixte — REQUIS à la finalisation
    const [deliveryOn, setDeliveryOn] = React.useState(false);
    const [delivery, setDelivery] = React.useState("");
    const [vatOnDebits, setVatOnDebits] = React.useState(false);
    // Mentions légales (BR-FR-05) — auto-remplies, surcharge possible
    const [mentionsOpen, setMentionsOpen] = React.useState(false);
    const [mentions, setMentions] = React.useState({
      PMT: window.OryzeMentions.PMT.text, PMD: window.OryzeMentions.PMD.text, AAB: window.OryzeMentions.AAB.text,
    });
    const [lines, setLines] = React.useState([
      { designation: "Atelier design system", qty: "1", unitPrice: "1200", tvaRate: 0.2 },
      { designation: "Forfait intégration", qty: "2", unitPrice: "260", tvaRate: 0.2 },
    ]);
    const [errors, setErrors] = React.useState({});
    const [phase, setPhase] = React.useState("edit"); // edit | finalizing | done

    const cl = CLIENTS.find((c) => c.value === client);
    const serie = SERIES.find((s) => s.value === series);
    const assigned = serie.prefix + "-" + serie.next;

    // Totaux par taux
    const byRate = {};
    let ht = 0;
    lines.forEach((l) => {
      const base = (parseFloat(l.qty) || 0) * (parseFloat(l.unitPrice) || 0);
      ht += base;
      byRate[l.tvaRate] = (byRate[l.tvaRate] || 0) + base;
    });
    const rates = Object.keys(byRate).map(Number).sort((a, b) => b - a).map((r) => ({ rate: r, tva: byRate[r] * r }));
    const tva = rates.reduce((a, x) => a + x.tva, 0);

    const update = (i, patch) => setLines((ls) => ls.map((l, j) => (j === i ? { ...l, ...patch } : l)));
    const remove = (i) => setLines((ls) => ls.filter((_, j) => j !== i));
    const add = () => setLines((ls) => [...ls, { designation: "", qty: "1", unitPrice: "", tvaRate: 0.2 }]);

    // Validation — BLOQUANTE à la finalisation seulement.
    function validate() {
      const e = {};
      if (!category) e.category = "Choisissez la catégorie d'opération — mention obligatoire (2026).";
      if (!lines.length || lines.some((l) => !l.designation.trim() || !(parseFloat(l.unitPrice) > 0) || !(parseFloat(l.qty) > 0)))
        e.lines = "Chaque ligne doit avoir une désignation, une quantité et un prix.";
      if (deliveryOn && !delivery.trim()) e.delivery = "Renseignez l'adresse de livraison, ou désactivez l'option.";
      if (!cl.email) e.email = "Adresse électronique du client manquante — requise (2026). Complétez la fiche client.";
      if (Object.values(mentions).some((t) => !t.trim())) e.mentions = "Les trois mentions légales doivent être renseignées.";
      return e;
    }

    function finalize() {
      const e = validate();
      setErrors(e);
      if (Object.keys(e).length) return;
      setPhase("finalizing");
      setTimeout(() => {
        setPhase("done");
        setTimeout(() => onSubmit && onSubmit({ number: assigned }), 1600);
      }, 900);
    }

    if (phase === "done") {
      return (
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14, padding: "36px 0 28px", textAlign: "center" }}>
          <StatusBadge status="finalized" />
          <div style={{ fontWeight: 700, fontSize: 20, letterSpacing: "-0.02em" }}>Facture <span style={{ fontFamily: "var(--font-mono)" }}>{assigned}</span> finalisée</div>
          <div style={{ fontSize: 13.5, color: "var(--text-muted)", maxWidth: 340, lineHeight: 1.5 }}>
            Numéro attribué dans la série {serie.prefix}-2026. Le document est scellé — toute correction passera par un avoir.
          </div>
        </div>
      );
    }

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {/* Série + numéro à la finalisation (compact : empilés) */}
        <div style={{ display: "grid", gridTemplateColumns: compact ? "1fr" : "1fr 1fr", gap: 14 }}>
          <Select label="Série" value={series} onChange={(e) => setSeries(e.target.value)} options={SERIES} />
          <div>
            <div style={{ ...lbl, marginBottom: 7 }}>Numéro</div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, height: 42, padding: "0 12px", border: "var(--border-thin) dashed var(--line-keyline)", borderRadius: "var(--radius-md)", background: "var(--surface-sunken)", boxSizing: "border-box", overflow: "hidden" }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 13.5, color: "var(--text-muted)", flex: "none" }}>{serie.prefix}-••••</span>
              <span style={{ fontSize: 11.5, color: "var(--text-subtle)", minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>attribué à la finalisation</span>
            </div>
          </div>
        </div>

        {/* Client + échéance + identité (mention SIREN) */}
        <div>
          <div style={{ display: "grid", gridTemplateColumns: compact ? "1fr 130px" : "1fr 160px", gap: 14 }}>
            <Select label="Client" value={client} onChange={(e) => setClient(e.target.value)} options={CLIENTS} style={{ minWidth: 0 }} />
            <Input label="Échéance" value={due} onChange={(e) => setDue(e.target.value)} mono />
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: "4px 18px", marginTop: 8, padding: "9px 12px", background: "var(--surface-sunken)", border: "var(--border-hair) solid var(--line-divider)", borderRadius: "var(--radius-md)", fontSize: 12.5, color: "var(--text-muted)" }}>
            <span>SIREN <span style={{ fontFamily: "var(--font-mono)", color: "var(--text-body)" }}>{cl.siren}</span></span>
            <span style={{ minWidth: 0 }}>{cl.address}</span>
            <span style={{ minWidth: 0 }}>{cl.email
              ? <span style={{ fontFamily: "var(--font-mono)", color: "var(--text-body)" }}>{cl.email}</span>
              : <span style={{ color: "var(--fin-negative)", fontWeight: 600 }}>courriel manquant — requis à la finalisation</span>}</span>
          </div>
          {errors.email && <div style={err}>{errors.email}</div>}
        </div>

        {/* Catégorie d'opération (mention 2026) */}
        <div>
          <div style={{ ...lbl, marginBottom: 7 }}>Catégorie d'opération <span style={{ color: "var(--fin-negative)" }}>*</span></div>
          <SegmentedControl value={category} onChange={setCategory}
            options={[{ value: "biens", label: "Biens" }, { value: "services", label: "Services" }, { value: "mixte", label: "Mixte" }]} />
          {errors.category && <div style={err}>{errors.category}</div>}
        </div>

        {/* Options 2026 : livraison + débits */}
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>Adresse de livraison différente</div>
              <div style={{ fontSize: 12, color: "var(--text-subtle)" }}>Mention requise si les biens sont livrés ailleurs qu'à l'adresse de facturation</div>
            </div>
            <Toggle checked={deliveryOn} onChange={setDeliveryOn} aria-label="Adresse de livraison différente" />
          </div>
          {deliveryOn && (
            <div>
              <Input placeholder="Adresse de livraison" value={delivery} onChange={(e) => setDelivery(e.target.value)} />
              {errors.delivery && <div style={err}>{errors.delivery}</div>}
            </div>
          )}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>TVA d'après les débits</div>
              <div style={{ fontSize: 12, color: "var(--text-subtle)" }}>Si vous avez opté pour l'exigibilité à la facturation (services)</div>
            </div>
            <Toggle checked={vatOnDebits} onChange={setVatOnDebits} aria-label="TVA d'après les débits" />
          </div>
        </div>

        {/* Mentions légales (BR-FR-05) — auto-remplies, éditables en surcharge */}
        <div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>Mentions légales</div>
              <div style={{ fontSize: 12, color: "var(--text-subtle)" }}>Recouvrement · pénalités · escompte — pré-remplies, toujours présentes sur la facture</div>
            </div>
            <Button size="sm" variant="ghost" onClick={() => setMentionsOpen((o) => !o)} style={{ flex: "none" }}>{mentionsOpen ? "Replier" : "Modifier"}</Button>
          </div>
          {mentionsOpen ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 10 }}>
              {["PMT", "PMD", "AAB"].map((k) => (
                <Input key={k} label={window.OryzeMentions[k].label + " (" + k + ")"} value={mentions[k]}
                  onChange={(e) => setMentions((m) => ({ ...m, [k]: e.target.value }))} />
              ))}
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 5, marginTop: 8, padding: "9px 12px", background: "var(--surface-sunken)", border: "var(--border-hair) solid var(--line-divider)", borderRadius: "var(--radius-md)" }}>
              {["PMT", "PMD", "AAB"].map((k) => (
                <div key={k} style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, fontWeight: 600, letterSpacing: "0.08em", color: "var(--text-subtle)", border: "1px solid var(--line-divider)", borderRadius: 4, padding: "1px 5px", flex: "none" }}>{k}</span>
                  <span style={{ fontSize: 11.5, color: "var(--text-muted)", lineHeight: 1.45, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{mentions[k]}</span>
                </div>
              ))}
            </div>
          )}
          {errors.mentions && <div style={err}>{errors.mentions}</div>}
        </div>

        {/* Lignes — taux PAR LIGNE (compact : empilées pour le mobile) */}
        <div>
          {compact ? (
            <div style={{ ...lbl, marginBottom: 8 }}>Lignes</div>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) 48px 86px 68px 92px 32px", gap: 8, marginBottom: 8 }}>
              {["Désignation", "Qté", "PU HT", "TVA", "Total", ""].map((h, i) => (
                <div key={i} style={{ ...lbl, textAlign: i === 0 || i === 3 ? "left" : "right" }}>{h}</div>
              ))}
            </div>
          )}
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {lines.map((l, i) => compact ? (
              <CompactLine key={i} l={l} onChange={(patch) => update(i, patch)} onRemove={() => remove(i)} />
            ) : (
              <InvoiceLineRow key={i} editable designation={l.designation} qty={l.qty} unitPrice={l.unitPrice} tvaRate={l.tvaRate}
                onChange={(patch) => update(i, patch)} onRemove={() => remove(i)} />
            ))}
          </div>
          {errors.lines && <div style={err}>{errors.lines}</div>}
          <button onClick={add} style={{ marginTop: 12, display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 12px", border: "var(--border-thin) dashed var(--line-keyline)", borderRadius: "var(--radius-md)", background: "transparent", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, color: "var(--text-body)" }}>
            <Ic.plus size={15} /> Ajouter une ligne
          </button>
        </div>

        {/* Totaux — ventilés par taux */}
        <div style={{ display: "flex", flexDirection: "column", gap: 7, marginLeft: "auto", width: 250, paddingTop: 14, borderTop: "var(--border-thin) solid var(--line-keyline)" }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}><span style={{ fontSize: 13, color: "var(--text-muted)", whiteSpace: "nowrap" }}>Total HT</span><Amount value={ht} size="sm" weight={500} /></div>
          {rates.filter((r) => r.tva > 0 || rates.length > 1).map((r) => (
            <div key={r.rate} style={{ display: "flex", justifyContent: "space-between" }}>
              <span style={{ fontSize: 13, color: "var(--text-muted)", whiteSpace: "nowrap" }}>TVA {(r.rate * 100).toLocaleString("fr-FR")} %</span>
              <Amount value={r.tva} size="sm" weight={500} tone="muted" />
            </div>
          ))}
          <div style={{ height: 1, background: "var(--line-keyline)", margin: "3px 0" }} />
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}><span style={{ fontWeight: 700, fontSize: 14, whiteSpace: "nowrap" }}>Total TTC</span><Amount value={ht + tva} size="lg" /></div>
        </div>

        {/* Actions — brouillon libre / finalisation validée */}
        {compact ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 8, paddingTop: 4 }}>
            <Button size="md" fullWidth loading={phase === "finalizing"} iconLeft={<Ic.check size={15} />} onClick={finalize}>Finaliser</Button>
            <Button variant="secondary" size="md" fullWidth iconLeft={<Ic.file size={15} />} onClick={() => onSubmit && onSubmit({ draft: true })}>Enregistrer le brouillon</Button>
            <Button variant="ghost" size="md" fullWidth onClick={onCancel}>Annuler</Button>
          </div>
        ) : (
          <div style={{ display: "flex", gap: 10, alignItems: "center", paddingTop: 4 }}>
            <Button variant="ghost" size="md" onClick={onCancel} style={{ flex: "none" }}>Annuler</Button>
            <div style={{ flex: 1 }} />
            <Button variant="secondary" size="md" iconLeft={<Ic.file size={15} />} onClick={() => onSubmit && onSubmit({ draft: true })}>Enregistrer le brouillon</Button>
            <Button size="md" loading={phase === "finalizing"} iconLeft={<Ic.check size={15} />} onClick={finalize}>Finaliser</Button>
          </div>
        )}
        <div style={{ fontSize: 11.5, color: "var(--text-subtle)", textAlign: compact ? "center" : "right", marginTop: compact ? 0 : -10 }}>
          La finalisation attribue le n° {assigned} et scelle le document.
        </div>
      </div>
    );
  }

  // Ligne compacte (mobile) — empilée : désignation pleine largeur, puis
  // qté / PU / TVA, total à droite. Mêmes données que InvoiceLineRow.
  function CompactLine({ l, onChange, onRemove }) {
    const total = (parseFloat(l.qty) || 0) * (parseFloat(l.unitPrice) || 0);
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 8, padding: "10px 12px", border: "var(--border-thin) solid var(--line-hairline)", borderRadius: "var(--radius-md)", background: "var(--surface-card)" }}>
        <Input aria-label="Désignation" placeholder="Désignation" value={l.designation} onChange={(e) => onChange({ designation: e.target.value })} />
        <div style={{ display: "grid", gridTemplateColumns: "minmax(40px,52px) minmax(0,1fr) minmax(0,92px)", gap: 8, minWidth: 0 }}>
          <Input aria-label="Quantité" value={l.qty} mono onChange={(e) => onChange({ qty: e.target.value })} style={{ minWidth: 0 }} />
          <Input aria-label="Prix unitaire HT" value={l.unitPrice} mono suffix="€" onChange={(e) => onChange({ unitPrice: e.target.value })} style={{ minWidth: 0 }} />
          <Select aria-label="Taux de TVA" value={String(l.tvaRate)} onChange={(e) => onChange({ tvaRate: parseFloat(e.target.value) })} style={{ minWidth: 0 }}
            options={[{ value: "0.2", label: "20 %" }, { value: "0.1", label: "10 %" }, { value: "0.055", label: "5,5 %" }, { value: "0", label: "0 %" }]} />
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
          <button onClick={onRemove} style={{ border: "none", background: "none", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 600, color: "var(--text-subtle)", padding: 0 }}>Supprimer</button>
          <Amount value={total} size="sm" />
        </div>
      </div>
    );
  }

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