"use client";

import { useEffect, useState } from "react";
import { Dialog } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import type { TenantDetail } from "@/lib/db/queries/tenants";

const dateFmt = new Intl.DateTimeFormat("fr-FR", {
  day: "2-digit",
  month: "short",
  year: "numeric",
});

const dateTimeFmt = new Intl.DateTimeFormat("fr-FR", {
  day: "2-digit",
  month: "short",
  year: "numeric",
  hour: "2-digit",
  minute: "2-digit",
});

const priceFmt = new Intl.NumberFormat("fr-FR", {
  style: "currency",
  currency: "EUR",
  maximumFractionDigits: 0,
});

const SUB_STATUS_LABEL = {
  trialing: "En essai",
  active: "Actif (paiement OK)",
  past_due: "Paiement en échec",
  canceled: "Annulé",
} as const;

const SUB_STATUS_TONE = {
  trialing: "warning",
  active: "success",
  past_due: "danger",
  canceled: "neutral",
} as const;

function daysBetween(end: Date | null): number | null {
  if (!end) return null;
  const endDate = new Date(end);
  const now = new Date();
  const utcEnd = Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
  const utcNow = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
  return Math.round((utcEnd - utcNow) / (1000 * 60 * 60 * 24));
}

export function TenantDetailModal({
  tenantId,
  onClose,
}: {
  tenantId: number | null;
  onClose: () => void;
}) {
  const open = tenantId !== null;
  return (
    <Dialog
      open={open}
      onOpenChange={(o) => !o && onClose()}
      title="Détail tenant"
      size="xl"
    >
      {tenantId !== null ? (
        // Le `key={tenantId}` provoque un remount complet à chaque tenant
        // ouvert : ça reset state interne (data/error/loading) sans avoir
        // à le faire à la main dans un useEffect (interdit par
        // react-hooks/set-state-in-effect).
        <DetailContent key={tenantId} tenantId={tenantId} />
      ) : null}
    </Dialog>
  );
}

function DetailContent({ tenantId }: { tenantId: number }) {
  const [data, setData] = useState<TenantDetail | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  // Bump pour re-fetcher le détail après une mutation (réactivation sysop) :
  // on relit l'état frais depuis la DB plutôt que de patcher localement.
  const [reloadNonce, setReloadNonce] = useState(0);

  useEffect(() => {
    let cancelled = false;
    fetch(`/api/superadmin/tenants/${tenantId}`)
      .then(async (res) => {
        const body = (await res.json().catch(() => null)) as
          | { success: true; data: TenantDetail }
          | { success: false; message?: string; error?: string }
          | null;
        if (cancelled) return;
        if (!res.ok || !body || body.success === false) {
          setError(
            (body && "message" in body && body.message) ||
              (body && "error" in body && body.error) ||
              `HTTP ${res.status}`,
          );
          return;
        }
        setData(body.data);
      })
      .catch((e) => {
        if (cancelled) return;
        setError(e instanceof Error ? e.message : "Erreur réseau");
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [tenantId, reloadNonce]);

  if (loading) {
    return <p className="text-sm text-muted-foreground">Chargement…</p>;
  }
  if (error) {
    return (
      <div className="rounded-md border border-red-200 bg-danger-subtle px-3 py-2 text-sm text-danger">
        {error}
      </div>
    );
  }
  if (!data) return null;

  return (
    <div className="space-y-5">
      <header className="flex items-baseline justify-between gap-3 border-b border-border pb-3">
        <div>
          <h2 className="text-lg font-semibold">{data.name}</h2>
          <p className="font-mono text-xs text-muted-foreground">{data.slug}</p>
        </div>
        {data.admin_email && (
          <p className="text-xs text-muted-foreground">{data.admin_email}</p>
        )}
      </header>
      <SubscriptionSection detail={data} />
      <PaymentSection detail={data} />
      <ReactivateSection
        detail={data}
        onReactivated={() => setReloadNonce((n) => n + 1)}
      />
      <RgpdExportSection
        detail={data}
        onChanged={() => setReloadNonce((n) => n + 1)}
      />
      <UsageStatsSection detail={data} />
      <PastSubscriptionsSection detail={data} />
      <RecentActivitiesSection detail={data} />
    </div>
  );
}

function SubscriptionSection({ detail }: { detail: TenantDetail }) {
  const sub = detail.active_subscription;
  const trialEnd = sub?.trial_end ?? detail.trial_end_at ?? null;
  const daysLeft = daysBetween(trialEnd);
  const trialBadge =
    sub?.status === "trialing" && trialEnd ? (
      <Badge tone={daysLeft !== null && daysLeft <= 3 ? "danger" : "warning"}>
        {daysLeft !== null && daysLeft >= 0
          ? `${daysLeft} j restant${daysLeft > 1 ? "s" : ""}`
          : "Trial expiré"}
      </Badge>
    ) : null;

  // Résiliation programmée : la sub est encore `active` mais s'annulera à
  // l'échéance (cancel_at_period_end=1, mf #192). Sous-état d'`active`, pas un
  // `canceled` — on le signale sans changer le badge de statut.
  const scheduledCancel =
    sub?.status === "active" && sub.cancel_at_period_end === 1;
  const cancelBadge =
    scheduledCancel ? (
      <Badge tone="warning">
        {sub?.current_period_end
          ? `Résiliation le ${dateFmt.format(new Date(sub.current_period_end))}`
          : "Résiliation programmée"}
      </Badge>
    ) : null;

  return (
    <section>
      <h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
        Abonnement
      </h3>
      <div className="rounded-lg border border-border bg-surface p-4">
        <div className="flex items-center gap-3 flex-wrap">
          <span className="text-lg font-semibold">
            {sub?.plan_name ?? "Aucun plan actif"}
          </span>
          {sub && (
            <Badge tone={SUB_STATUS_TONE[sub.status]}>
              {SUB_STATUS_LABEL[sub.status]}
            </Badge>
          )}
          {trialBadge}
          {cancelBadge}
        </div>

        <dl className="mt-3 grid grid-cols-2 gap-3 text-xs sm:grid-cols-4">
          <Field label="Inscription">
            {dateFmt.format(new Date(detail.created_at))}
          </Field>
          {sub?.plan_monthly_price && (
            <Field label="Tarif mensuel">
              {priceFmt.format(Number(sub.plan_monthly_price))}
            </Field>
          )}
          {sub?.billing_period && (
            <Field label="Facturation">
              {sub.billing_period === "yearly" ? "Annuelle" : "Mensuelle"}
            </Field>
          )}
          {trialEnd && (
            <Field label="Fin de l'essai">
              {dateFmt.format(new Date(trialEnd))}
            </Field>
          )}
          {sub?.current_period_start && (
            <Field label="Période courante">
              {dateFmt.format(new Date(sub.current_period_start))}
              {sub.current_period_end &&
                ` → ${dateFmt.format(new Date(sub.current_period_end))}`}
            </Field>
          )}
          {sub?.canceled_at && (
            <Field label="Annulé le">
              {dateFmt.format(new Date(sub.canceled_at))}
            </Field>
          )}
          <Field label="Onboarding">
            {detail.onboarding_completed ? "Terminé" : "Non terminé"}
          </Field>
        </dl>
      </div>
    </section>
  );
}

function PaymentSection({ detail }: { detail: TenantDetail }) {
  const sub = detail.active_subscription;
  const customerId = sub?.stripe_customer_id ?? detail.stripe_customer_id;
  const subscriptionId =
    sub?.stripe_subscription_id ?? detail.stripe_subscription_id;

  const isPastDue = sub?.status === "past_due";
  const isCanceled = sub?.status === "canceled";

  return (
    <section>
      <h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
        Paiement
      </h3>
      <div
        className={`rounded-lg border p-4 ${
          isPastDue
            ? "border-red-200 bg-danger-subtle"
            : "border-border bg-surface"
        }`}
      >
        {isPastDue && (
          <p className="mb-3 text-sm font-medium text-danger">
            ⚠ Le dernier prélèvement a échoué — facture en retard.
          </p>
        )}
        {isCanceled && (
          <p className="mb-3 text-sm text-muted-foreground">
            Abonnement annulé · réactivable. Aucun prélèvement à venir — le
            tenant peut reprendre son abonnement en self-service.
          </p>
        )}
        {!isPastDue &&
          !isCanceled &&
          sub?.status === "active" &&
          (sub.cancel_at_period_end === 1 ? (
            <p className="mb-3 text-sm text-warning">
              Résiliation programmée : accès conservé jusqu&apos;au{" "}
              {sub.current_period_end
                ? dateFmt.format(new Date(sub.current_period_end))
                : "—"}
              , puis fermeture du compte (3 mois pour exporter). Aucun
              renouvellement ne sera prélevé.
            </p>
          ) : (
            <p className="mb-3 text-sm text-success">
              ✓ Prélèvement à jour. Prochaine échéance{" "}
              {sub.current_period_end
                ? dateFmt.format(new Date(sub.current_period_end))
                : "—"}
              .
            </p>
          ))}
        {sub?.status === "trialing" && (
          <p className="mb-3 text-sm text-warning">
            Aucun prélèvement tant que la période d&apos;essai n&apos;est pas
            terminée.
          </p>
        )}

        <dl className="grid grid-cols-1 gap-3 text-xs sm:grid-cols-2">
          <Field label="Stripe customer">
            <code className="font-mono">{customerId ?? "—"}</code>
          </Field>
          <Field label="Stripe subscription">
            <code className="font-mono">{subscriptionId ?? "—"}</code>
          </Field>
        </dl>
        {customerId && (
          <p className="mt-3 text-[11px] text-muted-foreground">
            Pour voir l&apos;historique des paiements et factures Stripe,
            ouvrir le client dans le dashboard Stripe à partir du customer ID
            ci-dessus.
          </p>
        )}
      </div>
    </section>
  );
}

function UsageStatsSection({ detail }: { detail: TenantDetail }) {
  const items = [
    { label: "Techniciens", value: detail.stats.tech_count },
    { label: "Sites", value: detail.stats.site_count },
    { label: "Machines", value: detail.stats.machine_count },
    { label: "Interventions (total)", value: detail.stats.intervention_count },
    { label: "Interventions (30 j)", value: detail.stats.intervention_30j },
  ];
  return (
    <section>
      <h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
        Usage
      </h3>
      <div className="grid grid-cols-2 gap-2 sm:grid-cols-5">
        {items.map((it) => (
          <div
            key={it.label}
            className="rounded-lg border border-border bg-surface-2 px-3 py-2"
          >
            <p className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
              {it.label}
            </p>
            <p className="mt-0.5 text-lg font-semibold tabular-nums">
              {it.value}
            </p>
          </div>
        ))}
      </div>
    </section>
  );
}

function PastSubscriptionsSection({ detail }: { detail: TenantDetail }) {
  if (detail.past_subscriptions.length === 0) return null;
  return (
    <section>
      <h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
        Anciens abonnements
      </h3>
      <ul className="divide-y divide-border rounded-lg border border-border bg-surface">
        {detail.past_subscriptions.map((s) => (
          <li
            key={s.id}
            className="flex items-center gap-3 px-3 py-2 text-sm"
          >
            <span className="font-medium">{s.plan_name ?? "—"}</span>
            <Badge tone="neutral">{s.status}</Badge>
            <span className="ml-auto text-xs text-muted-foreground tabular-nums">
              {s.canceled_at
                ? `annulé le ${dateFmt.format(new Date(s.canceled_at))}`
                : s.current_period_end
                  ? `fin ${dateFmt.format(new Date(s.current_period_end))}`
                  : "—"}
            </span>
          </li>
        ))}
      </ul>
    </section>
  );
}

function RecentActivitiesSection({ detail }: { detail: TenantDetail }) {
  if (detail.recent_activities.length === 0) return null;
  return (
    <section>
      <h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
        Activité récente
      </h3>
      <ul className="divide-y divide-border rounded-lg border border-border bg-surface max-h-60 overflow-y-auto">
        {detail.recent_activities.map((a) => (
          <li key={a.id} className="px-3 py-2 text-xs">
            <div className="flex items-baseline gap-2">
              <span className="font-mono text-[10px] text-muted-foreground">
                {a.type ?? "?"}
              </span>
              <span className="ml-auto text-muted-foreground tabular-nums">
                {dateTimeFmt.format(new Date(a.created_at))}
              </span>
            </div>
            {a.title && <div className="mt-0.5 font-medium">{a.title}</div>}
            {a.description && (
              <div className="mt-0.5 text-muted-foreground">
                {a.description}
              </div>
            )}
            {a.user_name?.trim() && (
              <div className="mt-0.5 italic text-[10px] text-muted-foreground">
                par {a.user_name}
              </div>
            )}
          </li>
        ))}
      </ul>
    </section>
  );
}

// Statuts depuis lesquels un déblocage manuel sysop a du sens. Le backend
// accepte aussi un trial expiré, mais on n'expose le bouton que sur les états
// franchement « bloqués » côté panel pour éviter les réactivations à la volée.
const REACTIVATABLE: ReadonlySet<TenantDetail["status"]> = new Set([
  "canceled",
  "suspended",
]);

type ReactivateOutcome =
  | { kind: "idle" }
  | { kind: "pending" }
  | { kind: "ok"; message: string }
  | { kind: "error"; message: string };

function ReactivateSection({
  detail,
  onReactivated,
}: {
  detail: TenantDetail;
  onReactivated: () => void;
}) {
  const [confirming, setConfirming] = useState(false);
  const [note, setNote] = useState("");
  const [state, setState] = useState<ReactivateOutcome>({ kind: "idle" });

  if (!REACTIVATABLE.has(detail.status)) return null;

  async function submit() {
    setState({ kind: "pending" });
    try {
      const res = await fetch(
        `/api/superadmin/tenants/${detail.id}/reactivate`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ note: note.trim() || undefined }),
        },
      );
      const body = (await res.json().catch(() => null)) as
        | {
            success: true;
            data: { outcome: "reactivated" | "already_active" };
          }
        | { success: false; message?: string; error?: string }
        | null;

      if (!res.ok || !body || body.success === false) {
        const msg =
          (body && "message" in body && body.message) ||
          (body && "error" in body && body.error) ||
          `HTTP ${res.status}`;
        setState({ kind: "error", message: String(msg) });
        return;
      }

      setState({
        kind: "ok",
        message:
          body.data.outcome === "already_active"
            ? "Ce tenant était déjà actif (aucun changement)."
            : "Tenant réactivé — statut repassé à « actif ».",
      });
      setConfirming(false);
      setNote("");
      onReactivated();
    } catch (e) {
      setState({
        kind: "error",
        message: e instanceof Error ? e.message : "Erreur réseau",
      });
    }
  }

  const pending = state.kind === "pending";

  return (
    <section>
      <h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
        Action sysop
      </h3>
      <div className="rounded-lg border border-amber-200 bg-warning-subtle p-4">
        <p className="text-sm text-foreground">
          Déblocage manuel : repasse ce tenant{" "}
          <strong>{detail.status === "canceled" ? "annulé" : "suspendu"}</strong>{" "}
          en <strong>actif</strong> sans relancer de paiement Stripe. À réserver
          aux cas où le paiement existe (preuve à l&apos;appui) mais que le
          statut est resté bloqué à tort.
        </p>

        {state.kind === "ok" && (
          <p className="mt-3 text-sm font-medium text-success">
            ✓ {state.message}
          </p>
        )}
        {state.kind === "error" && (
          <p className="mt-3 text-sm font-medium text-danger">
            ✗ Échec : {state.message}
          </p>
        )}

        {!confirming ? (
          state.kind !== "ok" && (
            <button
              type="button"
              onClick={() => {
                setState({ kind: "idle" });
                setConfirming(true);
              }}
              className="mt-3 rounded-md border border-amber-300 bg-surface px-3 py-1.5 text-sm font-medium text-foreground hover:bg-surface-2"
            >
              Réactiver ce tenant
            </button>
          )
        ) : (
          <div className="mt-3 space-y-2">
            <label className="block text-xs font-medium text-muted-foreground">
              Justificatif (réf. preuve de paiement, optionnel)
              <textarea
                value={note}
                onChange={(e) => setNote(e.target.value)}
                rows={2}
                disabled={pending}
                placeholder="ex : reçu Stripe ch_xxx / ticket support #123"
                className="mt-1 w-full rounded-md border border-border bg-surface px-2 py-1.5 text-sm text-foreground"
              />
            </label>
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={submit}
                disabled={pending}
                className="rounded-md bg-amber-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-amber-700 disabled:opacity-60"
              >
                {pending ? "Réactivation…" : "Confirmer la réactivation"}
              </button>
              <button
                type="button"
                onClick={() => {
                  setConfirming(false);
                  setNote("");
                  setState({ kind: "idle" });
                }}
                disabled={pending}
                className="rounded-md border border-border px-3 py-1.5 text-sm text-muted-foreground hover:bg-surface-2 disabled:opacity-60"
              >
                Annuler
              </button>
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

// ── Export RGPD (portabilité art. 20) côté sysop ─────────────────────────────
// Cas d'usage : un tenant ne peut pas faire son export self-service → le
// super-admin l'extrait pour lui (mf #151). Le statut est lu en DB directe
// (detail.latest_export_job) ; le déclenchement et le téléchargement passent
// par les endpoints sysop backend.

const EXPORT_STATUS_LABEL = {
  pending: "En file d'attente",
  processing: "Génération en cours",
  completed: "Disponible",
  failed: "Échec",
} as const;

function formatBytes(bytes: number | null): string | null {
  if (bytes == null || bytes <= 0) return null;
  const units = ["o", "Ko", "Mo", "Go"];
  let value = bytes;
  let i = 0;
  while (value >= 1024 && i < units.length - 1) {
    value /= 1024;
    i += 1;
  }
  return `${value.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
}

type ExportTriggerState =
  | { kind: "idle" }
  | { kind: "pending" }
  | { kind: "ok"; message: string }
  | { kind: "error"; message: string };

function RgpdExportSection({
  detail,
  onChanged,
}: {
  detail: TenantDetail;
  onChanged: () => void;
}) {
  const [state, setState] = useState<ExportTriggerState>({ kind: "idle" });
  const job = detail.latest_export_job;

  const now = new Date();
  const isExpired =
    job?.status === "completed" &&
    job.expires_at != null &&
    new Date(job.expires_at) <= now;
  const isDownloadable = job?.status === "completed" && !isExpired;
  const inFlight = job?.status === "pending" || job?.status === "processing";

  async function trigger() {
    setState({ kind: "pending" });
    try {
      const res = await fetch(
        `/api/superadmin/tenants/${detail.id}/rgpd-export`,
        { method: "POST" },
      );
      const body = (await res.json().catch(() => null)) as
        | { success: true; data: { outcome: "created" | "already_running" } }
        | { success: false; message?: string; error?: string }
        | null;

      if (!res.ok || !body || body.success === false) {
        const msg =
          (body && "message" in body && body.message) ||
          (body && "error" in body && body.error) ||
          `HTTP ${res.status}`;
        setState({ kind: "error", message: String(msg) });
        return;
      }

      setState({
        kind: "ok",
        message:
          body.data.outcome === "already_running"
            ? "Un export est déjà en cours pour ce tenant — pas de doublon créé."
            : "Export lancé. Le ZIP sera généré par le worker (sous quelques minutes).",
      });
      // Relit le statut frais en DB (le job apparaît / passe en pending).
      onChanged();
    } catch (e) {
      setState({
        kind: "error",
        message: e instanceof Error ? e.message : "Erreur réseau",
      });
    }
  }

  const pending = state.kind === "pending";
  // Statut « badge » : expiré l'emporte sur completed.
  const badgeTone = isExpired
    ? "neutral"
    : job?.status === "completed"
      ? "success"
      : job?.status === "failed"
        ? "danger"
        : "warning";
  const badgeLabel = isExpired
    ? "Expiré"
    : job
      ? EXPORT_STATUS_LABEL[job.status]
      : null;

  return (
    <section>
      <h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
        Export RGPD (portabilité)
      </h3>
      <div className="rounded-lg border border-border bg-surface p-4">
        <p className="text-sm text-foreground">
          Extraction des données du tenant (art. 20 RGPD) pour son compte —
          utile quand il ne peut pas faire l&apos;export self-service. Le fichier
          est à transmettre au tenant ; il expire automatiquement.
        </p>

        {job ? (
          <div className="mt-3 rounded-md border border-border bg-surface-2 px-3 py-2">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="text-xs font-medium text-muted-foreground">
                Dernier export
              </span>
              {badgeLabel && <Badge tone={badgeTone}>{badgeLabel}</Badge>}
              <span className="ml-auto text-[11px] text-muted-foreground tabular-nums">
                demandé le {dateTimeFmt.format(new Date(job.created_at))}
              </span>
            </div>
            <dl className="mt-2 grid grid-cols-2 gap-2 text-xs sm:grid-cols-3">
              {job.completed_at && (
                <Field label="Généré le">
                  {dateTimeFmt.format(new Date(job.completed_at))}
                </Field>
              )}
              {formatBytes(job.file_size) && (
                <Field label="Taille">{formatBytes(job.file_size)}</Field>
              )}
              {job.expires_at && (
                <Field label="Expire le">
                  {dateTimeFmt.format(new Date(job.expires_at))}
                </Field>
              )}
            </dl>
            {job.status === "failed" && job.error_message && (
              <p className="mt-2 text-xs text-danger">
                Erreur : {job.error_message}
              </p>
            )}
            {isDownloadable && (
              <a
                href={`/api/superadmin/tenants/${detail.id}/rgpd-export/download?job_id=${job.id}`}
                className="mt-3 inline-flex items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-sm font-medium text-background hover:opacity-90"
              >
                Télécharger le ZIP
              </a>
            )}
            {inFlight && (
              <p className="mt-2 text-xs text-muted-foreground">
                Génération en cours — le worker traite la file toutes les
                quelques minutes. Rouvrez le détail pour rafraîchir le statut.
              </p>
            )}
            {isExpired && (
              <p className="mt-2 text-xs text-muted-foreground">
                Ce fichier a expiré et a été purgé. Relancez un export pour en
                obtenir un nouveau.
              </p>
            )}
          </div>
        ) : (
          <p className="mt-3 text-xs text-muted-foreground">
            Aucun export demandé pour ce tenant.
          </p>
        )}

        {state.kind === "ok" && (
          <p className="mt-3 text-sm font-medium text-success">
            ✓ {state.message}
          </p>
        )}
        {state.kind === "error" && (
          <p className="mt-3 text-sm font-medium text-danger">
            ✗ Échec : {state.message}
          </p>
        )}

        <div className="mt-3">
          <button
            type="button"
            onClick={trigger}
            disabled={pending || inFlight}
            className="rounded-md border border-border bg-surface px-3 py-1.5 text-sm font-medium text-foreground hover:bg-surface-2 disabled:opacity-60"
            title={
              inFlight
                ? "Un export est déjà en cours pour ce tenant"
                : undefined
            }
          >
            {pending
              ? "Lancement…"
              : job
                ? "Relancer un export"
                : "Lancer un export"}
          </button>
        </div>
      </div>
    </section>
  );
}

function Field({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <div>
      <dt className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
        {label}
      </dt>
      <dd className="mt-0.5 text-foreground">{children}</dd>
    </div>
  );
}
