import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { toast } from 'sonner';
import {
  ArrowUpCircleIcon, ArrowDownCircleIcon, DevicePhoneMobileIcon,
  ClockIcon, CheckCircleIcon, XCircleIcon, BellAlertIcon, ChatBubbleLeftEllipsisIcon,
  BanknotesIcon,
} from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
import type { SmsWalletBalance, SmsWalletLog, SmsSettings } from '../types';
import { usePaymentConfig } from '../hooks/usePaymentConfig';
import { formatRial, formatNumber, formatDateTime, tomanToRial } from '../lib/utils';
import Modal from '../components/ui/Modal';
import Pagination from '../components/ui/Pagination';
import SearchableSelect from '../components/ui/SearchableSelect';
import PageHeader from '../components/ui/PageHeader';
import FeatureGate from '../components/ui/FeatureGate';

const chargeSchema = z.object({
  amount_rials: z.coerce.number().min(1000, 'حداقل مبلغ ۱٬۰۰۰ تومان است'),
});
type ChargeForm = z.infer<typeof chargeSchema>;

const EMPTY_LOGS: SmsWalletLog[] = [];

const REMINDER_HOUR_OPTIONS = [1, 2, 3, 4, 6, 12, 24, 48];

const POST_VISIT_VARS: { key: string; label: string }[] = [
  { key: 'patient_name', label: 'نام بیمار' },
  { key: 'doctor', label: 'نام پزشک' },
  { key: 'clinic', label: 'نام کلینیک' },
  { key: 'date', label: 'تاریخ ویزیت' },
];

function SmsWalletPageInner() {
  const qc = useQueryClient();
  const [chargeOpen, setChargeOpen] = useState(false);
  const [gateway, setGateway] = useState<'mellat' | 'sep'>('mellat');
  const [logPage, setLogPage] = useState(1);

  const { data: balanceData, isLoading: balanceLoading } = useQuery<ApiResponse<SmsWalletBalance>>({
    queryKey: ['sms-wallet-balance'],
    queryFn: () => api.get('/api/v1/sms/wallet/balance'),
  });

  const { data: logsData, isLoading: logsLoading } = useQuery<PaginatedResponse<SmsWalletLog>>({
    queryKey: ['sms-wallet-logs', logPage],
    queryFn: () => api.get(`/api/v1/sms/wallet/logs?page=${logPage}&limit=20`),
  });

  const { data: settingsData } = useQuery<ApiResponse<SmsSettings>>({
    queryKey: ['sms-settings'],
    queryFn: () => api.get('/api/v1/sms/settings'),
  });

  const { isTestMode } = usePaymentConfig();

  const balance     = balanceData?.data;
  const logs        = logsData?.data ?? EMPTY_LOGS;
  const total       = logsData?.meta?.totalRecords ?? 0;
  const settings    = settingsData?.data;

  const chargeForm = useForm<ChargeForm>({ resolver: zodResolver(chargeSchema) });
  const watchAmount = chargeForm.watch('amount_rials');

  const chargeMutation = useMutation({
    mutationFn: ({ amount_rials }: ChargeForm) =>
      api.post<{ data: { payment_url: string } }>('/api/v1/sms/wallet/charge', {
        gateway, amount_rials: tomanToRial(amount_rials),
        frontend_address: `${window.location.origin}${window.location.pathname}`,
      }),
    onSuccess: (res: any) => {
      const url = res?.data?.pay_url ?? res?.data?.redirect_url ?? res?.data?.payment_url;
      if (url) window.location.href = url;
      else toast.error('خطا در دریافت لینک پرداخت');
    },
    onError: (e: any) => toast.error(e.message),
  });

  const [localSettings, setLocalSettings] = useState<SmsSettings | null>(null);
  const currentSettings = localSettings ?? settings;

  // با هر بار تازه‌شدن داده‌ی سرور، ویرایش محلی صفر شود تا وضعیت واقعی (مثل وضعیت تأیید متن) نمایش داده شود.
  useEffect(() => { setLocalSettings(null); }, [settingsData]);

  const saveMutation = useMutation({
    mutationFn: (body: SmsSettings) => api.patch('/api/v1/sms/settings', body),
    onSuccess: () => {
      setLocalSettings(null);
      qc.invalidateQueries({ queryKey: ['sms-settings'] });
      toast.success('تنظیمات ذخیره شد');
    },
    onError: (e: any) => toast.error(e.message),
  });

  const smsCount   = balance?.estimated_sms_count ?? 0;
  const isLowBalance = smsCount < 10;

  return (
    <>
      <PageHeader title="کیف پول پیامک" description="مدیریت موجودی و تنظیمات ارسال پیامک" />

      {/* ردیف بالا: موجودی + آمار */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16, marginBottom: 20 }}>
        {/* کارت موجودی — gradient */}
        <div style={{
          background: 'linear-gradient(135deg, oklch(0.52 0.22 256), oklch(0.40 0.18 256))',
          borderRadius: 'var(--r)', padding: '24px 24px 20px',
          color: '#fff', position: 'relative', overflow: 'hidden', gridColumn: '1 / 2',
        }}>
          <div style={{
            position: 'absolute', top: -30, left: -30,
            width: 140, height: 140, borderRadius: '50%',
            background: 'rgba(255,255,255,0.06)',
          }} />
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <div style={{ fontSize: 13, opacity: 0.85 }}>موجودی کیف پول</div>
            <span style={{
              fontSize: 11.5, fontWeight: 600, padding: '3px 10px', borderRadius: 20,
              background: isLowBalance ? 'rgba(239,68,68,0.3)' : 'rgba(34,197,94,0.3)',
              border: `1px solid ${isLowBalance ? 'rgba(239,68,68,0.5)' : 'rgba(34,197,94,0.5)'}`,
            }}>
              {isLowBalance ? 'موجودی کم' : 'فعال'}
            </span>
          </div>
          {balanceLoading ? <div style={{ height: 60 }} /> : (
            <>
              <div style={{ fontSize: 34, fontWeight: 800, letterSpacing: '-0.5px', marginBottom: 4 }}>
                {formatRial(balance?.balance_rials ?? 0)}
              </div>
              <div style={{ fontSize: 13, opacity: 0.8, marginBottom: 16 }}>
                معادل {formatNumber(smsCount)} پیامک
                {balance?.sms_price_rials ? ` (هر پیامک ${formatRial(balance.sms_price_rials)})` : ''}
              </div>
              <div style={{ background: 'rgba(255,255,255,0.2)', borderRadius: 8, height: 6, marginBottom: 16, overflow: 'hidden' }}>
                <div style={{
                  height: '100%', borderRadius: 8,
                  width: `${Math.min(100, (smsCount / 500) * 100)}%`,
                  background: isLowBalance ? '#ef4444' : 'rgba(255,255,255,0.85)',
                  transition: 'width 0.4s ease',
                }} />
              </div>
              <button
                style={{
                  background: '#fff', color: 'var(--primary)', border: 'none', borderRadius: 8,
                  padding: '8px 18px', fontWeight: 700, fontSize: 13.5, cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}
                onClick={() => setChargeOpen(true)}
              >
                <DevicePhoneMobileIcon style={{ width: 16 }} />
                شارژ کیف پول
              </button>
            </>
          )}
        </div>

        {/* آمار پیامک */}
        <div className="card" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '20px 24px', gap: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--primary-subtle)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <ChatBubbleLeftEllipsisIcon style={{ width: 20, color: 'var(--primary)' }} />
            </div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 700 }}>{formatNumber(smsCount)}</div>
              <div style={{ fontSize: 12.5, color: 'var(--text-3)' }}>پیامک باقی‌مانده</div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: 'oklch(0.96 0.02 162)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <ClockIcon style={{ width: 20, color: 'oklch(0.45 0.17 162)' }} />
            </div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 700 }}>
                {currentSettings?.reminder_enabled ? `${currentSettings.reminder_hours_before} ساعت` : '—'}
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--text-3)' }}>یادآوری قبل از نوبت</div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--warning-bg)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <BanknotesIcon style={{ width: 20, color: 'var(--warning)' }} />
            </div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 700 }}>{formatRial(balance?.sms_price_rials ?? 0)}</div>
              <div style={{ fontSize: 12.5, color: 'var(--text-3)' }}>قیمت هر پیامک</div>
            </div>
          </div>
        </div>

        {/* وضعیت سرویس */}
        <div className="card" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '20px 24px', gap: 16 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-2)', marginBottom: 4 }}>وضعیت سرویس‌ها</div>
          {[
            { label: 'یادآوری نوبت', on: currentSettings?.reminder_enabled ?? false },
            { label: 'پیامک بعد از ویزیت', on: currentSettings?.post_visit_enabled ?? false },
          ].map(({ label, on }) => (
            <div key={label} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 13, color: 'var(--text-2)' }}>{label}</span>
              <span style={{
                fontSize: 11.5, fontWeight: 600, padding: '2px 10px', borderRadius: 20,
                background: on ? 'oklch(0.94 0.05 162)' : 'var(--surface-2)',
                color: on ? 'oklch(0.38 0.14 162)' : 'var(--text-3)',
              }}>
                {on ? 'فعال' : 'غیرفعال'}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* تنظیمات ارسال — full width */}
      <div className="card" style={{ marginBottom: 20 }}>
        <div style={{
          fontWeight: 600, padding: '14px 20px', borderBottom: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <BellAlertIcon style={{ width: 17, color: 'var(--primary)' }} />
          تنظیمات ارسال پیامک
        </div>
        <div style={{ padding: '20px' }}>
          {currentSettings ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>

              {/* ردیف: یادآوری قبل از نوبت */}
              <div style={{
                display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16,
                padding: '16px 0', borderBottom: '1px solid var(--border)',
              }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                  <div style={{ width: 36, height: 36, borderRadius: 9, background: 'var(--primary-subtle)', display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 2 }}>
                    <ClockIcon style={{ width: 18, color: 'var(--primary)' }} />
                  </div>
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 14 }}>یادآوری قبل از نوبت</div>
                    <div style={{ color: 'var(--text-3)', fontSize: 12.5, marginTop: 3 }}>پیامک یادآور به بیمار چند ساعت قبل از وقت نوبت ارسال می‌شود</div>
                    {currentSettings.reminder_enabled && (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12 }}>
                        <label style={{ fontSize: 13, color: 'var(--text-2)', whiteSpace: 'nowrap' }}>ارسال</label>
                        <div style={{ width: 150 }}>
                          <SearchableSelect
                            options={REMINDER_HOUR_OPTIONS.map((h) => ({ value: h, label: `${h} ساعت قبل` }))}
                            value={currentSettings.reminder_hours_before}
                            onChange={(v) => setLocalSettings({ ...currentSettings, reminder_hours_before: Number(v) || 0 })}
                            placeholder="ساعت"
                          />
                        </div>
                      </div>
                    )}
                  </div>
                </div>
                <label className="switch" style={{ marginTop: 4, flexShrink: 0 }}>
                  <input
                    type="checkbox"
                    checked={currentSettings.reminder_enabled}
                    onChange={() => setLocalSettings({ ...currentSettings, reminder_enabled: !currentSettings.reminder_enabled })}
                  />
                  <span className="switch-track"><span className="switch-thumb" /></span>
                </label>
              </div>

              {/* ردیف: پیامک بعد از ویزیت */}
              <div style={{ padding: '16px 0' }}>
                {/* header ردیف */}
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ width: 36, height: 36, borderRadius: 9, background: 'oklch(0.96 0.02 162)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                      <ChatBubbleLeftEllipsisIcon style={{ width: 18, color: 'oklch(0.45 0.17 162)' }} />
                    </div>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 14 }}>پیامک بعد از ویزیت</div>
                      <div style={{ color: 'var(--text-3)', fontSize: 12.5, marginTop: 3 }}>متن تشکر پس از پایان مراجعه برای بیمار ارسال می‌شود</div>
                    </div>
                  </div>
                  <label className="switch" style={{ flexShrink: 0 }}>
                    <input
                      type="checkbox"
                      checked={currentSettings.post_visit_enabled}
                      onChange={() => setLocalSettings({ ...currentSettings, post_visit_enabled: !currentSettings.post_visit_enabled })}
                    />
                    <span className="switch-track"><span className="switch-thumb" /></span>
                  </label>
                </div>

                {/* محتوای باز‌شونده */}
                {currentSettings.post_visit_enabled && (
                  <div style={{
                    marginTop: 16,
                    marginRight: 48,
                    padding: 16,
                    background: 'var(--surface-2)',
                    borderRadius: 10,
                    border: '1px solid var(--border)',
                  }}>
                    <div style={{ marginBottom: 12 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-2)', marginBottom: 8 }}>متن پیامک</div>
                      <textarea
                        value={currentSettings.post_visit_text_pending ?? currentSettings.post_visit_text ?? ''}
                        onChange={(e) => setLocalSettings({ ...currentSettings, post_visit_text: e.target.value })}
                        rows={4}
                        placeholder="ممنون از مراجعه شما..."
                        style={{
                          display: 'block',
                          width: '100%',
                          boxSizing: 'border-box',
                          resize: 'vertical',
                          padding: '10px 12px',
                          borderRadius: 8,
                          border: '1px solid var(--border)',
                          background: 'var(--surface-1)',
                          fontSize: 13,
                          lineHeight: 1.7,
                          color: 'var(--text-1)',
                          fontFamily: 'inherit',
                          direction: 'rtl',
                        }}
                      />
                      <div style={{ marginTop: 10 }}>
                        <div style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 6 }}>
                          برای افزودن، روی پارامتر کلیک کنید:
                        </div>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                          {POST_VISIT_VARS.map(({ key, label }) => (
                            <button
                              key={key}
                              type="button"
                              onClick={() => setLocalSettings({
                                ...currentSettings,
                                post_visit_text: `${currentSettings.post_visit_text_pending ?? currentSettings.post_visit_text ?? ''}{${key}}`,
                              })}
                              style={{
                                fontSize: 12, fontWeight: 600,
                                padding: '4px 10px', borderRadius: 16, cursor: 'pointer',
                                background: 'var(--primary-subtle)', color: 'var(--primary)',
                                border: '1px solid color-mix(in oklch, var(--primary) 30%, transparent)',
                              }}
                            >
                              {label} <span style={{ direction: 'ltr', opacity: 0.7 }}>{`{${key}}`}</span>
                            </button>
                          ))}
                        </div>
                      </div>

                      <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 8 }}>
                        متن پس از تغییر باید توسط ادمین تأیید شود تا فعال گردد
                      </div>
                    </div>

                    {/* وضعیت تأیید */}
                    {currentSettings.post_visit_text_status === 'pending' && (
                      <div style={{
                        display: 'flex', alignItems: 'center', gap: 10,
                        padding: '10px 14px', borderRadius: 8,
                        background: 'var(--warning-bg)', border: '1px solid var(--warning)', fontSize: 13,
                      }}>
                        <ClockIcon style={{ width: 16, color: 'var(--warning)', flexShrink: 0 }} />
                        <span style={{ color: 'var(--warning)' }}>در انتظار تأیید ادمین</span>
                      </div>
                    )}
                    {currentSettings.post_visit_text_status === 'approved' && (
                      <div style={{
                        display: 'flex', alignItems: 'center', gap: 10,
                        padding: '10px 14px', borderRadius: 8,
                        background: 'var(--success-bg)', border: '1px solid var(--success)', fontSize: 13,
                      }}>
                        <CheckCircleIcon style={{ width: 16, color: 'var(--success)', flexShrink: 0 }} />
                        <span style={{ color: 'var(--success)' }}>تأیید شده و فعال است</span>
                      </div>
                    )}
                    {currentSettings.post_visit_text_status === 'rejected' && (
                      <div style={{
                        display: 'flex', alignItems: 'flex-start', gap: 10,
                        padding: '10px 14px', borderRadius: 8,
                        background: 'var(--danger-bg)', border: '1px solid var(--danger)', fontSize: 13,
                      }}>
                        <XCircleIcon style={{ width: 16, color: 'var(--danger)', flexShrink: 0, marginTop: 1 }} />
                        <div style={{ color: 'var(--danger)' }}>
                          <div>متن پیامک رد شد</div>
                          {currentSettings.post_visit_text_reject_reason && (
                            <div style={{ marginTop: 3, fontSize: 12, opacity: 0.85 }}>دلیل: {currentSettings.post_visit_text_reject_reason}</div>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* footer ذخیره */}
              <div style={{ display: 'flex', justifyContent: 'flex-end', paddingTop: 16, borderTop: '1px solid var(--border)' }}>
                <button
                  className="btn primary sm"
                  disabled={saveMutation.isPending}
                  onClick={() => currentSettings && saveMutation.mutate(currentSettings)}
                >
                  {saveMutation.isPending ? 'در حال ذخیره...' : 'ذخیره تنظیمات'}
                </button>
              </div>
            </div>
          ) : (
            <div style={{ color: 'var(--text-3)', fontSize: 13, padding: '8px 0' }}>در حال بارگذاری...</div>
          )}
        </div>
      </div>

      {/* تاریخچه تراکنش‌ها */}
      <div className="card">
        <div style={{
          fontWeight: 600, padding: '14px 16px', borderBottom: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          تاریخچه تراکنش‌ها
          {!logsLoading && total > 0 && (
            <span className="badge gray" style={{ fontSize: 11 }}>{total} تراکنش</span>
          )}
        </div>

        {logsLoading ? (
          <div style={{ color: 'var(--text-3)', fontSize: 13, padding: '16px' }}>در حال بارگذاری...</div>
        ) : logs.length === 0 ? (
          <div style={{ color: 'var(--text-3)', fontSize: 13, padding: '32px 16px', textAlign: 'center' }}>
            تراکنشی ثبت نشده است
          </div>
        ) : (
          <>
            <div className="table-wrap"><table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ background: 'oklch(0.97 0.01 256)', borderBottom: '1px solid var(--border)' }}>
                  <th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>نوع</th>
                  <th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>مبلغ</th>
                  <th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>توضیحات</th>
                  <th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>تاریخ</th>
                </tr>
              </thead>
              <tbody>
                {logs.map((log, idx) => (
                  <tr
                    key={log.uuid}
                    style={{
                      borderBottom: '1px solid var(--border)',
                      background: idx % 2 === 1 ? 'oklch(0.985 0.005 256)' : 'transparent',
                    }}
                  >
                    <td style={{ padding: '11px 16px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        {log.type === 'credit' ? (
                          <ArrowUpCircleIcon style={{ width: 18, color: 'oklch(0.52 0.17 162)', flexShrink: 0 }} />
                        ) : (
                          <ArrowDownCircleIcon style={{ width: 18, color: 'oklch(0.52 0.2 25)', flexShrink: 0 }} />
                        )}
                        <span className={`badge ${log.type === 'credit' ? 'green' : 'red'}`}>
                          {log.type === 'credit' ? 'شارژ' : 'کسر'}
                        </span>
                      </div>
                    </td>
                    <td style={{
                      padding: '11px 16px',
                      fontWeight: 600,
                      color: log.type === 'credit' ? 'oklch(0.45 0.17 162)' : 'oklch(0.45 0.2 25)',
                    }}>
                      {formatRial(log.amount_rials)}
                    </td>
                    <td style={{ padding: '11px 16px', color: 'var(--text-2)' }}>{log.description}</td>
                    <td style={{ padding: '11px 16px', color: 'var(--text-3)' }}>{formatDateTime(log.created_at)}</td>
                  </tr>
                ))}
              </tbody>
            </table></div>
            <div style={{ padding: '12px 16px' }}>
              <Pagination page={logPage} total={total} limit={20} onPageChange={setLogPage} />
            </div>
          </>
        )}
      </div>

      {/* Modal شارژ */}
      <Modal open={chargeOpen} onClose={() => setChargeOpen(false)} title="شارژ کیف پول پیامک">
        <form onSubmit={chargeForm.handleSubmit((d) => chargeMutation.mutate(d))}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {/* انتخاب درگاه */}
            {isTestMode ? (
              <div style={{
                background: 'var(--warning-bg)',
                border: '1px solid var(--warning)',
                borderRadius: 10,
                padding: '12px 16px',
                display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <span style={{ fontSize: 20 }}>⚠️</span>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--warning)' }}>درگاه آزمایشی فعال است</div>
                  <div style={{ fontSize: 12, color: 'var(--warning)', marginTop: 2, opacity: 0.8 }}>پول واقعی کسر نخواهد شد — این تراکنش آزمایشی است</div>
                </div>
              </div>
            ) : (
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8, color: 'var(--text-2)' }}>انتخاب درگاه پرداخت</div>
                <div style={{ display: 'flex', gap: 10 }}>
                  {(['mellat', 'sep'] as const).map((gw) => (
                    <div
                      key={gw}
                      onClick={() => setGateway(gw)}
                      style={{
                        flex: 1, textAlign: 'center', padding: '12px',
                        border: `2px solid ${gateway === gw ? 'var(--primary)' : 'var(--border)'}`,
                        borderRadius: 10, cursor: 'pointer',
                        background: gateway === gw ? 'var(--primary-subtle)' : 'transparent',
                        transition: 'all 0.15s',
                      }}
                    >
                      <div style={{ fontWeight: 700, fontSize: 15, color: gateway === gw ? 'var(--primary)' : 'var(--text-1)' }}>
                        {gw === 'mellat' ? 'ملت' : 'سپ'}
                      </div>
                      <div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 3 }}>
                        {gw === 'mellat' ? 'بانک ملت' : 'بانک صادرات'}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <div className="field">
              <label>مبلغ (تومان)</label>
              <input
                {...chargeForm.register('amount_rials')}
                type="number" min={1000}
                placeholder="50000" dir="ltr"
              />
              {chargeForm.formState.errors.amount_rials && (
                <span className="field-error">{chargeForm.formState.errors.amount_rials.message}</span>
              )}
            </div>

            {watchAmount && Number(watchAmount) >= 1000 && (
              <div style={{
                background: isTestMode ? 'var(--warning-bg)' : 'var(--primary-soft)',
                border: `1px solid ${isTestMode ? 'var(--warning)' : 'color-mix(in oklch, var(--primary) 40%, transparent)'}`,
                borderRadius: 8, padding: '10px 14px',
                fontSize: 13, color: isTestMode ? 'var(--warning)' : 'var(--primary)', fontWeight: 500,
              }}>
                {isTestMode
                  ? `پرداخت آزمایشی ${formatRial(tomanToRial(Number(watchAmount)))}`
                  : `پرداخت ${formatRial(tomanToRial(Number(watchAmount)))} از طریق ${gateway === 'mellat' ? 'بانک ملت' : 'سپ'}`
                }
              </div>
            )}

            <div style={{ display: 'flex', gap: 8 }}>
              <button type="submit" className="btn primary" disabled={chargeMutation.isPending}>
                {chargeMutation.isPending ? 'در حال انتقال...' : 'پرداخت'}
              </button>
              <button type="button" className="btn" onClick={() => setChargeOpen(false)}>انصراف</button>
            </div>
          </div>
        </form>
      </Modal>
    </>
  );
}

export default function SmsWalletPage() {
  return (
    <FeatureGate feature="sms_panel">
      <SmsWalletPageInner />
    </FeatureGate>
  );
}
