// @File: src/pages/ClientBizmail.tsx
// @Desc: Client-facing Bizmail360 subscriptions page. Lets the logged-in
//        user see their active mail plans, order a new one, and drill
//        into mailbox / alias management for each active subscription.
import { useCallback, useEffect, useMemo, useState } from "react";
import {
  Inbox,
  Loader2,
  AlertTriangle,
  PlusCircle,
  ShieldCheck,
  Mail,
  Users as UsersIcon,
  HardDrive,
  CheckCircle2,
  Clock,
  PauseCircle,
  XCircle,
  Rocket,
  Trash2,
  KeyRound,
  RefreshCw,
} from "lucide-react";
import { toast } from "sonner";

import {
  activateMySubscription,
  cancelMySubscription,
  createAlias,
  createMailbox,
  deleteAlias,
  deleteMailbox,
  fetchAliases,
  fetchMailboxes,
  fetchMySubscriptions,
  fetchPublicPlans,
  fetchUsage,
  orderSubscription,
  resetMailboxPassword,
  type BizmailAlias,
  type BizmailMailbox,
  type BizmailPlan,
  type BizmailSubscription,
  type BizmailUsage,
} from "@/lib/bizmailApi";

// ---------- helpers ----------
function statusBadge(status: BizmailSubscription["status"]): {
  pill: string;
  label: string;
  Icon: typeof CheckCircle2;
} {
  switch (status) {
    case "active":
      return { pill: "bg-emerald-500/15 text-emerald-300", label: "Active", Icon: CheckCircle2 };
    case "pending":
      return { pill: "bg-amber-500/20 text-amber-300", label: "Pending", Icon: Clock };
    case "suspended":
      return { pill: "bg-rose-500/20 text-rose-300", label: "Suspended", Icon: PauseCircle };
    case "cancelled":
      return { pill: "bg-slate-500/20 text-slate-300", label: "Cancelled", Icon: XCircle };
  }
}

function formatMb(mb: number): string {
  if (mb >= 1024) {
    return `${(mb / 1024).toFixed(1)} GB`;
  }
  return `${mb} MB`;
}

// ---------- subscription detail panel ----------
function SubscriptionDetail({
  subscription,
  onChanged,
}: {
  subscription: BizmailSubscription;
  onChanged: (updated: BizmailSubscription) => void;
}) {
  const [mailboxes, setMailboxes] = useState<BizmailMailbox[]>([]);
  const [aliases, setAliases] = useState<BizmailAlias[]>([]);
  const [usage, setUsage] = useState<BizmailUsage | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const [newMailboxUser, setNewMailboxUser] = useState("");
  const [newMailboxPwd, setNewMailboxPwd] = useState("");
  const [newMailboxName, setNewMailboxName] = useState("");

  const [newAliasName, setNewAliasName] = useState("");
  const [newAliasTargets, setNewAliasTargets] = useState("");

  const refresh = useCallback(async () => {
    if (subscription.status !== "active") {
      setLoading(false);
      setMailboxes([]);
      setAliases([]);
      setUsage(null);
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const [mbs, als, usg] = await Promise.all([
        fetchMailboxes(subscription.id),
        fetchAliases(subscription.id),
        fetchUsage(subscription.id),
      ]);
      setMailboxes(mbs);
      setAliases(als);
      setUsage(usg);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load mailbox data");
    } finally {
      setLoading(false);
    }
  }, [subscription.id, subscription.status]);

  useEffect(() => {
    void refresh();
  }, [refresh]);

  const handleAddMailbox = async () => {
    if (!newMailboxUser.trim() || !newMailboxPwd.trim()) {
      toast.error("Username and password are required");
      return;
    }
    setBusy(true);
    try {
      const created = await createMailbox(subscription.id, {
        username: newMailboxUser.trim(),
        password: newMailboxPwd,
        display_name: newMailboxName.trim() || undefined,
      });
      setMailboxes((prev) => [...prev, created]);
      setNewMailboxUser("");
      setNewMailboxPwd("");
      setNewMailboxName("");
      toast.success("Mailbox created");
      void refresh();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Failed to create mailbox");
    } finally {
      setBusy(false);
    }
  };

  const handleResetPassword = async (username: string) => {
    const pwd = prompt(`Enter new password for ${username}@${subscription.domain_name}`);
    if (!pwd) return;
    try {
      await resetMailboxPassword(subscription.id, username, pwd);
      toast.success("Password updated");
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Reset failed");
    }
  };

  const handleDeleteMailbox = async (username: string) => {
    if (!confirm(`Delete mailbox ${username}@${subscription.domain_name}? This cannot be undone.`))
      return;
    try {
      await deleteMailbox(subscription.id, username);
      setMailboxes((prev) => prev.filter((m) => m.username !== username));
      toast.success("Mailbox deleted");
      void refresh();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Delete failed");
    }
  };

  const handleAddAlias = async () => {
    if (!newAliasName.trim() || !newAliasTargets.trim()) {
      toast.error("Alias name and at least one target are required");
      return;
    }
    const targets = newAliasTargets
      .split(/[,\n]/)
      .map((t) => t.trim())
      .filter(Boolean);
    if (targets.length === 0) {
      toast.error("Provide at least one target address");
      return;
    }
    setBusy(true);
    try {
      const created = await createAlias(subscription.id, {
        alias_name: newAliasName.trim(),
        targets,
      });
      setAliases((prev) => [...prev, created]);
      setNewAliasName("");
      setNewAliasTargets("");
      toast.success("Alias created");
      void refresh();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Failed to create alias");
    } finally {
      setBusy(false);
    }
  };

  const handleDeleteAlias = async (name: string) => {
    if (!confirm(`Delete alias ${name}@${subscription.domain_name}?`)) return;
    try {
      await deleteAlias(subscription.id, name);
      setAliases((prev) => prev.filter((a) => a.name !== name));
      toast.success("Alias deleted");
      void refresh();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Delete failed");
    }
  };

  const handleActivate = async () => {
    setBusy(true);
    try {
      const result = await activateMySubscription(subscription.id);
      onChanged(result.subscription);
      if (result.primary_password) {
        toast.success(
          `Mailbox provisioned: ${result.primary_mailbox}. Temporary password: ${result.primary_password}`,
          { duration: 12000 }
        );
      } else {
        toast.success("Subscription activated");
      }
      void refresh();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Activation failed");
    } finally {
      setBusy(false);
    }
  };

  const handleCancel = async () => {
    if (!confirm(`Cancel mail service for ${subscription.domain_name}?`)) return;
    setBusy(true);
    try {
      const res = await cancelMySubscription(subscription.id);
      onChanged(res.subscription);
      toast.success(res.message);
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Cancel failed");
    } finally {
      setBusy(false);
    }
  };

  if (subscription.status === "cancelled") {
    return (
      <div className="rounded-2xl border border-slate-700 bg-slate-900/60 p-6 text-slate-300 text-sm">
        This subscription has been cancelled.
      </div>
    );
  }

  if (subscription.status === "pending") {
    return (
      <div className="rounded-2xl border border-amber-500/30 bg-amber-500/5 p-6 space-y-4">
        <div className="flex items-center gap-2 text-amber-300 font-semibold">
          <Clock className="w-5 h-5" /> Pending activation
        </div>
        <p className="text-sm text-slate-300">
          Point the MX records of <span className="font-mono">{subscription.domain_name}</span> to
          our SmarterMail servers, then click <b>Activate</b> to provision your mailbox.
        </p>
        <div className="flex gap-2">
          <button
            onClick={() => void handleActivate()}
            disabled={busy}
            className="px-4 py-2 rounded-lg bg-emerald-500 text-white text-sm font-semibold hover:bg-emerald-600 transition disabled:opacity-60 inline-flex items-center gap-2"
          >
            {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Rocket className="w-4 h-4" />}
            Activate now
          </button>
          <button
            onClick={() => void handleCancel()}
            disabled={busy}
            className="px-4 py-2 rounded-lg border border-rose-400/40 text-rose-300 text-sm font-semibold hover:bg-rose-500/10 transition disabled:opacity-60"
          >
            Cancel
          </button>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="rounded-2xl border border-slate-700 bg-slate-900/60 p-6 text-slate-300 text-sm inline-flex items-center gap-2">
        <Loader2 className="w-4 h-4 animate-spin" /> Loading mailbox data…
      </div>
    );
  }

  return (
    <div className="space-y-5">
      {error && (
        <div className="flex items-start gap-2 rounded-lg border border-rose-500/30 bg-rose-500/10 p-3 text-sm text-rose-200">
          <AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
          <span>{error}</span>
        </div>
      )}

      {usage && (
        <div className="grid sm:grid-cols-3 gap-3">
          <UsageTile
            icon={<Mail className="w-4 h-4" />}
            label="Mailboxes"
            current={usage.mailboxes_used}
            total={usage.mailbox_quota}
          />
          <UsageTile
            icon={<UsersIcon className="w-4 h-4" />}
            label="Aliases"
            current={usage.aliases_used}
            total={usage.aliases_included}
          />
          <UsageTile
            icon={<HardDrive className="w-4 h-4" />}
            label="Storage"
            current={usage.storage_used_mb}
            total={usage.storage_quota_mb}
            formatter={formatMb}
          />
        </div>
      )}

      {/* Mailboxes */}
      <div className="rounded-2xl border border-slate-700 bg-slate-900/60 p-5">
        <div className="flex items-center justify-between mb-3 flex-wrap gap-2">
          <div className="font-semibold text-slate-100 inline-flex items-center gap-2">
            <Mail className="w-4 h-4 text-emerald-300" /> Mailboxes ({mailboxes.length})
          </div>
          <button
            onClick={() => void refresh()}
            className="text-xs text-slate-400 hover:text-slate-200 inline-flex items-center gap-1"
          >
            <RefreshCw className="w-3.5 h-3.5" /> Refresh
          </button>
        </div>
        <div className="grid md:grid-cols-2 gap-3 mb-4">
          <input
            value={newMailboxUser}
            onChange={(e) => setNewMailboxUser(e.target.value)}
            placeholder="username"
            className="px-3 py-2 rounded-lg bg-slate-950 border border-slate-700 text-slate-100 text-sm focus:outline-none focus:border-emerald-500"
          />
          <input
            value={newMailboxName}
            onChange={(e) => setNewMailboxName(e.target.value)}
            placeholder="Display name (optional)"
            className="px-3 py-2 rounded-lg bg-slate-950 border border-slate-700 text-slate-100 text-sm focus:outline-none focus:border-emerald-500"
          />
          <input
            type="password"
            value={newMailboxPwd}
            onChange={(e) => setNewMailboxPwd(e.target.value)}
            placeholder="Password"
            className="px-3 py-2 rounded-lg bg-slate-950 border border-slate-700 text-slate-100 text-sm focus:outline-none focus:border-emerald-500"
          />
          <button
            onClick={() => void handleAddMailbox()}
            disabled={busy}
            className="px-4 py-2 rounded-lg bg-emerald-500 text-white text-sm font-semibold hover:bg-emerald-600 transition disabled:opacity-60 inline-flex items-center justify-center gap-2"
          >
            {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <PlusCircle className="w-4 h-4" />}
            Add mailbox
          </button>
        </div>
        {mailboxes.length === 0 ? (
          <div className="text-sm text-slate-400">No mailboxes yet.</div>
        ) : (
          <ul className="divide-y divide-slate-800">
            {mailboxes.map((mb) => (
              <li
                key={mb.username}
                className="py-2.5 flex items-center justify-between gap-3 flex-wrap"
              >
                <div className="min-w-0">
                  <div className="text-slate-100 font-mono text-sm truncate">
                    {mb.username}@{subscription.domain_name}
                  </div>
                  <div className="text-xs text-slate-500 truncate">
                    {mb.display_name || "—"}
                    {mb.is_domain_admin && " · Domain admin"}
                    {mb.disabled && " · Disabled"}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => void handleResetPassword(mb.username)}
                    className="px-2.5 py-1.5 rounded-md border border-slate-600 text-slate-200 text-xs hover:bg-slate-800 transition inline-flex items-center gap-1"
                  >
                    <KeyRound className="w-3.5 h-3.5" /> Reset
                  </button>
                  <button
                    onClick={() => void handleDeleteMailbox(mb.username)}
                    className="px-2.5 py-1.5 rounded-md border border-rose-500/40 text-rose-300 text-xs hover:bg-rose-500/10 transition inline-flex items-center gap-1"
                  >
                    <Trash2 className="w-3.5 h-3.5" /> Delete
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>

      {/* Aliases */}
      <div className="rounded-2xl border border-slate-700 bg-slate-900/60 p-5">
        <div className="font-semibold text-slate-100 inline-flex items-center gap-2 mb-3">
          <UsersIcon className="w-4 h-4 text-emerald-300" /> Aliases ({aliases.length})
        </div>
        <div className="grid md:grid-cols-3 gap-3 mb-4">
          <input
            value={newAliasName}
            onChange={(e) => setNewAliasName(e.target.value)}
            placeholder="alias name"
            className="px-3 py-2 rounded-lg bg-slate-950 border border-slate-700 text-slate-100 text-sm focus:outline-none focus:border-emerald-500"
          />
          <input
            value={newAliasTargets}
            onChange={(e) => setNewAliasTargets(e.target.value)}
            placeholder="target1@..., target2@..."
            className="md:col-span-1 px-3 py-2 rounded-lg bg-slate-950 border border-slate-700 text-slate-100 text-sm focus:outline-none focus:border-emerald-500"
          />
          <button
            onClick={() => void handleAddAlias()}
            disabled={busy}
            className="px-4 py-2 rounded-lg bg-emerald-500 text-white text-sm font-semibold hover:bg-emerald-600 transition disabled:opacity-60 inline-flex items-center justify-center gap-2"
          >
            {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <PlusCircle className="w-4 h-4" />}
            Add alias
          </button>
        </div>
        {aliases.length === 0 ? (
          <div className="text-sm text-slate-400">No aliases defined.</div>
        ) : (
          <ul className="divide-y divide-slate-800">
            {aliases.map((a) => (
              <li
                key={a.name}
                className="py-2.5 flex items-center justify-between gap-3 flex-wrap"
              >
                <div className="min-w-0">
                  <div className="text-slate-100 font-mono text-sm truncate">
                    {a.name}@{subscription.domain_name}
                  </div>
                  <div className="text-xs text-slate-500 truncate">
                    → {a.addresses.join(", ") || "—"}
                  </div>
                </div>
                <button
                  onClick={() => void handleDeleteAlias(a.name)}
                  className="px-2.5 py-1.5 rounded-md border border-rose-500/40 text-rose-300 text-xs hover:bg-rose-500/10 transition inline-flex items-center gap-1"
                >
                  <Trash2 className="w-3.5 h-3.5" /> Delete
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>

      {subscription.status === "active" && (
        <div className="flex justify-end">
          <button
            onClick={() => void handleCancel()}
            disabled={busy}
            className="px-4 py-2 rounded-lg border border-rose-400/40 text-rose-300 text-sm font-semibold hover:bg-rose-500/10 transition disabled:opacity-60"
          >
            Cancel subscription
          </button>
        </div>
      )}
    </div>
  );
}

function UsageTile({
  icon,
  label,
  current,
  total,
  formatter,
}: {
  icon: React.ReactNode;
  label: string;
  current: number;
  total: number;
  formatter?: (n: number) => string;
}) {
  const fmt = formatter ?? ((n: number) => String(n));
  const pct = total > 0 ? Math.min(100, Math.round((current / total) * 100)) : 0;
  return (
    <div className="rounded-xl border border-slate-700 bg-slate-900/40 p-4">
      <div className="flex items-center gap-2 text-xs uppercase tracking-wider text-slate-400">
        {icon}
        {label}
      </div>
      <div className="mt-1 text-lg font-bold text-slate-100">
        {fmt(current)} <span className="text-slate-500 font-normal">/ {fmt(total)}</span>
      </div>
      <div className="mt-2 h-1.5 w-full rounded-full bg-slate-800 overflow-hidden">
        <div
          className="h-full bg-emerald-500 transition-all"
          style={{ width: `${pct}%` }}
        />
      </div>
    </div>
  );
}

// ---------- new-subscription modal ----------
function OrderDialog({
  plans,
  onClose,
  onCreated,
}: {
  plans: BizmailPlan[];
  onClose: () => void;
  onCreated: (sub: BizmailSubscription) => void;
}) {
  const [planId, setPlanId] = useState<number | null>(plans[0]?.id ?? null);
  const [domain, setDomain] = useState("");
  const [cycle, setCycle] = useState<"monthly" | "yearly">("monthly");
  const [busy, setBusy] = useState(false);

  const submit = async () => {
    if (!planId || !domain.trim()) {
      toast.error("Domain and plan are required");
      return;
    }
    setBusy(true);
    try {
      const sub = await orderSubscription({
        plan_id: planId,
        domain_name: domain.trim(),
        billing_cycle: cycle,
      });
      onCreated(sub);
      toast.success("Subscription created. Activate it when your MX records are ready.");
      onClose();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Order failed");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4">
      <div className="bg-slate-900 border border-slate-700 rounded-2xl w-full max-w-lg p-6 space-y-5 shadow-2xl">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-bold text-slate-100">New Bizmail360 subscription</h2>
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-slate-200 text-sm"
          >
            Close
          </button>
        </div>

        <label className="block text-sm">
          <span className="text-slate-300 font-semibold">Your domain</span>
          <input
            value={domain}
            onChange={(e) => setDomain(e.target.value)}
            placeholder="yourbusiness.com"
            className="mt-1 w-full px-3 py-2 rounded-lg bg-slate-950 border border-slate-700 text-slate-100 focus:outline-none focus:border-emerald-500"
          />
        </label>

        <div className="space-y-2">
          <div className="text-sm text-slate-300 font-semibold">Choose a plan</div>
          <div className="grid gap-2">
            {plans.map((p) => (
              <button
                key={p.id}
                onClick={() => setPlanId(p.id)}
                className={`text-left rounded-xl border p-3 transition ${
                  planId === p.id
                    ? "border-emerald-500 bg-emerald-500/10"
                    : "border-slate-700 bg-slate-950 hover:border-slate-600"
                }`}
              >
                <div className="flex items-center justify-between">
                  <div className="font-semibold text-slate-100">{p.name}</div>
                  <div className="text-sm text-slate-300">
                    {cycle === "monthly"
                      ? p.price_monthly
                        ? `${p.currency} ${p.price_monthly}/mo`
                        : "Contact us"
                      : p.price_yearly
                      ? `${p.currency} ${p.price_yearly}/yr`
                      : "Contact us"}
                  </div>
                </div>
                <div className="text-xs text-slate-400 mt-1">
                  {p.mailbox_quota} mailboxes · {formatMb(p.storage_mb_per_mailbox)} each ·{" "}
                  {p.aliases_included} aliases
                </div>
              </button>
            ))}
          </div>
        </div>

        <div className="flex items-center gap-2 text-sm">
          <span className="text-slate-300 font-semibold">Billing:</span>
          {(["monthly", "yearly"] as const).map((c) => (
            <button
              key={c}
              onClick={() => setCycle(c)}
              className={`px-3 py-1.5 rounded-full text-xs font-semibold transition ${
                cycle === c
                  ? "bg-emerald-500 text-white"
                  : "bg-slate-800 text-slate-300 hover:bg-slate-700"
              }`}
            >
              {c === "monthly" ? "Monthly" : "Yearly"}
            </button>
          ))}
        </div>

        <div className="flex justify-end gap-2">
          <button
            onClick={onClose}
            className="px-4 py-2 rounded-lg border border-slate-600 text-slate-300 text-sm hover:bg-slate-800 transition"
          >
            Cancel
          </button>
          <button
            onClick={() => void submit()}
            disabled={busy}
            className="px-4 py-2 rounded-lg bg-emerald-500 text-white text-sm font-bold hover:bg-emerald-600 transition disabled:opacity-60 inline-flex items-center gap-2"
          >
            {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Rocket className="w-4 h-4" />}
            Create subscription
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------- page ----------
export default function ClientBizmail() {
  const [subs, setSubs] = useState<BizmailSubscription[]>([]);
  const [plans, setPlans] = useState<BizmailPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedId, setSelectedId] = useState<number | null>(null);
  const [showOrder, setShowOrder] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [mine, pubPlans] = await Promise.all([fetchMySubscriptions(), fetchPublicPlans()]);
      setSubs(mine);
      setPlans(pubPlans);
      if (mine.length > 0 && selectedId == null) {
        setSelectedId(mine[0].id);
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load subscriptions");
    } finally {
      setLoading(false);
    }
  }, [selectedId]);

  useEffect(() => {
    void load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const selected = useMemo(
    () => subs.find((s) => s.id === selectedId) ?? null,
    [subs, selectedId]
  );

  const handleChanged = (updated: BizmailSubscription) => {
    setSubs((prev) => prev.map((s) => (s.id === updated.id ? updated : s)));
  };

  const handleCreated = (created: BizmailSubscription) => {
    setSubs((prev) => [created, ...prev]);
    setSelectedId(created.id);
  };

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100">
      <div className="max-w-6xl mx-auto px-4 md:px-6 py-8">
        <div className="flex items-center justify-between gap-4 mb-8 flex-wrap">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-2xl bg-emerald-500/20 text-emerald-300 flex items-center justify-center">
              <Inbox className="w-6 h-6" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-extrabold">My Bizmail360 Mail</h1>
              <p className="text-sm text-slate-400">
                Professional mail hosting powered by SmarterMail.
              </p>
            </div>
          </div>
          <button
            onClick={() => setShowOrder(true)}
            className="px-4 py-2.5 rounded-lg bg-emerald-500 text-white text-sm font-bold hover:bg-emerald-600 transition inline-flex items-center gap-2"
          >
            <PlusCircle className="w-4 h-4" /> New subscription
          </button>
        </div>

        {error && (
          <div className="mb-4 flex items-start gap-2 rounded-lg border border-rose-500/30 bg-rose-500/10 p-3 text-sm text-rose-200">
            <AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
            <span>{error}</span>
          </div>
        )}

        {loading ? (
          <div className="flex items-center gap-2 text-slate-400 text-sm">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading…
          </div>
        ) : subs.length === 0 ? (
          <div className="rounded-2xl border border-slate-700 bg-slate-900/60 p-8 text-center">
            <ShieldCheck className="w-10 h-10 mx-auto text-emerald-300 mb-3" />
            <h2 className="text-xl font-bold">Set up your first business mailbox</h2>
            <p className="text-sm text-slate-400 mt-2">
              Create a Bizmail360 subscription on one of your domains to start sending and receiving
              mail in minutes.
            </p>
            <button
              onClick={() => setShowOrder(true)}
              className="mt-5 px-5 py-2.5 rounded-lg bg-emerald-500 text-white text-sm font-bold hover:bg-emerald-600 transition inline-flex items-center gap-2"
            >
              <Rocket className="w-4 h-4" /> Choose a plan
            </button>
          </div>
        ) : (
          <div className="grid md:grid-cols-[18rem_1fr] gap-6">
            <div className="space-y-2">
              {subs.map((s) => {
                const meta = statusBadge(s.status);
                const isSelected = selectedId === s.id;
                return (
                  <button
                    key={s.id}
                    onClick={() => setSelectedId(s.id)}
                    className={`w-full text-left rounded-xl border p-3 transition ${
                      isSelected
                        ? "border-emerald-500 bg-emerald-500/10"
                        : "border-slate-700 bg-slate-900/60 hover:border-slate-600"
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="font-mono text-sm text-slate-100 truncate">
                        {s.domain_name}
                      </div>
                      <span
                        className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-semibold ${meta.pill}`}
                      >
                        <meta.Icon className="w-3 h-3" />
                        {meta.label}
                      </span>
                    </div>
                    <div className="text-xs text-slate-400 mt-1">
                      {s.plan?.name ?? `Plan #${s.plan_id}`} · {s.billing_cycle}
                    </div>
                  </button>
                );
              })}
            </div>
            <div>
              {selected ? (
                <SubscriptionDetail subscription={selected} onChanged={handleChanged} />
              ) : (
                <div className="rounded-2xl border border-slate-700 bg-slate-900/60 p-6 text-slate-400 text-sm">
                  Select a subscription on the left.
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {showOrder && (
        <OrderDialog
          plans={plans.filter((p) => p.is_active)}
          onClose={() => setShowOrder(false)}
          onCreated={handleCreated}
        />
      )}
    </div>
  );
}