"use client";

import { useEffect, useMemo, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Card,
  EmptyState,
  Input,
  Modal,
  PageHeader,
  PageLoader,
  Pagination,
  Select,
  StatCard,
  StatusBadge,
  usePagination,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatBDT, formatDateTime, formatDate } from "@/lib/utils";
import { AUDIENCE_TYPES, BROADCAST_CHANNELS, PAYMENT_METHODS, SMS_TYPES } from "@/lib/constants";
import { emsConfirm } from "@/components/ConfirmDialog";
import {
  IconAlertTriangle,
  IconCheckCircle,
  IconDollar,
  IconMail,
  IconMessageCircle,
  IconPhone,
  IconSend,
  IconSettings,
  IconWallet,
} from "@/components/icons";

interface BroadcastRow {
  id: number;
  channels: string[];
  audience: string;
  className: string | null;
  studentName: string | null;
  staffName: string | null;
  subject: string | null;
  body: string;
  recipientCount: number;
  status: string;
  sentBy: string | null;
  createdAt: string;
}

interface CommsData {
  stats: { total: number; SMS: number; EMAIL: number; WHATSAPP: number };
  smsBalance: number;
  broadcasts: BroadcastRow[];
}

interface StudentMini {
  id: number;
  roll: string;
  name: string;
  guardianName: string;
  classItemId: number | null;
}

interface StaffMini {
  id: number;
  employeeCode: string;
  name: string;
  status: string;
}

interface ClassItem {
  id: number;
  category: string;
  name: string;
  nameBn: string;
}

interface BroadcastDetail {
  broadcast: {
    id: number;
    channels: string[];
    audience: string;
    subject: string | null;
    body: string;
    status: string;
    sentBy: string | null;
    createdAt: string;
    recipients: { id: number; name: string; phone: string | null; email: string | null }[];
  };
}

interface CommSettings {
  setting: {
    smsApiUrl: string | null;
    smsApiKey: string | null;
    smsApiKeySet: boolean;
    smsSenderId: string | null;
    smsType: string;
    smsBalance: number;
    smtpHost: string | null;
    smtpPort: number | null;
    smtpUser: string | null;
    smtpFromName: string | null;
    smtpFromEmail: string | null;
    smtpSecure: boolean;
    waApiUrl: string | null;
    waPhoneId: string | null;
    updatedAt: string;
  };
  packages: { qty: number; price: number }[];
}

interface PurchaseData {
  balance: number;
  purchases: { id: number; quantity: number; price: number; method: string; createdAt: string }[];
}

type Tab = "compose" | "purchase" | "integration";

const channelIcons: Record<string, React.ComponentType<{ className?: string }>> = {
  SMS: IconPhone,
  EMAIL: IconMail,
  WHATSAPP: IconMessageCircle,
};

const emptyIntegration = {
  smsApiUrl: "",
  smsApiKey: "",
  smsSenderId: "",
  smsType: "NON_MASKING",
  smtpHost: "",
  smtpPort: "",
  smtpUser: "",
  smtpPass: "",
  smtpFromName: "",
  smtpFromEmail: "",
  smtpSecure: true,
  waApiUrl: "",
  waApiKey: "",
  waPhoneId: "",
};

export default function PortalCommunicationPage() {
  const { t, locale } = useLang();
  const [tab, setTab] = useState<Tab>("compose");
  const { data, loading, reload } = useApi<CommsData>("/api/portal/communication");
  const { data: studentsData } = useApi<{ students: StudentMini[] }>("/api/portal/students");
  const { data: hrData } = useApi<{ staff: StaffMini[] }>("/api/portal/hr");
  const { data: academicData } = useApi<{ items: ClassItem[]; selectedIds: number[] }>(
    "/api/portal/academic"
  );

  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [sending, setSending] = useState(false);

  // Composer state
  const [channels, setChannels] = useState<string[]>(["SMS"]);
  const [audience, setAudience] = useState("ALL_STUDENTS");
  const [classItemId, setClassItemId] = useState("");
  const [studentId, setStudentId] = useState("");
  const [staffId, setStaffId] = useState("");
  const [subject, setSubject] = useState("");
  const [body, setBody] = useState("");

  // Detail modal
  const [detailId, setDetailId] = useState<number | null>(null);
  const { data: detail, loading: detailLoading } = useApi<BroadcastDetail>(
    detailId ? `/api/portal/communication/${detailId}` : null
  );

  // Purchase tab
  const { data: purchaseData, reload: purchaseReload } = useApi<PurchaseData>(
    "/api/portal/communication/purchase"
  );
  const [buyPack, setBuyPack] = useState<{ qty: number; price: number } | null>(null);
  const [buyMethod, setBuyMethod] = useState("BKASH");
  const [buying, setBuying] = useState(false);

  // Integration tab
  const { data: settingsData, loading: settingsLoading, reload: settingsReload } =
    useApi<CommSettings>("/api/portal/communication/settings");
  const [form, setForm] = useState(emptyIntegration);
  const [savingSettings, setSavingSettings] = useState(false);

  // Hydrate the integration form once settings arrive
  useEffect(() => {
    if (!settingsData) return;
    const s = settingsData.setting;
    setForm({
      smsApiUrl: s.smsApiUrl ?? "",
      smsApiKey: s.smsApiKey ?? "",
      smsSenderId: s.smsSenderId ?? "",
      smsType: s.smsType,
      smtpHost: s.smtpHost ?? "",
      smtpPort: s.smtpPort != null ? String(s.smtpPort) : "",
      smtpUser: s.smtpUser ?? "",
      smtpPass: "",
      smtpFromName: s.smtpFromName ?? "",
      smtpFromEmail: s.smtpFromEmail ?? "",
      smtpSecure: s.smtpSecure,
      waApiUrl: s.waApiUrl ?? "",
      waApiKey: "",
      waPhoneId: s.waPhoneId ?? "",
    });
  }, [settingsData]);

  const classes = useMemo(() => {
    if (!academicData) return [];
    const selected = new Set(academicData.selectedIds);
    return academicData.items.filter((i) => i.category === "CLASS" && selected.has(i.id));
  }, [academicData]);

  const students = studentsData?.students ?? [];
  const activeStaff = (hrData?.staff ?? []).filter((s) => s.status === "ACTIVE");
  const smsBalance = data?.smsBalance ?? purchaseData?.balance ?? 0;
  const broadcasts = data?.broadcasts ?? [];
  const purchases = purchaseData?.purchases ?? [];
  const broadcastsPager = usePagination(broadcasts, 10);
  const purchasesPager = usePagination(purchases, 10);

  const recipientCount = useMemo(() => {
    switch (audience) {
      case "ALL_STUDENTS":
        return students.length;
      case "BY_CLASS":
        return classItemId ? students.filter((s) => s.classItemId === Number(classItemId)).length : 0;
      case "STUDENT":
        return studentId ? 1 : 0;
      case "ALL_STAFF":
        return activeStaff.length;
      case "STAFF":
        return staffId ? 1 : 0;
      default:
        return 0;
    }
  }, [audience, classItemId, studentId, staffId, students, activeStaff]);

  // Reset pickers when audience changes
  useEffect(() => {
    setClassItemId("");
    setStudentId("");
    setStaffId("");
  }, [audience]);

  function notify(type: "success" | "error", text: string) {
    setMessage({ type, text });
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function toggleChannel(ch: string) {
    setChannels((prev) =>
      prev.includes(ch) ? prev.filter((c) => c !== ch) : [...prev, ch]
    );
  }

  function applyTemplate(key: "FeeReminder" | "Holiday" | "Exam" | "Meeting") {
    const bodies = {
      FeeReminder: t.portal.communicationPage.templateFeeReminderBody,
      Holiday: t.portal.communicationPage.templateHolidayBody,
      Exam: t.portal.communicationPage.templateExamBody,
      Meeting: t.portal.communicationPage.templateMeetingBody,
    } as const;
    setBody(bodies[key]);
  }

  async function send() {
    if (channels.length === 0) {
      notify("error", t.portal.communicationPage.noChannel);
      return;
    }
    if (recipientCount === 0) {
      notify("error", t.portal.communicationPage.noRecipients);
      return;
    }
    setSending(true);
    setMessage(null);
    try {
      await api("/api/portal/communication", {
        method: "POST",
        body: JSON.stringify({
          channels,
          audience,
          classItemId: classItemId || null,
          studentId: studentId || null,
          staffId: staffId || null,
          subject,
          body,
        }),
      });
      setSubject("");
      setBody("");
      reload();
      purchaseReload();
      notify("success", t.portal.communicationPage.sentSuccessfully);
    } catch (e) {
      const err = e instanceof Error ? e.message : "";
      notify(
        "error",
        err === "NO_CHANNEL"
          ? t.portal.communicationPage.noChannel
          : err === "NO_RECIPIENTS"
            ? t.portal.communicationPage.noRecipients
            : err === "SMS_LOW_BALANCE"
              ? t.portal.communicationPage.smsLowBalance
              : t.common.tryAgain
      );
    } finally {
      setSending(false);
    }
  }

  async function confirmPurchase() {
    if (!buyPack) return;
    if (!(await emsConfirm({ message: t.portal.communicationPage.purchaseConfirm, danger: false }))) return;
    setBuying(true);
    try {
      await api("/api/portal/communication/purchase", {
        method: "POST",
        body: JSON.stringify({ quantity: buyPack.qty, method: buyMethod }),
      });
      setBuyPack(null);
      purchaseReload();
      reload();
      notify("success", t.portal.communicationPage.purchaseSuccess);
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setBuying(false);
    }
  }

  async function saveSettings() {
    setSavingSettings(true);
    try {
      await api("/api/portal/communication/settings", {
        method: "PUT",
        body: JSON.stringify(form),
      });
      settingsReload();
      notify("success", t.portal.communicationPage.integrationSaved);
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setSavingSettings(false);
    }
  }

  if (loading) return <PageLoader text={t.common.loading} />;
  const stats = data?.stats;

  return (
    <div>
      <PageHeader
        title={t.portal.communicationPage.title}
        subtitle={t.portal.communicationPage.subtitle}
        action={
          <span className="badge badge-primary px-3 py-2 d-inline-flex align-items-center gap-1">
            <IconPhone className="svg-14" />
            {t.portal.communicationPage.smsBalance}: {smsBalance}
          </span>
        }
      />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      {/* Tabs */}
      <ul className="nav nav-tabs mb-4" role="tablist">
        {(["compose", "purchase", "integration"] as Tab[]).map((key) => {
          const labels: Record<Tab, string> = {
            compose: t.portal.communicationPage.tabCompose,
            purchase: t.portal.communicationPage.tabPurchase,
            integration: t.portal.communicationPage.tabIntegration,
          };
          return (
            <li className="nav-item" key={key}>
              <button
                className={`nav-link ${tab === key ? "active" : ""}`}
                onClick={() => setTab(key)}
                type="button"
              >
                {labels[key]}
              </button>
            </li>
          );
        })}
      </ul>

      {/* ---------- Compose tab ---------- */}
      {tab === "compose" && (
        <div>
          {/* Stats */}
          <div className="row g-3 mb-4">
            <div className="col-xl-3 col-sm-6">
              <StatCard label={t.portal.communicationPage.totalSent} value={String(stats?.total ?? 0)} icon={<IconSend />} accent="teal" />
            </div>
            <div className="col-xl-3 col-sm-6">
              <StatCard label={t.portal.communicationPage.smsSent} value={String(stats?.SMS ?? 0)} icon={<IconPhone />} accent="blue" />
            </div>
            <div className="col-xl-3 col-sm-6">
              <StatCard label={t.portal.communicationPage.emailSent} value={String(stats?.EMAIL ?? 0)} icon={<IconMail />} accent="purple" />
            </div>
            <div className="col-xl-3 col-sm-6">
              <StatCard label={t.portal.communicationPage.whatsappSent} value={String(stats?.WHATSAPP ?? 0)} icon={<IconMessageCircle />} accent="sky" />
            </div>
          </div>

          <div className="row g-4">
            {/* Composer */}
            <div className="col-xl-5">
              <Card title={t.portal.communicationPage.composeTitle} icon={<IconSend className="svg-18" />}>
                {/* Channels */}
                <label className="col-form-label pt-0 f-w-600">{t.portal.communicationPage.channelsLabel}</label>
                <div className="d-flex flex-wrap gap-2 mb-2">
                  {BROADCAST_CHANNELS.map((ch) => {
                    const Icon = channelIcons[ch];
                    const active = channels.includes(ch);
                    return (
                      <button
                        key={ch}
                        type="button"
                        className={`ems-channel ${active ? "active" : ""}`}
                        onClick={() => toggleChannel(ch)}
                      >
                        <Icon />
                        {t.channels[ch]}
                      </button>
                    );
                  })}
                </div>
                {channels.includes("SMS") && (
                  <p className="mb-3 ems-fs-11 text-muted">
                    <IconAlertTriangle className="svg-14" /> {t.portal.communicationPage.balanceNote} ({smsBalance})
                  </p>
                )}

                <Select label={t.portal.communicationPage.audienceLabel} value={audience} onChange={(e) => setAudience(e.target.value)}>
                  {AUDIENCE_TYPES.map((a) => (
                    <option key={a} value={a}>
                      {t.audiences[a]}
                    </option>
                  ))}
                </Select>

                {audience === "BY_CLASS" && (
                  <Select label={t.portal.communicationPage.selectClass} value={classItemId} onChange={(e) => setClassItemId(e.target.value)}>
                    <option value="">— {t.common.filter} —</option>
                    {classes.map((c) => (
                      <option key={c.id} value={c.id}>
                        {locale === "bn" ? c.nameBn : c.name}
                      </option>
                    ))}
                  </Select>
                )}

                {audience === "STUDENT" && (
                  <Select label={t.portal.communicationPage.selectStudent} value={studentId} onChange={(e) => setStudentId(e.target.value)}>
                    <option value="">— {t.common.filter} —</option>
                    {students.map((s) => (
                      <option key={s.id} value={s.id}>
                        {s.roll} — {s.name} ({s.guardianName})
                      </option>
                    ))}
                  </Select>
                )}

                {audience === "STAFF" && (
                  <Select label={t.portal.communicationPage.selectStaff} value={staffId} onChange={(e) => setStaffId(e.target.value)}>
                    <option value="">— {t.common.filter} —</option>
                    {activeStaff.map((s) => (
                      <option key={s.id} value={s.id}>
                        {s.employeeCode} — {s.name}
                      </option>
                    ))}
                  </Select>
                )}

                {channels.includes("EMAIL") && (
                  <Input
                    label={t.portal.communicationPage.subjectLabel}
                    value={subject}
                    onChange={(e) => setSubject(e.target.value)}
                  />
                )}

                <div className="form-group mb-3">
                  <label className="col-form-label pt-0 f-w-600">{t.portal.communicationPage.messageLabel}</label>
                  <textarea
                    className="form-control"
                    rows={5}
                    placeholder={t.portal.communicationPage.messagePlaceholder}
                    value={body}
                    onChange={(e) => setBody(e.target.value)}
                  />
                </div>

                {/* Quick templates */}
                <label className="col-form-label pt-0 f-w-600 ems-fs-13">{t.portal.communicationPage.templatesLabel}</label>
                <div className="d-flex flex-wrap gap-2 mb-3">
                  <button type="button" className="btn btn-soft-secondary btn-sm" onClick={() => applyTemplate("FeeReminder")}>
                    {t.portal.communicationPage.templateFeeReminder}
                  </button>
                  <button type="button" className="btn btn-soft-secondary btn-sm" onClick={() => applyTemplate("Holiday")}>
                    {t.portal.communicationPage.templateHoliday}
                  </button>
                  <button type="button" className="btn btn-soft-secondary btn-sm" onClick={() => applyTemplate("Exam")}>
                    {t.portal.communicationPage.templateExam}
                  </button>
                  <button type="button" className="btn btn-soft-secondary btn-sm" onClick={() => applyTemplate("Meeting")}>
                    {t.portal.communicationPage.templateMeeting}
                  </button>
                </div>

                <div className="d-flex align-items-center justify-content-between gap-2 pt-2 border-top">
                  <p className="mb-0 ems-fs-13 text-muted">
                    <b className="ems-text-teal">{recipientCount}</b> {t.portal.communicationPage.recipientsCount}
                  </p>
                  <Button onClick={send} loading={sending} disabled={!body.trim()}>
                    <IconSend className="svg-16" />
                    <span className="ms-1">{sending ? t.portal.communicationPage.sendingLabel : t.portal.communicationPage.sendNotification}</span>
                  </Button>
                </div>
                <p className="mb-0 mt-3 ems-fs-11 text-muted">
                  <IconCheckCircle className="svg-14" /> {t.portal.communicationPage.simulatedNote}
                </p>
              </Card>
            </div>

            {/* History */}
            <div className="col-xl-7">
              <Card title={t.portal.communicationPage.historyTitle} icon={<IconMail className="svg-18" />}>
                {!data || data.broadcasts.length === 0 ? (
                  <EmptyState icon={<IconSend />} title={t.portal.communicationPage.noBroadcasts} />
                ) : (
                  <>
                    <div className="table-responsive">
                    <table className="table table-hover align-middle mb-0">
                      <thead className="ems-table-head">
                        <tr>
                          <th>{t.common.channel}</th>
                          <th>{t.common.audience}</th>
                          <th>{t.common.recipients}</th>
                          <th>{t.common.date}</th>
                          <th className="text-end">{t.common.view}</th>
                        </tr>
                      </thead>
                      <tbody>
                        {broadcastsPager.paged.map((b) => (
                          <tr key={b.id} style={{ cursor: "pointer" }} onClick={() => setDetailId(b.id)}>
                            <td>
                              <div className="d-flex gap-1">
                                {b.channels.map((ch) => {
                                  const Icon = channelIcons[ch];
                                  return Icon ? <Icon key={ch} className="svg-16 text-primary" /> : null;
                                })}
                              </div>
                            </td>
                            <td>
                              <p className="mb-0 f-w-600 ems-fs-13">{t.audiences[b.audience as keyof typeof t.audiences]}</p>
                              <p className="mb-0 ems-fs-11 text-muted text-truncate" style={{ maxWidth: 220 }}>
                                {b.className ?? b.studentName ?? b.staffName ?? "—"}
                              </p>
                            </td>
                            <td>
                              <span className="badge badge-primary">{b.recipientCount}</span>
                            </td>
                            <td className="ems-fs-12">{formatDateTime(b.createdAt, locale)}</td>
                            <td className="text-end">
                              <Button size="sm" variant="secondary" onClick={() => setDetailId(b.id)}>
                                {t.common.view}
                              </Button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                    </div>
                    <Pagination {...broadcastsPager} onPageChange={broadcastsPager.setPage} onSizeChange={broadcastsPager.setSize} />
                  </>
                )}
              </Card>
            </div>
          </div>
        </div>
      )}

      {/* ---------- Purchase tab ---------- */}
      {tab === "purchase" && (
        <div className="row g-4">
          <div className="col-xl-8">
            <Card title={t.portal.communicationPage.tabPurchase} icon={<IconWallet className="svg-18" />}>
              <div className="row g-3">
                {(settingsData?.packages ?? []).map((p) => (
                  <div className="col-md-3 col-6" key={p.qty}>
                    <div className="card h-100">
                      <div className="card-body text-center d-flex flex-column justify-content-center">
                        <h4 className="f-w-800 mb-1 ems-text-teal">{p.qty.toLocaleString()}</h4>
                        <p className="mb-2 ems-fs-12 text-muted">SMS</p>
                        <h5 className="f-w-700 mb-3">{formatBDT(p.price, locale)}</h5>
                        <Button size="sm" variant="success" onClick={() => setBuyPack(p)}>
                          <IconDollar className="svg-14" />
                          <span className="ms-1">{t.portal.communicationPage.buyNow}</span>
                        </Button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
              <p className="mb-0 mt-3 ems-fs-11 text-muted">{t.portal.communicationPage.balanceNote}</p>
            </Card>
          </div>
          <div className="col-xl-4">
            <StatCard
              label={t.portal.communicationPage.smsBalance}
              value={String(purchaseData?.balance ?? 0)}
              icon={<IconPhone />}
              accent="teal"
              hint={t.portal.communicationPage.balanceNote}
            />
          </div>
          <div className="col-12">
            <Card title={t.portal.communicationPage.purchaseHistory}>
              {!purchaseData || purchaseData.purchases.length === 0 ? (
                <EmptyState title={t.portal.communicationPage.noPurchases} />
              ) : (
                <>
                  <div className="table-responsive">
                  <table className="table table-hover align-middle mb-0">
                    <thead className="ems-table-head">
                      <tr>
                        <th>{t.common.quantity}</th>
                        <th>{t.common.amount}</th>
                        <th>{t.common.method}</th>
                        <th>{t.common.date}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {purchasesPager.paged.map((p) => (
                        <tr key={p.id}>
                          <td className="f-w-700">{p.quantity.toLocaleString()} SMS</td>
                          <td>{formatBDT(p.price, locale)}</td>
                          <td className="ems-fs-13">{t.methods[p.method as keyof typeof t.methods]}</td>
                          <td className="ems-fs-13">{formatDate(p.createdAt, locale)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  </div>
                  <Pagination {...purchasesPager} onPageChange={purchasesPager.setPage} onSizeChange={purchasesPager.setSize} />
                </>
              )}
            </Card>
          </div>
        </div>
      )}

      {/* ---------- Integration tab ---------- */}
      {tab === "integration" &&
        (settingsLoading ? (
          <PageLoader text={t.common.loading} />
        ) : (
          <div>
            <p className="mb-4 ems-fs-12 text-muted">
              <IconSettings className="svg-14" /> {t.portal.communicationPage.integrationNote}
            </p>
            <div className="row g-4">
              {/* SMS gateway */}
              <div className="col-xl-4">
                <Card title={t.portal.communicationPage.smsIntegration} icon={<IconPhone className="svg-18" />}>
                  <Input
                    label={t.portal.communicationPage.apiUrl}
                    value={form.smsApiUrl}
                    onChange={(e) => setForm({ ...form, smsApiUrl: e.target.value })}
                    placeholder="https://api.smsprovider.com/v1/send"
                  />
                  <Input
                    label={t.portal.communicationPage.apiKey}
                    value={form.smsApiKey}
                    onChange={(e) => setForm({ ...form, smsApiKey: e.target.value })}
                    placeholder={settingsData?.setting.smsApiKeySet ? "••••" : "API key"}
                  />
                  <Input
                    label={t.portal.communicationPage.senderId}
                    value={form.smsSenderId}
                    onChange={(e) => setForm({ ...form, smsSenderId: e.target.value })}
                    placeholder="e.g. DEMOSCHL"
                  />
                  <Select
                    label={t.portal.communicationPage.smsTypeLabel}
                    value={form.smsType}
                    onChange={(e) => setForm({ ...form, smsType: e.target.value })}
                  >
                    {SMS_TYPES.map((s) => (
                      <option key={s} value={s}>
                        {s === "MASKING" ? t.portal.communicationPage.masking : t.portal.communicationPage.nonMasking}
                      </option>
                    ))}
                  </Select>
                </Card>
              </div>

              {/* Email SMTP */}
              <div className="col-xl-4">
                <Card title={t.portal.communicationPage.emailIntegration} icon={<IconMail className="svg-18" />}>
                  <div className="row">
                    <div className="col-8">
                      <Input
                        label={t.portal.communicationPage.smtpHostLabel}
                        value={form.smtpHost}
                        onChange={(e) => setForm({ ...form, smtpHost: e.target.value })}
                        placeholder="smtp.provider.com"
                      />
                    </div>
                    <div className="col-4">
                      <Input
                        label={t.portal.communicationPage.smtpPortLabel}
                        value={form.smtpPort}
                        onChange={(e) => setForm({ ...form, smtpPort: e.target.value })}
                        placeholder="587"
                      />
                    </div>
                  </div>
                  <Input
                    label={t.portal.communicationPage.smtpUserLabel}
                    value={form.smtpUser}
                    onChange={(e) => setForm({ ...form, smtpUser: e.target.value })}
                  />
                  <Input
                    label={t.portal.communicationPage.smtpPassLabel}
                    type="password"
                    value={form.smtpPass}
                    onChange={(e) => setForm({ ...form, smtpPass: e.target.value })}
                    placeholder="••••••••"
                  />
                  <Input
                    label={t.portal.communicationPage.smtpFromNameLabel}
                    value={form.smtpFromName}
                    onChange={(e) => setForm({ ...form, smtpFromName: e.target.value })}
                    placeholder="Demo High School"
                  />
                  <Input
                    label={t.portal.communicationPage.smtpFromEmailLabel}
                    type="email"
                    value={form.smtpFromEmail}
                    onChange={(e) => setForm({ ...form, smtpFromEmail: e.target.value })}
                    placeholder="noreply@demohigh.edu"
                  />
                  <div className="form-check mb-3">
                    <input
                      className="form-check-input"
                      type="checkbox"
                      id="smtpSecure"
                      checked={form.smtpSecure}
                      onChange={(e) => setForm({ ...form, smtpSecure: e.target.checked })}
                    />
                    <label className="form-check-label f-w-600" htmlFor="smtpSecure">
                      {t.portal.communicationPage.smtpSecureLabel}
                    </label>
                  </div>
                </Card>
              </div>

              {/* WhatsApp */}
              <div className="col-xl-4">
                <Card title={t.portal.communicationPage.waIntegration} icon={<IconMessageCircle className="svg-18" />}>
                  <Input
                    label={t.portal.communicationPage.apiUrl}
                    value={form.waApiUrl}
                    onChange={(e) => setForm({ ...form, waApiUrl: e.target.value })}
                    placeholder="https://graph.facebook.com/v20.0"
                  />
                  <Input
                    label={t.portal.communicationPage.apiKey}
                    type="password"
                    value={form.waApiKey}
                    onChange={(e) => setForm({ ...form, waApiKey: e.target.value })}
                    placeholder="••••••••"
                  />
                  <Input
                    label={t.portal.communicationPage.waPhoneLabel}
                    value={form.waPhoneId}
                    onChange={(e) => setForm({ ...form, waPhoneId: e.target.value })}
                  />
                </Card>
              </div>

              <div className="col-12 d-flex justify-content-end gap-2">
                <p className="me-auto mb-0 ems-fs-11 text-muted align-self-center">
                  {t.portal.communicationPage.secretKeepNote}
                </p>
                <Button onClick={saveSettings} loading={savingSettings}>
                  <IconSettings className="svg-16" />
                  <span className="ms-1">{t.common.saveChanges}</span>
                </Button>
              </div>
            </div>
          </div>
        ))}

      {/* Broadcast detail modal */}
      <Modal
        open={detailId !== null}
        onClose={() => setDetailId(null)}
        title={t.portal.communicationPage.recipientsTitle}
        wide
      >
        {detailLoading || !detail ? (
          <div className="text-center py-4">
            <span className="spinner-border text-primary" role="status" />
          </div>
        ) : (
          <div>
            <div className="p-3 rounded mb-3" style={{ background: "rgba(36,105,92,0.07)" }}>
              <div className="d-flex flex-wrap align-items-center gap-2 mb-2">
                {detail.broadcast.channels.map((ch) => {
                  const Icon = channelIcons[ch];
                  return (
                    <span key={ch} className="badge badge-primary d-inline-flex align-items-center gap-1">
                      {Icon && <Icon className="svg-14" />}
                      {t.channels[ch as keyof typeof t.channels]}
                    </span>
                  );
                })}
                <StatusBadge status={detail.broadcast.status} label={t.status[detail.broadcast.status as keyof typeof t.status]} />
                <span className="ems-fs-11 text-muted ms-auto">{formatDateTime(detail.broadcast.createdAt, locale)}</span>
              </div>
              {detail.broadcast.subject && <h6 className="f-w-700 mb-1">{detail.broadcast.subject}</h6>}
              <p className="mb-1 ems-fs-13">{detail.broadcast.body}</p>
              <p className="mb-0 ems-fs-11 text-muted">
                {t.audiences[detail.broadcast.audience as keyof typeof t.audiences]}
                {detail.broadcast.sentBy ? ` · ${detail.broadcast.sentBy}` : ""}
              </p>
            </div>
            <div className="table-responsive">
              <table className="table table-sm table-hover align-middle mb-0">
                <thead className="ems-table-head">
                  <tr>
                    <th>{t.common.name}</th>
                    <th>{t.common.phone}</th>
                    <th>{t.common.email}</th>
                    <th>{t.common.status}</th>
                  </tr>
                </thead>
                <tbody>
                  {detail.broadcast.recipients.map((r) => (
                    <tr key={r.id}>
                      <td className="f-w-600">{r.name}</td>
                      <td className="ems-fs-13">{r.phone ?? "—"}</td>
                      <td className="ems-fs-13">{r.email ?? "—"}</td>
                      <td>
                        <span className="badge badge-success">{t.status.SENT}</span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </Modal>

      {/* Purchase confirm modal */}
      <Modal
        open={buyPack !== null}
        onClose={() => setBuyPack(null)}
        title={`${t.portal.communicationPage.buyNow} — ${buyPack?.qty ?? 0} SMS`}
      >
        {buyPack && (
          <div>
            <div className="p-3 rounded mb-3 d-flex justify-content-between align-items-center" style={{ background: "rgba(36,105,92,0.07)" }}>
              <div>
                <p className="mb-0 f-w-700">{buyPack.qty.toLocaleString()} SMS</p>
              </div>
              <h5 className="mb-0 f-w-800 ems-text-teal">{formatBDT(buyPack.price, locale)}</h5>
            </div>
            <Select label={t.common.method} value={buyMethod} onChange={(e) => setBuyMethod(e.target.value)}>
              {PAYMENT_METHODS.map((m) => (
                <option key={m} value={m}>
                  {t.methods[m]}
                </option>
              ))}
            </Select>
            <div className="d-flex justify-content-end gap-2">
              <Button variant="secondary" onClick={() => setBuyPack(null)}>
                {t.common.cancel}
              </Button>
              <Button variant="success" onClick={confirmPurchase} loading={buying}>
                <IconDollar className="svg-16" />
                <span className="ms-1">{t.portal.communicationPage.buyNow}</span>
              </Button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}
