// Settings page — فقط یکپارچه‌سازی
const Settings = () => {
  const { useToast } = window.SB_UI;
  const _t = useToast ? useToast() : null;
  const toast = {
    success: (m) => _t ? _t(m, 'success') : console.log(m),
    error:   (m) => _t ? _t(m, 'error')   : console.error(m),
    info:    (m) => _t ? _t(m, 'info')    : console.log(m),
  };
  return <IntegrationsTab toast={toast} />;
};

// ─── Meta پلتفرم‌های پیام‌رسان ────────────────────────────────
const MSG_META = {
  telegram:  { icon: 'send',            color: '#3B82F6', desc: 'api.telegram.org',       ph: '123456789:ABC...' },
  bale:      { icon: 'message-square',  color: '#22C55E', desc: 'tapi.bale.ai',            ph: '230025703:abc...' },
  eitaa:     { icon: 'message-circle',  color: '#F59E0B', desc: 'eitaayar.ir',             ph: 'bot...' },
  rubika:    { icon: 'send-horizontal', color: '#EF4444', desc: 'botapi.rubika.ir',        ph: 'token...' },
  instagram: { icon: 'instagram',       color: '#E1306C', desc: 'graph.facebook.com/v20',  ph: 'EAAxxxxxxxx...' },
};

// ─── کامپوننت badge وصل/قطع ────────────────────────────────
const StatusBadge = ({ status }) => {
  const ok  = status === 'ok';
  const err = status === 'error';
  const col = ok ? '#22C55E' : err ? '#EF4444' : '#64748b';
  return (
    <span style={{
      fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 999,
      background: ok ? 'rgba(34,197,94,0.15)' : err ? 'rgba(239,68,68,0.15)' : 'rgba(100,116,139,0.12)',
      color: col,
      border: `1px solid ${ok ? 'rgba(34,197,94,0.3)' : err ? 'rgba(239,68,68,0.3)' : 'rgba(100,116,139,0.2)'}`,
      display: 'inline-flex', alignItems: 'center', gap: 4,
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: col, boxShadow: `0 0 4px ${col}` }} />
      {ok ? 'وصل' : err ? 'قطع' : 'تست نشده'}
    </span>
  );
};

// ─── کامپوننت ویژه اینستاگرام ────────────────────────────────
const InstagramExtra = ({ it, hdrs, toast, load }) => {
  const { Button, Icon } = window.SB_UI;
  const cfg = it.config || {};
  const [vt, setVt] = useState(cfg.verify_token || '');
  const [saving, setSaving] = useState(false);
  const webhookUrl = `${window.location.origin}/webhook/instagram`;

  const saveVerifyToken = () => {
    if (!vt.trim()) return;
    setSaving(true);
    fetch(`/api/settings/integrations/instagram`, {
      method: 'PUT', headers: hdrs(),
      body: JSON.stringify({ config: { verify_token: vt.trim() } }),
    }).then(r => r.json()).then(d => {
      setSaving(false);
      if (d.success) { toast.success('Verify Token ذخیره شد'); load(true); }
      else toast.error(d.message || 'خطا');
    }).catch(() => { setSaving(false); toast.error('خطای شبکه'); });
  };

  return (
    <div style={{ padding: '10px 12px', background: 'rgba(225,48,108,0.05)', border: '1px solid rgba(225,48,108,0.15)', borderRadius: 8 }}>
      {/* Webhook URL */}
      <div className="col gap-6" style={{ marginBottom: 10 }}>
        <div className="text-xs text-3" style={{ fontWeight: 600 }}>🔗 Webhook URL (در Meta Dashboard بزار)</div>
        <div className="row gap-6">
          <div className="mono" style={{
            flex: 1, padding: '5px 8px', borderRadius: 6, fontSize: 10,
            background: 'rgba(0,0,0,0.25)', border: '1px solid var(--border-soft)',
            color: '#94a3b8', direction: 'ltr', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            userSelect: 'all', cursor: 'text',
          }}>{webhookUrl}</div>
          <button className="icon-btn" style={{ width: 28, height: 28, flexShrink: 0 }}
            onClick={() => navigator.clipboard.writeText(webhookUrl).then(() => toast.success('کپی شد'))}>
            <Icon name="copy" size={12} />
          </button>
        </div>
      </div>
      {/* Verify Token */}
      <div className="col gap-6">
        <div className="text-xs text-3" style={{ fontWeight: 600 }}>🔐 Verify Token (همین رو در Meta بزار)</div>
        <div className="row gap-6">
          <input className="input mono" style={{ flex: 1, fontSize: 11, direction: 'ltr' }}
            placeholder="smartbot_verify"
            value={vt}
            onChange={e => setVt(e.target.value)}
          />
          <Button kind="primary" size="sm" disabled={saving || !vt.trim()} onClick={saveVerifyToken}>
            {saving ? '...' : 'ذخیره'}
          </Button>
        </div>
        <div className="text-xs text-3" style={{ opacity: 0.7 }}>
          در Meta App → Webhooks → Callback URL همین آدرس رو بزار، Verify Token هم همینه
        </div>
      </div>
    </div>
  );
};

const IntegrationsTab = ({ toast }) => {
  const { Icon, Button, Toggle } = window.SB_UI;
  const [items,    setItems]    = useState([]);
  const [loading,  setLoading]  = useState(true);   // فقط بار اول
  const [editing,  setEditing]  = useState(null);   // { key, token }
  const [busy,     setBusy]     = useState({});
  const [refreshing, setRefreshing] = useState(false); // refresh بی‌صدا
  const [revealed, setRevealed] = useState({});
  // Claude AI config state
  const [models,      setModels]      = useState([]);
  const [modelsLoading, setModelsLoading] = useState(false);
  const [aiCfg,       setAiCfg]       = useState({ model: '', max_tokens: 2000, temperature: 0.7, system_lang: 'fa' });
  const [aiCfgDirty,  setAiCfgDirty]  = useState(false);
  const [savingCfg,   setSavingCfg]   = useState(false);

  const hdrs = () => ({
    'Content-Type': 'application/json',
    Authorization: `Bearer ${localStorage.getItem(window.TOKEN_KEY || 'sb_token')}`,
  });

  const load = (silent = false) => {
    // بار اول: loading spinner — refresh بعدی: بی‌صدا (scroll نمی‌خوره)
    if (!silent) setLoading(true);
    else setRefreshing(true);
    fetch('/api/settings/integrations', { headers: hdrs() })
      .then(r => r.json())
      .then(d => {
        if (d.success) {
          setItems(d.data.items || []);
          const claude = (d.data.items || []).find(x => x.key === 'claude');
          if (claude?.config) {
            setAiCfg(cfg => ({ ...cfg, ...claude.config }));
          }
        }
        setLoading(false);
        setRefreshing(false);
      })
      .catch(() => {
        setLoading(false);
        setRefreshing(false);
        toast.error('خطا در بارگذاری');
      });
  };
  useEffect(() => load(false), []);

  const loadModels = () => {
    setModelsLoading(true);
    fetch('/api/settings/integrations/claude/models', { headers: hdrs() })
      .then(r => r.json())
      .then(d => {
        setModelsLoading(false);
        if (d.success) setModels(d.data.models || []);
        else toast.error(d.message || 'خطا در بارگذاری مدل‌ها');
      })
      .catch(() => { setModelsLoading(false); toast.error('خطای شبکه'); });
  };

  const saveToken = (key, token) => {
    setBusy(b => ({ ...b, [key]: 'saving' }));
    fetch(`/api/settings/integrations/${key}`, {
      method: 'PUT', headers: hdrs(), body: JSON.stringify({ token }),
    }).then(r => r.json()).then(d => {
      setBusy(b => ({ ...b, [key]: null }));
      if (d.success) { toast.success('توکن ذخیره شد'); setEditing(null); load(true); }
      else toast.error(d.message || 'خطا');
    }).catch(() => { setBusy(b => ({ ...b, [key]: null })); toast.error('خطای شبکه'); });
  };

  const saveAiCfg = () => {
    setSavingCfg(true);
    fetch('/api/settings/integrations/claude', {
      method: 'PUT', headers: hdrs(), body: JSON.stringify({ config: aiCfg }),
    }).then(r => r.json()).then(d => {
      setSavingCfg(false);
      if (d.success) { toast.success('تنظیمات ذخیره شد'); setAiCfgDirty(false); }
      else toast.error(d.message || 'خطا');
    }).catch(() => { setSavingCfg(false); toast.error('خطای شبکه'); });
  };

  const toggleEnabled = (key, on) => {
    setItems(arr => arr.map(x => x.key === key ? { ...x, is_enabled: !!on } : x));
    fetch(`/api/settings/integrations/${key}`, {
      method: 'PUT', headers: hdrs(), body: JSON.stringify({ is_enabled: on }),
    }).then(r => r.json()).then(d => {
      if (d.success) toast.success(on ? 'فعال شد' : 'غیرفعال شد');
      else toast.error(d.message || 'خطا');
      load(true);
    }).catch(() => { toast.error('خطای شبکه'); load(true); });
  };

  const testConn = (key) => {
    const it = items.find(x => x.key === key);
    if (!it?.has_token) { toast.error('ابتدا توکن را تنظیم کنید'); return; }
    setBusy(b => ({ ...b, [key]: 'testing' }));
    fetch(`/api/settings/integrations/${key}/test`, { method: 'POST', headers: hdrs() })
      .then(r => r.json()).then(d => {
        setBusy(b => ({ ...b, [key]: null }));
        if (d.data?.last_status === 'ok') toast.success(d.message || 'اتصال موفق ✅');
        else toast.error(d.data?.last_error || d.message || 'اتصال ناموفق');
        load(true);
      }).catch(e => { setBusy(b => ({ ...b, [key]: null })); toast.error('خطای شبکه'); });
  };

  const toggleReveal = (key) => {
    if (revealed[key] != null) { setRevealed(r => ({ ...r, [key]: null })); return; }
    fetch(`/api/settings/integrations/${key}/token`, { headers: hdrs() })
      .then(r => r.json())
      .then(d => { if (d.success) setRevealed(r => ({ ...r, [key]: d.data.token || '' })); else toast.error(d.message); })
      .catch(() => toast.error('خطای شبکه'));
  };

  const copyToken = (key) => {
    const tok = revealed[key];
    if (!tok) return;
    navigator.clipboard.writeText(tok).then(() => toast.success('کپی شد'), () => toast.error('کپی نشد'));
  };

  const restartChannel = (key) => {
    setBusy(b => ({ ...b, [key]: 'restarting' }));
    fetch(`/api/settings/integrations/${key}/restart`, { method: 'POST', headers: hdrs() })
      .then(r => r.json()).then(d => {
        setBusy(b => ({ ...b, [key]: null }));
        if (d.success) toast.success(d.message || 'راه‌اندازی مجدد شد ✅');
        else toast.error(d.message || 'خطا');
        setTimeout(() => load(true), 1500);
      }).catch(() => { setBusy(b => ({ ...b, [key]: null })); toast.error('خطای شبکه'); });
  };

  const removeToken = (key) => {
    if (!confirm('توکن حذف شود؟')) return;
    fetch(`/api/settings/integrations/${key}/token`, { method: 'DELETE', headers: hdrs() })
      .then(r => r.json()).then(d => { if (d.success) { toast.success('حذف شد'); load(true); } });
  };

  // ── تست گفتگو با Claude ────────────────────────────────────
  const [testMsg,   setTestMsg]   = useState('');
  const [testReply, setTestReply] = useState(null); // null | { reply, model, elapsed_ms, input_tokens, output_tokens } | { error }
  const [testBusy,  setTestBusy]  = useState(false);

  const sendTestMsg = () => {
    if (!testMsg.trim() || testBusy) return;
    setTestBusy(true);
    setTestReply(null);
    fetch('/api/settings/integrations/claude/chat-test', {
      method: 'POST', headers: hdrs(), body: JSON.stringify({ message: testMsg }),
    }).then(r => r.json()).then(d => {
      setTestBusy(false);
      if (d.success) setTestReply(d.data);
      else setTestReply({ error: d.message || 'خطا' });
    }).catch(e => { setTestBusy(false); setTestReply({ error: 'خطای شبکه' }); });
  };

  const claude = items.find(x => x.key === 'claude');
  const msgItems = items.filter(x => x.key !== 'claude');

  // ── TokenRow ─────────────────────────────────────────────
  const TokenRow = ({ it, placeholder }) => (
    <div className="row gap-8">
      {editing?.key === it.key ? (
        <>
          <input type="text" className="input mono"
            style={{ flex: 1, fontSize: 11, direction: 'ltr' }}
            placeholder={placeholder || ''}
            value={editing.token} autoFocus
            onChange={e => setEditing({ ...editing, token: e.target.value })}
          />
          <Button kind="primary" size="sm"
            disabled={busy[it.key] === 'saving' || !editing.token.trim()}
            onClick={() => saveToken(it.key, editing.token)}
          >{busy[it.key] === 'saving' ? '...' : 'ذخیره'}</Button>
          <Button kind="ghost" size="sm" onClick={() => setEditing(null)}>لغو</Button>
        </>
      ) : (
        <>
          <div className="mono" style={{
            flex: 1, padding: '6px 10px', borderRadius: 8, fontSize: 11,
            background: 'rgba(0,0,0,0.2)', border: '1px solid var(--border-soft)',
            color: it.has_token ? '#cbd5e1' : '#475569', direction: 'ltr',
            overflow: 'hidden', textOverflow: revealed[it.key] != null ? 'unset' : 'ellipsis',
            whiteSpace: 'nowrap', userSelect: revealed[it.key] != null ? 'all' : 'none',
            cursor: revealed[it.key] != null ? 'text' : 'default',
          }}>{revealed[it.key] != null ? (revealed[it.key] || '(خالی)') : (it.token_masked || 'کلید وارد نشده')}</div>
          {it.has_token && (
            <button className="icon-btn" style={{ width: 30, height: 30, flexShrink: 0 }} title={revealed[it.key] != null ? 'مخفی' : 'نمایش'} onClick={() => toggleReveal(it.key)}>
              <Icon name={revealed[it.key] != null ? 'eye-off' : 'eye'} size={14} />
            </button>
          )}
          <Button kind="ghost" size="sm" icon="edit-2" onClick={() => setEditing({ key: it.key, token: '' })}>
            {it.has_token ? 'تغییر' : 'تنظیم'}
          </Button>
        </>
      )}
    </div>
  );

  if (loading) return <div className="card text-3 text-sm" style={{ padding: 24 }}>در حال بارگذاری…</div>;

  return (
    <div className="col gap-16">

      {/* ══════ بخش ۱: هوش مصنوعی ══════ */}
      <div className="card" style={{ border: '1px solid rgba(168,85,247,0.25)', background: 'rgba(168,85,247,0.04)' }}>
        <div className="row between" style={{ marginBottom: 16 }}>
          <div className="row gap-12">
            <div style={{ width: 42, height: 42, borderRadius: 12, background: 'rgba(168,85,247,0.15)', display: 'grid', placeItems: 'center' }}>
              <Icon name="sparkles" size={20} color="#A855F7" />
            </div>
            <div>
              <div className="row gap-8" style={{ alignItems: 'center' }}>
                <span className="bold" style={{ fontSize: 15 }}>Claude AI</span>
                {claude && <StatusBadge status={claude.last_status} />}
              </div>
              <div className="text-xs text-3 mt-4">Anthropic API • مدل هوش مصنوعی ربات</div>
            </div>
          </div>
          <div className="row gap-8">
            {claude && <Toggle on={!!claude.is_enabled} onChange={v => toggleEnabled('claude', v)} />}
          </div>
        </div>

        {/* API Key */}
        <div className="col gap-8">
          <div className="text-xs text-3" style={{ fontWeight: 600 }}>🔑 API Key</div>
          {claude && <TokenRow it={claude} placeholder="sk-ant-api03-..." />}
          {claude?.last_status === 'ok' && claude.bot_name && (
            <div className="row gap-8" style={{ fontSize: 11, padding: '6px 10px', background: 'rgba(34,197,94,0.08)', border: '1px solid rgba(34,197,94,0.2)', borderRadius: 8, color: '#86efac' }}>
              <Icon name="check-circle" size={12} /><span>{claude.bot_name}</span>
            </div>
          )}
          {claude?.last_status === 'error' && claude.last_error && (
            <div className="row gap-8" style={{ fontSize: 11, padding: '6px 10px', background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)', borderRadius: 8, color: '#fca5a5' }}>
              <Icon name="alert-circle" size={12} /><span>{claude.last_error}</span>
            </div>
          )}
          <div className="row gap-8 mt-4">
            <Button kind="ghost" size="sm" icon="zap" disabled={busy.claude === 'testing'} onClick={() => testConn('claude')}>
              {busy.claude === 'testing' ? 'در حال تست...' : 'تست اتصال'}
            </Button>
            {claude?.last_status_at && (
              <span className="text-xs text-3" style={{ alignSelf: 'center' }}>
                آخرین تست: {new Date(claude.last_status_at).toLocaleString('fa-IR', { hour:'2-digit', minute:'2-digit', day:'numeric', month:'short' })}
              </span>
            )}
          </div>
        </div>

        {/* ── تنظیمات مدل ── */}
        <div style={{ marginTop: 20, paddingTop: 16, borderTop: '1px solid rgba(168,85,247,0.15)' }}>
          <div className="row between" style={{ marginBottom: 12 }}>
            <div className="text-sm semi" style={{ color: '#c4b5fd' }}>⚙️ تنظیمات مدل</div>
            <Button kind="ghost" size="sm" icon="refresh-cw" onClick={loadModels} disabled={modelsLoading}>
              {modelsLoading ? 'در حال بارگذاری...' : 'بارگذاری مدل‌ها'}
            </Button>
          </div>
          <div className="grid grid-2 gap-12">
            {/* مدل */}
            <div className="col gap-6">
              <label className="text-xs text-3">مدل</label>
              {models.length > 0 ? (
                <select className="select" style={{ fontSize: 12, direction: 'ltr' }}
                  value={aiCfg.model}
                  onChange={e => { setAiCfg(c => ({ ...c, model: e.target.value })); setAiCfgDirty(true); }}>
                  <option value="">— انتخاب کنید —</option>
                  {models.map(m => <option key={m.id} value={m.id}>{m.name || m.id}</option>)}
                </select>
              ) : (
                <input className="input mono" style={{ fontSize: 11, direction: 'ltr' }}
                  placeholder="claude-opus-4-5"
                  value={aiCfg.model}
                  onChange={e => { setAiCfg(c => ({ ...c, model: e.target.value })); setAiCfgDirty(true); }}
                />
              )}
            </div>
            {/* max tokens */}
            <div className="col gap-6">
              <label className="text-xs text-3">حداکثر توکن پاسخ</label>
              <input type="number" className="input" style={{ fontSize: 12 }}
                min={100} max={8192} step={100}
                value={aiCfg.max_tokens}
                onChange={e => { setAiCfg(c => ({ ...c, max_tokens: +e.target.value })); setAiCfgDirty(true); }}
              />
            </div>
            {/* temperature */}
            <div className="col gap-6">
              <label className="text-xs text-3">دما (خلاقیت) — {aiCfg.temperature}</label>
              <input type="range" min={0} max={1} step={0.05}
                value={aiCfg.temperature}
                style={{ width: '100%', accentColor: '#A855F7' }}
                onChange={e => { setAiCfg(c => ({ ...c, temperature: +e.target.value })); setAiCfgDirty(true); }}
              />
              <div className="row between text-xs text-3"><span>دقیق ۰</span><span>۱ خلاق</span></div>
            </div>
            {/* زبان پیش‌فرض */}
            <div className="col gap-6">
              <label className="text-xs text-3">زبان پاسخ پیش‌فرض</label>
              <select className="select" style={{ fontSize: 12 }}
                value={aiCfg.system_lang}
                onChange={e => { setAiCfg(c => ({ ...c, system_lang: e.target.value })); setAiCfgDirty(true); }}>
                <option value="fa">فارسی</option>
                <option value="en">English</option>
                <option value="ar">العربية</option>
              </select>
            </div>
          </div>
          {aiCfgDirty && (
            <div className="row gap-8 mt-12">
              <Button kind="primary" size="sm" icon="save" onClick={saveAiCfg} disabled={savingCfg}>
                {savingCfg ? 'در حال ذخیره...' : 'ذخیره تنظیمات'}
              </Button>
              <Button kind="ghost" size="sm" onClick={() => { load(true); setAiCfgDirty(false); }}>لغو</Button>
            </div>
          )}
        </div>

        {/* ── تست گفتگو ── */}
        <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid rgba(168,85,247,0.15)' }}>
          <div className="text-sm semi" style={{ color: '#c4b5fd', marginBottom: 10 }}>💬 تست گفتگو با AI</div>
          <div className="row gap-8">
            <input
              className="input"
              style={{ flex: 1, fontSize: 13 }}
              placeholder="یه پیام بفرست تا ببینی AI جواب می‌ده..."
              value={testMsg}
              onChange={e => setTestMsg(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && sendTestMsg()}
              disabled={testBusy}
            />
            <Button kind="primary" size="sm" icon={testBusy ? 'loader' : 'send'} onClick={sendTestMsg} disabled={testBusy || !testMsg.trim()}>
              {testBusy ? 'در حال ارسال...' : 'ارسال'}
            </Button>
          </div>

          {testReply && (
            <div style={{ marginTop: 10, borderRadius: 10, overflow: 'hidden', border: '1px solid rgba(168,85,247,0.2)' }}>
              {/* پیام کاربر */}
              <div style={{ padding: '8px 14px', background: 'rgba(99,102,241,0.1)', fontSize: 12, color: '#a5b4fc', borderBottom: '1px solid rgba(168,85,247,0.15)' }}>
                <span style={{ opacity: 0.6, fontSize: 10 }}>شما: </span>{testMsg}
              </div>
              {/* پاسخ AI */}
              {testReply.error ? (
                <div style={{ padding: '10px 14px', background: 'rgba(239,68,68,0.08)', color: '#fca5a5', fontSize: 12 }}>
                  ❌ {testReply.error}
                </div>
              ) : (
                <>
                  <div style={{ padding: '10px 14px', background: 'rgba(168,85,247,0.06)', color: '#e2e8f0', fontSize: 13, lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>
                    {testReply.reply}
                  </div>
                  <div className="row gap-12" style={{ padding: '6px 14px', background: 'rgba(0,0,0,0.2)', fontSize: 10, color: '#475569' }}>
                    <span>مدل: <span className="mono" style={{ color: '#64748b' }}>{testReply.model}</span></span>
                    <span>زمان: {testReply.elapsed_ms}ms</span>
                    <span>ورودی: {testReply.input_tokens} توکن</span>
                    <span>خروجی: {testReply.output_tokens} توکن</span>
                  </div>
                </>
              )}
            </div>
          )}
        </div>
      </div>

      {/* ══════ بخش ۲: پیام‌رسان‌ها ══════ */}
      <div className="card">
        <div className="row between" style={{ marginBottom: 16 }}>
          <div>
            <div className="bold">پیام‌رسان‌ها</div>
            <div className="text-xs text-3 mt-4">کانال‌های ارتباطی ربات با کاربران</div>
          </div>
          <Button kind="ghost" icon="refresh-cw" size="sm" onClick={() => load(true)}>
            {refreshing ? '...' : 'به‌روزرسانی'}
          </Button>
        </div>
        <div className="grid grid-2 gap-12">
          {msgItems.map(it => {
            const m = MSG_META[it.key] || { icon: 'plug', color: '#64748b', desc: '', ph: '' };
            return (
              <div key={it.key} style={{
                padding: 14, background: 'rgba(15,15,26,0.4)',
                border: '1px solid var(--border-soft)', borderRadius: 12,
                display: 'flex', flexDirection: 'column', gap: 10,
              }}>
                {/* Header */}
                <div className="row gap-10">
                  <div style={{ width: 36, height: 36, borderRadius: 9, background: m.color+'22', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                    <Icon name={m.icon} size={17} color={m.color} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="row gap-8" style={{ alignItems: 'center' }}>
                      <span className="text-sm semi">{it.label}</span>
                      <StatusBadge status={it.last_status} />
                    </div>
                    <div className="text-xs text-3" style={{ marginTop: 2 }}>{m.desc}</div>
                  </div>
                  <Toggle on={!!it.is_enabled} onChange={v => toggleEnabled(it.key, v)} />
                </div>

                {it.last_status === 'ok' && (it.bot_username || it.bot_name) && (
                  <div className="row gap-8" style={{ fontSize: 11, padding: '5px 10px', background: 'rgba(34,197,94,0.08)', border: '1px solid rgba(34,197,94,0.2)', borderRadius: 7, color: '#86efac' }}>
                    <Icon name="check-circle" size={11} />
                    <span>{it.bot_name}</span>
                    {it.bot_username && <span className="text-3" style={{ direction: 'ltr' }}>@{it.bot_username}</span>}
                  </div>
                )}
                {it.last_status === 'error' && it.last_error && (
                  <div className="row gap-8" style={{ fontSize: 11, padding: '5px 10px', background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)', borderRadius: 7, color: '#fca5a5' }}>
                    <Icon name="alert-circle" size={11} />
                    <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.last_error}</span>
                  </div>
                )}

                {/* توکن */}
                <div>
                  <div className="text-xs text-3" style={{ marginBottom: 4, fontWeight: 600 }}>
                    {it.key === 'instagram' ? '🔑 Page Access Token' : '🔑 Bot Token'}
                  </div>
                  <TokenRow it={it} placeholder={m.ph} />
                </div>

                {/* اینستاگرام — فیلد Verify Token و اطلاعات Webhook */}
                {it.key === 'instagram' && (
                  <InstagramExtra it={it} hdrs={hdrs} toast={toast} load={load} />
                )}

                <div className="row gap-8">
                  <Button kind="ghost" size="sm" icon="zap"
                    disabled={busy[it.key] === 'testing'}
                    onClick={() => testConn(it.key)}>
                    {busy[it.key] === 'testing' ? '...' : 'تست'}
                  </Button>
                  <Button kind="ghost" size="sm" icon="refresh-cw"
                    disabled={!it.has_token || busy[it.key] === 'restarting'}
                    onClick={() => restartChannel(it.key)}
                    title="راه‌اندازی مجدد اتصال">
                    {busy[it.key] === 'restarting' ? '...' : 'ری‌استارت'}
                  </Button>
                  {it.has_token && (
                    <Button kind="ghost" size="sm" icon="trash-2" onClick={() => removeToken(it.key)} />
                  )}
                  {it.last_status_at && (
                    <span className="text-xs text-3" style={{ marginRight: 'auto', alignSelf: 'center' }}>
                      {new Date(it.last_status_at).toLocaleString('fa-IR', { hour:'2-digit', minute:'2-digit', day:'numeric', month:'short' })}
                    </span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

    </div>
  );
};

window.Settings = Settings;
