// Dashboard — TVA. 3 régimes (réel simplifié / réel normal / franchise),
// drill-down justificatifs (fiabilité par pièce), export, disclaimer :
// Oryze PRÉPARE la déclaration, il ne la dépose jamais.
// window.OryzeDash.TvaView
(function () {
  const { Card, Amount, Tag, Button, ProgressRing, StatusTimeline, InsightCard, Select, Dialog, EmptyState } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;

  const lbl = { fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" };

  function Disclaimer() {
    const t = window.OryzeTVA.trace;
    return (
      <Card variant="flat" padding="16px 18px" background="var(--surface-sunken)">
        <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flex: "none", marginTop: 2 }}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10"/></svg>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13.5, color: "var(--text-body)", lineHeight: 1.5 }}>
              <strong>Oryze prépare votre déclaration — il ne la dépose jamais.</strong> Vérifiez ces montants,
              puis reportez-les vous-même sur impots.gouv.fr. Vous restez seul déclarant.
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: "4px 14px", marginTop: 8, fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-subtle)" }}>
              <span>Préparation · règle {t.rule}</span><span>calculée le {t.computedAt}</span><span>données → {t.dataUntil}</span>
            </div>
          </div>
        </div>
      </Card>
    );
  }

  // Drill-down — justificatifs d'une somme (collectée ou déductible)
  function DetailDialog({ open, onClose, title, rows, total }) {
    return (
      <Dialog open={open} onClose={onClose} width={640} title={title} subtitle="Chaque montant est adossé à une pièce — fiabilité vérifiée ligne à ligne">
        {open && (
          <div>
            <div style={{ display: "grid", gridTemplateColumns: "76px minmax(0,1fr) 56px 96px 96px 104px", gap: 10, padding: "9px 0", borderBottom: "1.5px solid var(--line-keyline)" }}>
              {["Réf.", "Libellé", "Date", "Base HT", "TVA", "Fiabilité"].map((h, i) => (
                <div key={i} style={{ ...lbl, textAlign: i === 3 || i === 4 ? "right" : "left" }}>{h}</div>
              ))}
            </div>
            {rows.map((r, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "76px minmax(0,1fr) 56px 96px 96px 104px", gap: 10, padding: "10px 0", borderBottom: "1px solid var(--line-divider)", alignItems: "center", opacity: r.aggregate ? 0.75 : 1 }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>{r.ref}</div>
                <div style={{ fontSize: 13, fontWeight: r.aggregate ? 400 : 600, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  {r.label}
                  {r.note && <span style={{ color: "var(--fin-negative)", fontWeight: 600 }}> · {r.note}</span>}
                </div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-subtle)" }}>{r.date}</div>
                <div style={{ textAlign: "right" }}><Amount value={r.base} size="sm" weight={400} /></div>
                <div style={{ textAlign: "right" }}><Amount value={r.tva} size="sm" /></div>
                <div>{r.ok ? <Tag tone="mint" dot>Vérifié</Tag> : <Tag tone="butter" dot>À confirmer</Tag>}</div>
              </div>
            ))}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 13 }}>
              <Button size="sm" variant="ghost" iconLeft={<Ic.download size={15} />}>Exporter le détail (CSV)</Button>
              <div style={{ display: "flex", gap: 12, alignItems: "baseline" }}>
                <span style={{ fontWeight: 700, fontSize: 13.5 }}>Total</span>
                <Amount value={total} size="lg" />
              </div>
            </div>
          </div>
        )}
      </Dialog>
    );
  }

  function TvaView({ demoState = "normal" }) {
    const TVA = window.OryzeTVA;
    const [regime, setRegime] = React.useState("simplifie");
    const [drill, setDrill] = React.useState(null); // "collected" | "deductible" | null
    const c = TVA.regimes[regime];

    // ---- États démo : chargement / vide / erreur (patterns guidelines/states.html) ----
    const { ErrorState, SkelListCard, SkelBlockCard } = window.OryzeShared;
    if (demoState === "empty") {
      return (
        <EmptyState framed title="Pas encore de TVA à préparer"
          description="Dès vos premières factures et dépenses, on calcule la TVA collectée, déductible et nette — et on met la provision de côté pour vous."
          action={<Button size="sm" variant="secondary">Configurer le régime de TVA</Button>} />
      );
    }
    if (demoState === "loading") {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 16 }}>
            <SkelBlockCard height={150} />
            <SkelBlockCard height={150} />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <SkelBlockCard height={110} />
            <SkelBlockCard height={110} />
          </div>
          <SkelListCard rows={3} avatar={false} />
        </div>
      );
    }
    if (demoState === "error") {
      return <ErrorState what="Impossible de charger votre TVA" endpoint="GET /tva/preparation · 503 · réf. d6e0-…" />;
    }

    const header = (
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16 }}>
        <Select label="Régime de TVA" value={regime} onChange={(e) => setRegime(e.target.value)} options={TVA.regimeOptions} style={{ width: 300 }} />
        {c && <Button size="sm" variant="ghost" iconLeft={<Ic.download size={15} />}>Exporter la préparation (CSV)</Button>}
      </div>
    );

    // ---- Franchise en base : pas de TVA ----
    if (!c) {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          {header}
          <EmptyState framed title="Franchise en base — pas de TVA à déclarer"
            description="Vous facturez sans TVA (art. 293 B du CGI). Oryze surveille votre chiffre d'affaires et vous préviendra à l'approche du seuil de bascule."
            action={<Button size="sm" variant="secondary">Voir le suivi du seuil</Button>} />
          <Disclaimer />
        </div>
      );
    }

    const pct = Math.round((c.provisioned / c.net) * 100);
    const toConfirm = TVA.deductibleDetail.filter((r) => !r.ok).length;

    const clickableRow = (key, label, value, tone) => (
      <button onClick={() => setDrill(key)} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, width: "100%", padding: 0, background: "none", border: "none", cursor: "pointer", fontFamily: "inherit" }}>
        <span style={{ fontSize: 13, color: "var(--text-muted)", whiteSpace: "nowrap", display: "inline-flex", alignItems: "center", gap: 6 }}>
          {label}
          <Ic.chevronRight size={13} style={{ color: "var(--text-subtle)" }} />
        </span>
        <Amount value={value} size="sm" weight={500} tone={tone} />
      </button>
    );

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {header}

        <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 16 }}>
          {/* Provision hero */}
          <Card variant="hero" padding="22px" style={{ minWidth: 0 }}>
            <div style={{ ...lbl, marginBottom: 14 }}>À provisionner · {c.period} · {c.months}</div>
            <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
              <ProgressRing size={100} thickness={20} rounded={false} color="var(--fin-positive)" trackColor="var(--oryze-ink-10)" value={pct} label={pct + "%"} sublabel="mis de côté" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <Amount value={c.net} size="lg" />
                <div style={{ display: "flex", flexWrap: "wrap", gap: "10px 16px", marginTop: 14 }}>
                  <div style={{ minWidth: 0 }}><div style={lbl}>De côté le {c.provisionedDate}</div><div style={{ marginTop: 4 }}><Amount value={c.provisioned} size="md" /></div></div>
                  <div style={{ minWidth: 0 }}><div style={lbl}>État</div><div style={{ marginTop: 6, display: "flex", gap: 6, flexWrap: "wrap" }}>
                    <Tag tone="paid" dot>Provision complète</Tag>
                    {toConfirm > 0 && <button onClick={() => setDrill("deductible")} style={{ padding: 0, border: "none", background: "none", cursor: "pointer" }}><Tag tone="butter" dot>{toConfirm} pièce à confirmer</Tag></button>}
                  </div></div>
                </div>
                <Button size="sm" variant="secondary" iconLeft={<Ic.check size={15} />} style={{ marginTop: 16 }}>Automatiser les prochains</Button>
              </div>
            </div>
          </Card>

          {/* Échéance + barème → drill-down */}
          <Card variant="flat" padding="20px" style={{ minWidth: 0 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 }}>
              <div>
                <div style={lbl}>Échéance · déclaration</div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 20, fontWeight: 600, marginTop: 5 }}>{c.dueDate}</div>
              </div>
              <Tag tone="butter" dot>Dans {c.daysLeft} j</Tag>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 9, paddingTop: 14, borderTop: "1px solid var(--line-divider)" }}>
              {clickableRow("collected", "TVA collectée", c.collected)}
              {clickableRow("deductible", "TVA déductible", -c.deductible, "muted")}
              <div style={{ height: 1, background: "var(--line-keyline)", margin: "2px 0" }} />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <span style={{ fontWeight: 700, fontSize: 14, whiteSpace: "nowrap" }}>TVA nette à payer</span>
                <Amount value={c.net} size="lg" />
              </div>
              <div style={{ fontSize: 11.5, color: "var(--text-subtle)" }}>Cliquez une ligne pour voir les justificatifs.</div>
            </div>
          </Card>
        </div>

        {/* Anticipation + timeline */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <InsightCard capability="anticipation" title="TVA provisionnée ce mois"
            trace={{ rule: "provision-tva-v1.2", computedAt: "15/04/2026 07:30", dataUntil: "14/04" }}
            primaryAction={<Button size="sm" variant="secondary" iconLeft={<Ic.check size={15} />} disabled>Mise de côté</Button>}
            secondaryAction={<Button size="sm" variant="ghost">Automatiser les prochains</Button>}>
            On a mis 2 480 € de côté le 14/04 pour la TVA du trimestre. On peut le faire automatiquement chaque mois pour éviter la surprise à l'échéance.
          </InsightCard>
          <Card variant="flat" padding="20px">
            <div style={{ ...lbl, marginBottom: 14 }}>Suivi de la période</div>
            <StatusTimeline steps={c.timeline} />
          </Card>
        </div>

        {/* Historique */}
        <Card variant="flat" padding="0">
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 18px", borderBottom: "1.5px solid var(--line-keyline)" }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{c.historyLabel}</div>
            <Button size="sm" variant="ghost" iconRight={<Ic.chevronRight size={15} />}>Tout l'historique</Button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr 1fr 1fr 100px", gap: 12, padding: "10px 18px", borderBottom: "1px solid var(--line-divider)", background: "var(--surface-page)" }}>
            {["Période", "Dates", "TVA nette", "Payée le", "Statut"].map((h, i) => (
              <div key={i} style={{ ...lbl, textAlign: i === 2 ? "right" : "left" }}>{h}</div>
            ))}
          </div>
          {c.history.map((h) => (
            <div key={h.period} style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr 1fr 1fr 100px", gap: 12, padding: "12px 18px", borderBottom: "1px solid var(--line-divider)", alignItems: "center" }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{h.period}</div>
              <div style={{ fontSize: 13, color: "var(--text-muted)" }}>{h.months}</div>
              <div style={{ textAlign: "right" }}><Amount value={h.net} size="md" /></div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-muted)" }}>{h.paidDate}</div>
              <div><Tag tone="paid" dot>Payée</Tag></div>
            </div>
          ))}
        </Card>

        <Disclaimer />

        <DetailDialog open={drill === "collected"} onClose={() => setDrill(null)}
          title={`TVA collectée — ${c.period}`} rows={TVA.collectedDetail} total={c.collected} />
        <DetailDialog open={drill === "deductible"} onClose={() => setDrill(null)}
          title={`TVA déductible — ${c.period}`} rows={TVA.deductibleDetail} total={c.deductible} />
      </div>
    );
  }

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