'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { adminClient } from '@/lib/api';
import { formatCount } from '@/lib/format';
import { isTwilioSmsProvider, TWILIO_TRIAL_SMS_TEMPLATES } from '@/lib/twilio';
import type { AdminMessage } from '@zyphon/api-client';
import { CHANNELS, ago, type ChannelId } from '@/lib/types';
import { useToast } from '@/components/Toast';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
import { Input } from '@/components/ui/Input';
import { Select } from '@/components/ui/Select';

const PRIMARY_CHANNELS: ChannelId[] = ['email', 'sms', 'whatsapp'];

export default function HomePage() {
  const router = useRouter();
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const { data: stats = null } = useQuery({
    queryKey: ['stats'],
    queryFn: () => adminClient.getStats(),
    refetchInterval: 5000,
  });
  const { data: messages = [] } = useQuery({
    queryKey: ['messages', 'home'],
    queryFn: () => adminClient.getMessages({ limit: 8 }),
    refetchInterval: 4000,
  });
  const { data: providers = [] } = useQuery({
    queryKey: ['providers'],
    queryFn: () => adminClient.getProviders(),
  });
  const { data: apps = [] } = useQuery({
    queryKey: ['applications'],
    queryFn: () => adminClient.getApplications(),
  });
  const { data: templatesData } = useQuery({
    queryKey: ['templates'],
    queryFn: () => adminClient.getTemplates(),
  });
  const allTemplates = (templatesData?.templates || []) as Array<{
    id: string;
    name: string;
    channel: ChannelId;
    subject?: string;
    body: string;
    dlt_id?: string;
    variables?: string[];
  }>;

  // Drawer & Modal state
  const [selectedMessage, setSelectedMessage] = useState<AdminMessage | null>(null);
  const [showTestModal, setShowTestModal] = useState(false);
  const [testChannel, setTestChannel] = useState<ChannelId>('email');
  const [selectedTemplateId, setSelectedTemplateId] = useState('');
  const [templateVars, setTemplateVars] = useState<Record<string, string>>({});
  const [testTo, setTestTo] = useState('');
  const [testSubject, setTestSubject] = useState('Zyphon Live Test');
  const [testBody, setTestBody] = useState(
    'Your message was routed cleanly through Zyphon Unified Messaging Gateway.',
  );
  const [testTemplateId, setTestTemplateId] = useState('');
  const [testSending, setTestSending] = useState(false);
  const [testError, setTestError] = useState('');

  const badProviders = providers.filter((p) => p.status !== 'Connected');

  const resolveProviderForApp = (appName: string, channel: ChannelId) => {
    const appObj = apps.find((a) => a.name === appName || a.id === appName);
    const boundIds = appObj?.bindings?.[channel] || [];
    for (const bid of boundIds) {
      const found = providers.find((p) => p.id === bid && p.channel === channel);
      if (found) return found;
    }
    return providers.find((p) => p.channel === channel);
  };

  const homeTestProvider =
    providers.find((p) => p.channel === testChannel) ||
    resolveProviderForApp(apps[0]?.name || '', testChannel);
  const homeTwilioTrial = testChannel === 'sms' && isTwilioSmsProvider(homeTestProvider);

  const renderWithVars = (text: string, vars: Record<string, string>) => {
    return text.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (_match, key) => {
      return vars[key] !== undefined && vars[key] !== '' ? vars[key]! : `{{${key}}}`;
    });
  };

  const handleSelectTestTemplate = (tplId: string) => {
    setSelectedTemplateId(tplId);
    if (!tplId) {
      setTemplateVars({});
      return;
    }
    const tpl = allTemplates.find((t) => t.id === tplId);
    if (!tpl) return;
    if (tpl.subject) setTestSubject(tpl.subject);
    if (tpl.body) setTestBody(tpl.body);
    if (tpl.dlt_id) setTestTemplateId(tpl.dlt_id);
    else setTestTemplateId(tpl.id);

    const detected = new Set<string>(tpl.variables || []);
    const regex = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
    for (const src of [tpl.subject || '', tpl.body || '']) {
      let m: RegExpExecArray | null;
      while ((m = regex.exec(src)) !== null) {
        if (m[1]) detected.add(m[1]);
      }
    }
    const nextVars: Record<string, string> = {};
    detected.forEach((v) => {
      nextVars[v] = templateVars[v] || '';
    });
    setTemplateVars(nextVars);
  };

  const handleTestSend = async (e: React.FormEvent) => {
    e.preventDefault();
    setTestError('');
    if (!testTo.trim()) {
      setTestError('Please enter a recipient email or phone number.');
      return;
    }

    const matchingProvider =
      providers.find((p) => p.channel === testChannel) ||
      resolveProviderForApp(apps[0]?.name || '', testChannel);
    if (!matchingProvider) {
      setTestError(
        `No ${CHANNELS[testChannel].name} provider connected yet. Connect one in Channels first.`,
      );
      return;
    }

    setTestSending(true);
    try {
      const finalSubject =
        testChannel === 'email'
          ? renderWithVars(testSubject.trim(), templateVars) || undefined
          : undefined;
      const finalBody = renderWithVars(testBody.trim(), templateVars) || undefined;
      const res = await adminClient.testSendProvider(matchingProvider.id, {
        to: testTo.trim(),
        subject: finalSubject,
        body: finalBody,
        template_id: testTemplateId.trim() || undefined,
        variables: Object.keys(templateVars).length > 0 ? templateVars : undefined,
      });
      if (res.ok) {
        toast(`Dispatched via ${matchingProvider.name} (${res.latency_ms}ms)`);
        setShowTestModal(false);
        setTestTo('');
        void queryClient.invalidateQueries({ queryKey: ['messages'] });
        void queryClient.invalidateQueries({ queryKey: ['stats'] });
        void queryClient.invalidateQueries({ queryKey: ['providers'] });
      } else {
        setTestError(res.error || 'Test send failed');
      }
    } catch (err: any) {
      setTestError(err.message || 'Failed to dispatch test');
    } finally {
      setTestSending(false);
    }
  };

  return (
    <div>
      {/* Hero Command Center Header */}
      <div className="flex gap-3 items-end justify-between mb-6 flex-wrap">
        <div>
          <div className="inline-flex items-center gap-2 px-2.5 py-1 rounded-full bg-accent-soft text-accent text-xs font-semibold mb-2">
            <span>⚡ Unified Developer Messaging Layer</span>
          </div>
          <h1 className="text-2xl font-bold tracking-tight text-text m-0 mb-1">
            Zyphon Command Center
          </h1>
          <div className="text-muted text-sm">
            One clean API between your applications and every Email, India DLT SMS, and WhatsApp provider.
          </div>
        </div>
        <div className="flex items-center gap-2.5">
          <Button variant="default" onClick={() => router.push('/channels')}>
            Configure Providers
          </Button>
          <Button
            variant="primary"
            onClick={() => {
              setTestError('');
              setSelectedTemplateId('');
              setTemplateVars({});
              const resolved =
                providers.find((p) => p.channel === testChannel) ||
                resolveProviderForApp(apps[0]?.name || '', testChannel);
              if (testChannel === 'sms' && isTwilioSmsProvider(resolved)) {
                const trialTpl =
                  String(resolved?.config?.default_template || '') ||
                  String(resolved?.config?.template_id || '') ||
                  'sms_2fa';
                setTestBody(trialTpl);
                setTestTemplateId(trialTpl);
              }
              setShowTestModal(true);
            }}
          >
            + Send Test Message
          </Button>
        </div>
      </div>

      {/* Live Message Routing Bridge: Per-Application Routes */}
      <div className="zy-card-3d p-5 mb-5">
        <div className="flex items-center justify-between mb-3.5 flex-wrap gap-2 pb-3 border-b border-line">
          <div className="flex items-center gap-2.5 flex-wrap">
            <span className="text-xs font-semibold uppercase tracking-wider text-muted">
              Live Message Routing Bridge
            </span>
            <Badge tone="accent" title={`${apps.length} client applications`}>
              {formatCount(apps.length)} {apps.length === 1 ? 'app' : 'apps'}
            </Badge>
            <span className="text-muted text-xs">→</span>
            <Badge tone="ok">Zyphon Router Active</Badge>
            <span className="text-muted text-xs">→</span>
            <Badge tone={providers.length > 0 ? 'ok' : 'warn'} title={`${providers.length} providers`}>
              {formatCount(providers.length)} {providers.length === 1 ? 'provider' : 'providers'}
            </Badge>
          </div>
          <div className="flex items-center gap-2">
            <Link
              href="/apps"
              className="text-xs font-medium text-accent hover:underline no-underline"
            >
              Manage App Routes ({formatCount(apps.length)}) →
            </Link>
          </div>
        </div>

        {apps.length === 0 ? (
          <div className="py-6 text-center text-sm text-muted">
            No client applications registered yet.{' '}
            <Link href="/apps" className="text-accent font-semibold underline">
              Create your first app →
            </Link>
          </div>
        ) : (
          <div className="space-y-2 max-h-72 overflow-y-auto pr-1">
            {apps.slice(0, 8).map((app) => {
              const allowed = app.channels || [];
              return (
                <div
                  key={app.id}
                  className="grid grid-cols-1 md:grid-cols-[minmax(160px,1fr)_auto_auto_auto_minmax(220px,1.5fr)] items-center gap-2.5 px-3.5 py-2.5 rounded-[var(--r)] border border-line bg-bg hover:border-accent transition-colors"
                >
                  {/* 1. App Node */}
                  <div className="flex items-center gap-2 min-w-0">
                    <span
                      className={`w-2 h-2 rounded-full flex-none ${
                        app.enabled !== false ? 'bg-ok' : 'bg-muted'
                      }`}
                    />
                    <Link
                      href="/apps"
                      className="font-semibold text-sm text-text truncate no-underline hover:text-accent"
                    >
                      {app.name}
                    </Link>
                  </div>

                  <span className="hidden md:inline text-muted text-xs font-mono">──▶</span>

                  {/* 2. Zyphon Router Node */}
                  <div className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded border border-accent/40 bg-accent-soft/30 text-xs font-mono text-accent w-fit">
                    <span>⚡ Zyphon</span>
                  </div>

                  <span className="hidden md:inline text-muted text-xs font-mono">──▶</span>

                  {/* 3. Bound Channel Providers */}
                  <div className="flex items-center gap-1.5 flex-wrap md:justify-end">
                    {allowed.length === 0 ? (
                      <Link
                        href="/apps"
                        className="text-xs font-mono text-warn underline"
                      >
                        No channels enabled
                      </Link>
                    ) : (
                      allowed.map((ch) => {
                        const boundIds = Array.from(new Set(app.bindings?.[ch] || []));
                        const boundNames = boundIds
                          .map((id) => providers.find((p) => p.id === id)?.name || id)
                          .filter(Boolean);
                        const isBound = boundNames.length > 0;
                        return (
                          <Link
                            key={ch}
                            href={isBound ? '/channels' : '/apps'}
                            className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-mono border no-underline transition-colors ${
                              isBound
                                ? 'bg-surface border-line text-text hover:border-accent'
                                : 'bg-warn-soft border-warn/40 text-warn hover:border-warn'
                            }`}
                          >
                            <span className="uppercase text-[10px] opacity-75">{ch}:</span>
                            <b>{isBound ? boundNames.join(' → ') : 'Unbound (Bind →)'}</b>
                          </Link>
                        );
                      })
                    )}
                  </div>
                </div>
              );
            })}
            {apps.length > 8 && (
              <div className="pt-1 text-right">
                <Link href="/apps" className="text-xs font-semibold text-accent hover:underline">
                  View all {formatCount(apps.length)} applications →
                </Link>
              </div>
            )}
          </div>
        )}
      </div>

      {/* 4 3D Stat Cards */}
      <div className="grid grid-cols-[repeat(auto-fit,minmax(190px,1fr))] gap-3.5 mb-5">
        <div className="zy-stat-3d p-[18px]">
          <span className="text-muted text-[13px]">Dispatched today</span>
          <b
            className="block text-[28px] font-bold tracking-tight text-text mt-0.5 font-mono"
            title={String(stats ? stats.sent_today : 0)}
          >
            {formatCount(stats ? stats.sent_today : 0)}
          </b>
        </div>
        <div className="zy-stat-3d p-[18px]">
          <span className="text-muted text-[13px]">Delivery success rate</span>
          <b className="block text-[28px] font-bold tracking-tight text-ok mt-0.5 font-mono">
            {stats && stats.success_rate !== null ? `${stats.success_rate}%` : '—'}
          </b>
        </div>
        <div className="zy-stat-3d p-[18px]">
          <span className="text-muted text-[13px]">Failed dispatches</span>
          <b
            className="block text-[28px] font-bold tracking-tight text-danger mt-0.5 font-mono"
            title={String(stats ? stats.failed_today : 0)}
          >
            {formatCount(stats ? stats.failed_today : 0)}
          </b>
        </div>
        <div className="zy-stat-3d p-[18px]">
          <span className="text-muted text-[13px]">Connected applications</span>
          <b
            className="block text-[28px] font-bold tracking-tight text-text mt-0.5 font-mono"
            title={String(stats ? stats.active_apps : apps.length)}
          >
            {formatCount(stats ? stats.active_apps : apps.length)}
          </b>
        </div>
      </div>

      {/* Connected Channel Providers Card */}
      <div className="zy-card-3d p-[18px] mb-5">
        <div className="flex items-center justify-between mb-3 flex-wrap gap-2">
          <div>
            <h2 className="text-base font-semibold text-text m-0">Connected Channel Providers</h2>
            <div className="text-muted text-xs">
              Active providers and the applications bound to them.
            </div>
          </div>
          <Link
            href="/channels"
            className="text-[13px] font-medium px-2.5 py-1 rounded-[var(--r)] border border-line bg-surface text-text hover:bg-surface-2 transition-colors no-underline"
          >
            Manage Channels →
          </Link>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          {PRIMARY_CHANNELS.map((ch) => {
            const chProviders = providers.filter((p) => p.channel === ch);
            return (
              <div
                key={ch}
                className="rounded-[var(--r)] border border-line bg-bg p-3.5 flex flex-col justify-between gap-2"
              >
                <div className="flex items-center justify-between">
                  <span className="font-semibold text-sm text-text">{CHANNELS[ch].name}</span>
                  <Badge tone={chProviders.length > 0 ? 'ok' : 'muted'}>
                    {chProviders.length ? `${chProviders.length} connected` : 'Unconfigured'}
                  </Badge>
                </div>
                {chProviders.length > 0 ? (
                  <div className="text-xs space-y-1.5 mt-1">
                    {chProviders.map((p) => {
                      const boundApps = Array.from(
                        new Set([
                          ...(p.used_by || []),
                          ...apps
                            .filter((a) => (a.bindings?.[ch] || []).includes(p.id))
                            .map((a) => a.name),
                        ]),
                      );
                      return (
                        <div
                          key={p.id}
                          className="flex items-center justify-between gap-2 py-1 border-t border-line first:border-0"
                        >
                          <b className="text-text font-mono truncate">{p.name}</b>
                          <span className="text-muted truncate">
                            {boundApps.length > 0 ? boundApps.join(', ') : 'Unassigned'}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                ) : (
                  <div className="text-xs text-muted">No provider connected yet.</div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Recent Messages Card (Now Live & Functional) */}
      <div className="zy-card-3d p-[18px] mb-4">
        <div className="flex items-center justify-between mb-3 flex-wrap gap-2">
          <div>
            <h2 className="text-base font-semibold text-text m-0">Recent Application Messages</h2>
            <div className="text-xs text-muted">
              Click any message to inspect content, or open Messages for Gmail / SMS / WhatsApp views.
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Link
              href="/messages"
              className="text-[13px] font-medium px-3 py-1 rounded-[var(--r)] border border-line bg-surface text-text hover:bg-surface-2 transition-colors no-underline"
            >
              Open Inbox & Views →
            </Link>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full border-collapse">
            <thead>
              <tr className="border-b border-line text-left text-muted text-[12.5px] font-medium">
                <th className="py-2 px-3">When</th>
                <th className="py-2 px-3">Application</th>
                <th className="py-2 px-3">Channel</th>
                <th className="py-2 px-3">Recipient</th>
                <th className="py-2 px-3">Subject / Content</th>
                <th className="py-2 px-3">Status</th>
                <th className="py-2 px-3">Sent via</th>
              </tr>
            </thead>
            <tbody>
              {messages.length > 0 ? (
                messages.map((m) => (
                  <tr
                    key={m.id}
                    onClick={() => setSelectedMessage(m)}
                    className="border-b border-line last:border-0 hover:bg-surface-2 cursor-pointer transition-colors"
                  >
                    <td className="py-3 px-3 text-muted text-xs font-mono">{ago(m.ts)}</td>
                    <td className="py-3 px-3">
                      <Badge tone="accent">{m.app}</Badge>
                    </td>
                    <td className="py-3 px-3 text-text font-medium">
                      {CHANNELS[m.channel]?.name || m.channel}
                    </td>
                    <td className="py-3 px-3 text-text font-mono text-[13px]">{m.to}</td>
                    <td className="py-3 px-3 text-muted text-xs max-w-[240px] truncate">
                      {m.subject ? <b className="text-text">{m.subject}</b> : m.body || m.note || '—'}
                    </td>
                    <td className="py-3 px-3">
                      <span
                        className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold ${
                          m.status === 'delivered' || m.status === 'sent'
                            ? 'bg-ok-soft text-ok'
                            : m.status === 'failed'
                            ? 'bg-danger-soft text-danger'
                            : 'bg-warn-soft text-warn'
                        }`}
                      >
                        {m.status.charAt(0).toUpperCase() + m.status.slice(1)}
                      </span>
                    </td>
                    <td className="py-3 px-3 text-muted font-mono text-xs">
                      {m.via || '—'} ({m.ms}ms)
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={7} className="py-8 text-center text-muted">
                    No messages yet. Click <b>+ Send Test Message</b> to dispatch one now.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Needs Attention Card */}
      {badProviders.length > 0 && (
        <div className="zy-card-3d p-[18px]">
          <h2 className="text-base font-semibold text-text m-0 mb-2">Needs attention</h2>
          <div className="divide-y divide-line">
            {badProviders.map((p) => (
              <div key={p.id} className="flex items-center gap-2.5 py-2.5 flex-wrap">
                <Badge tone={p.status === 'Paused briefly' ? 'warn' : 'danger'}>
                  {p.status}
                </Badge>
                <b className="text-text font-semibold">{p.name}</b>
                <span className="text-muted text-[13px] flex-1 min-w-[200px]">
                  {CHANNELS[p.channel]?.name || p.channel} · failover active if backup provider is configured.
                </span>
                <Button size="sm" onClick={() => router.push('/channels')}>
                  Open Channels
                </Button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Message Detail Drawer */}
      {selectedMessage && (
        <>
          <div
            onClick={() => setSelectedMessage(null)}
            className="fixed inset-0 bg-overlay z-30 transition-opacity"
          />
          <aside className="fixed top-0 right-0 h-full w-[min(560px,100vw)] bg-bg border-l border-line z-40 overflow-y-auto p-[26px] shadow-card">
            <div className="flex justify-between items-center mb-3">
              <Badge tone="accent">{selectedMessage.app}</Badge>
              <button
                onClick={() => setSelectedMessage(null)}
                className="text-muted hover:text-text text-[13px] font-medium px-2 py-1 rounded cursor-pointer border-0 bg-transparent"
              >
                Close ✕
              </button>
            </div>

            <h1 className="text-xl font-bold tracking-tight text-text mb-1">
              {CHANNELS[selectedMessage.channel]?.name} to {selectedMessage.to}
            </h1>
            <div className="flex items-center gap-2.5 my-2 mb-4 flex-wrap">
              <Badge
                tone={
                  selectedMessage.status === 'delivered' || selectedMessage.status === 'sent'
                    ? 'ok'
                    : 'danger'
                }
              >
                {selectedMessage.status.toUpperCase()}
              </Badge>
              <span className="text-muted text-[13px] font-mono">
                {new Date(selectedMessage.ts).toLocaleString()} · {selectedMessage.ms} ms
              </span>
            </div>

            {(selectedMessage.subject || selectedMessage.body) && (
              <div className="zy-card-3d p-4 mb-4">
                {selectedMessage.subject && (
                  <div className="font-semibold text-sm text-text mb-1.5">
                    {selectedMessage.subject}
                  </div>
                )}
                <div className="text-sm text-muted whitespace-pre-wrap">
                  {selectedMessage.body || 'Dispatched via Zyphon Gateway.'}
                </div>
              </div>
            )}

            <div className="zy-card-3d p-[18px] mb-4">
              <h2 className="text-base font-semibold text-text mb-3">Delivery Trace</h2>
              <div className="border-l-2 border-line pl-4 ml-1 space-y-4">
                <div className="relative text-[13px] text-text">
                  <div className="font-medium">Accepted by Zyphon</div>
                  <div className="text-muted text-xs mt-0.5">
                    From application <b className="text-text">{selectedMessage.app}</b>
                  </div>
                </div>

                {selectedMessage.att.map((a, i) => {
                  const matched = providers.find((p) => p.id === a.p);
                  const providerLabel = matched?.name || a.p;
                  return (
                    <div
                      key={i}
                      className={`relative text-[13px] ${a.ok ? 'text-ok' : 'text-danger'}`}
                    >
                      {a.ok ? (
                        <>
                          <div className="font-medium">
                            Accepted by provider · <b>{providerLabel}</b>
                          </div>
                          {matched && matched.name !== a.p ? (
                            <div className="text-muted text-xs font-mono mt-0.5">{a.p}</div>
                          ) : null}
                        </>
                      ) : (
                        <>
                          <div className="font-medium">
                            Provider rejected · <b>{providerLabel}</b>
                          </div>
                          {matched && matched.name !== a.p ? (
                            <div className="text-muted text-xs font-mono mt-0.5">{a.p}</div>
                          ) : null}
                          <div className="mt-1.5 text-xs leading-relaxed whitespace-pre-wrap break-words rounded-[var(--r)] border border-danger/30 bg-danger-soft/40 px-2.5 py-2 text-danger">
                            {a.e || 'Unknown provider error'}
                          </div>
                        </>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>

            <div className="text-muted text-xs font-mono">Message ID {selectedMessage.id}</div>
          </aside>
        </>
      )}

      {/* Live Test Dispatch Modal */}
      {showTestModal && (
        <div className="fixed inset-0 bg-overlay z-50 flex items-center justify-center p-4">
          <div className="zy-card-3d bg-surface w-[min(540px,94vw)] p-6 max-h-[92vh] overflow-y-auto">
            <h2 className="text-lg font-semibold text-text mb-1">Send a live test message</h2>
            <p className="text-muted text-[13px] mb-4">
              Tests the connected provider for the selected channel. App attribution is applied
              automatically from bindings.
              {homeTestProvider ? (
                <>
                  {' '}
                  Using <b>{homeTestProvider.name}</b>.
                </>
              ) : null}
            </p>

            <form onSubmit={handleTestSend} className="space-y-3.5">
              <div>
                <label className="block text-sm font-medium text-text mb-1.5">Channel</label>
                <div className="grid grid-cols-3 gap-2">
                  {PRIMARY_CHANNELS.map((ch) => (
                    <button
                      key={ch}
                      type="button"
                      onClick={() => {
                        setTestChannel(ch);
                        setSelectedTemplateId('');
                        setTemplateVars({});
                        const resolved =
                          providers.find((p) => p.channel === ch) ||
                          resolveProviderForApp(apps[0]?.name || '', ch);
                        if (ch === 'sms' && isTwilioSmsProvider(resolved)) {
                          const trialTpl =
                            String(resolved?.config?.default_template || '') ||
                            String(resolved?.config?.template_id || '') ||
                            'sms_2fa';
                          setTestBody(trialTpl);
                          setTestTemplateId(trialTpl);
                        }
                      }}
                      className={`py-2 px-3 rounded-[var(--r)] border text-sm font-medium transition-colors cursor-pointer ${
                        testChannel === ch
                          ? 'border-accent bg-accent-soft text-text'
                          : 'border-line bg-bg text-muted hover:text-text'
                      }`}
                    >
                      {CHANNELS[ch].name}
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-text mb-1.5">
                  Template <span className="text-muted font-normal">(optional — choose a saved template)</span>
                </label>
                <Select
                  value={selectedTemplateId}
                  onChange={(e) => handleSelectTestTemplate(e.target.value)}
                >
                  <option value="">Custom message (no template)</option>
                  {allTemplates
                    .filter((t) => t.channel === testChannel)
                    .map((t) => (
                      <option key={t.id} value={t.id}>
                        {t.name} ({t.id})
                      </option>
                    ))}
                </Select>
              </div>

              {Object.keys(templateVars).length > 0 && (
                <div className="p-3 rounded-[var(--r)] border border-line bg-bg space-y-2">
                  <div className="text-xs font-semibold uppercase tracking-wider text-muted">
                    Template Variables
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                    {Object.keys(templateVars).map((varKey) => (
                      <label key={varKey} className="block text-xs text-muted">
                        {`{{${varKey}}}`}
                        <Input
                          className="mt-1"
                          placeholder={`Value for ${varKey}`}
                          value={templateVars[varKey] || ''}
                          onChange={(e) =>
                            setTemplateVars((prev) => ({ ...prev, [varKey]: e.target.value }))
                          }
                        />
                      </label>
                    ))}
                  </div>
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-text mb-1.5">
                  {testChannel === 'email' ? 'Recipient email' : 'Recipient mobile (+91...)'}
                </label>
                <Input
                  type="text"
                  placeholder={testChannel === 'email' ? 'you@company.in' : '+919876543210'}
                  value={testTo}
                  onChange={(e) => setTestTo(e.target.value)}
                  autoFocus
                />
              </div>

              {testChannel === 'email' && (
                <div>
                  <label className="block text-sm font-medium text-text mb-1.5">Subject</label>
                  <Input
                    type="text"
                    value={testSubject}
                    onChange={(e) => setTestSubject(e.target.value)}
                  />
                </div>
              )}

              {testChannel !== 'email' && !homeTwilioTrial && (
                <div>
                  <label className="block text-sm font-medium text-text mb-1.5">
                    DLT / WhatsApp Template ID{' '}
                    <span className="text-muted font-normal">(optional if set on provider)</span>
                  </label>
                  <Input
                    type="text"
                    placeholder={
                      testChannel === 'sms'
                        ? '19-digit DLT Template ID or Flow ID'
                        : 'Approved WhatsApp template name'
                    }
                    value={testTemplateId}
                    onChange={(e) => setTestTemplateId(e.target.value)}
                  />
                </div>
              )}

              {homeTwilioTrial ? (
                <div className="p-3 rounded-[var(--r)] border border-warn/40 bg-warn-soft/30 space-y-2">
                  <div className="text-xs leading-relaxed text-text">
                    Twilio trial accounts require a template key as Body (same as Console → Try out
                    SMS), not free-form text. Recipient must be verified on the trial account.
                  </div>
                  <label className="block text-sm font-medium text-text">
                    Twilio trial template
                    <Select
                      className="mt-1.5"
                      value={
                        TWILIO_TRIAL_SMS_TEMPLATES.some((t) => t.value === testBody)
                          ? testBody
                          : 'sms_2fa'
                      }
                      onChange={(e) => {
                        setTestBody(e.target.value);
                        setTestTemplateId(e.target.value);
                      }}
                    >
                      {TWILIO_TRIAL_SMS_TEMPLATES.map((t) => (
                        <option key={t.value} value={t.value}>
                          {t.label}
                        </option>
                      ))}
                    </Select>
                  </label>
                </div>
              ) : (
                <div>
                  <label className="block text-sm font-medium text-text mb-1.5">Message body</label>
                  <textarea
                    rows={3}
                    value={testBody}
                    onChange={(e) => setTestBody(e.target.value)}
                    className="w-full bg-bg border border-line rounded-[var(--r)] px-3 py-2 text-text text-sm focus:border-accent focus:outline-none"
                  />
                </div>
              )}

              {testError && <div className="text-danger text-[13px]">{testError}</div>}

              <div className="flex justify-end gap-2.5 pt-2">
                <Button type="button" variant="ghost" onClick={() => setShowTestModal(false)}>
                  Cancel
                </Button>
                <Button type="submit" variant="primary" disabled={testSending}>
                  {testSending ? 'Sending…' : 'Send now'}
                </Button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
