// Campaigns page — real API (campaign_triggers)
const Campaigns = () => {
  const { Icon, Button, Modal, Field, Toggle, useToast } = window.SB_UI;
  const { fa } = window.SB_DATA;
  const [triggers, setTriggers] = useState([]);
  const [scripts, setScripts] = useState([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(true);
  const toast = useToast();
  const [form, setForm] = useState({ keyword: '', script_id: '', platform: 'all' });

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

  const load = () => {
    setLoading(true);
    Promise.all([
      fetch('/api/scripts/campaigns/triggers', { headers }).then(r => r.json()),
      fetch('/api/scripts', { headers }).then(r => r.json()),
    ]).then(([td, sd]) => {
      if (td.success) setTriggers(td.data.triggers || []);
      if (sd.success && sd.data?.scripts?.length) {
        setScripts(sd.data.scripts);
        setForm(f => ({ ...f, script_id: f.script_id || sd.data.scripts[0].id }));
      }
    }).finally(() => setLoading(false));
  };

  useEffect(() => { load(); }, []);

  const deleteTrigger = (id, keyword) => {
    if (!confirm(`تریگر «${keyword}» حذف شود؟`)) return;
    fetch(`/api/scripts/campaigns/triggers/${id}`, { method: 'DELETE', headers })
      .then(r => r.json())
      .then(d => {
        if (d.success) {
          toast('تریگر حذف شد', 'success');
          setTriggers(prev => prev.filter(t => t.id !== id));
        }
      });
  };

  const submit = () => {
    if (!form.keyword.trim()) return toast('کلمه کلیدی الزامیه', 'error');
    if (!form.script_id) return toast('اسکریپت را انتخاب کنید', 'error');
    fetch('/api/scripts/campaigns/triggers', {
      method: 'POST', headers,
      body: JSON.stringify({
        keyword: form.keyword.trim(),
        script_id: form.script_id,
        platform: form.platform,
      }),
    }).then(r => r.json()).then(d => {
      if (d.success) {
        toast('تریگر ساخته شد ✓', 'success');
        setOpen(false);
        setForm(f => ({ ...f, keyword: '' }));
        load();
      } else {
        toast(d.message || 'خطا در ساخت تریگر', 'error');
      }
    });
  };

  const platformLabel = (p) =>
    ({ all: 'همه', telegram: 'تلگرام', bale: 'بله', instagram: 'اینستاگرام' }[p] || p);
  const platformColor = (p) =>
    ({ all: '#818CF8', telegram: '#3B82F6', bale: '#10B981', instagram: '#FF6B35' }[p] || '#6B7280');

  return (
    <div>
      {/* ─── هدر ─── */}
      <div className="row between">
        <div>
          <div className="semi" style={{ fontSize: 15 }}>تریگرهای کمپین</div>
          <div className="text-xs text-3 mt-4">
            {loading ? 'در حال بارگذاری...' : `${fa(triggers.length)} تریگر تعریف شده`}
          </div>
        </div>
        <Button kind="primary" icon="plus" onClick={() => setOpen(true)}>تریگر جدید</Button>
      </div>

      {/* ─── توضیح ─── */}
      <div style={{
        marginTop: 16, padding: '12px 16px',
        background: 'rgba(108,99,255,0.08)',
        borderRadius: 10, borderRight: '3px solid var(--primary)',
      }}>
        <div className="text-sm" style={{ color: 'var(--text-2)', lineHeight: 1.8 }}>
          <strong>چطور کار می‌کنه:</strong> وقتی کاربر یه کلمه کلیدی مشخص را برای ربات بفرستد، اسکریپت متناظر فعال می‌شه.
          مثلاً: کاربر «وبینار» می‌فرسته → ربات اسکریپت ثبت‌نام وبینار را اجرا می‌کنه.
        </div>
      </div>

      {/* ─── جدول تریگرها ─── */}
      {loading ? (
        <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-3)' }}>در حال بارگذاری...</div>
      ) : triggers.length === 0 ? (
        <div className="card mt-16" style={{ textAlign: 'center', padding: 60 }}>
          <Icon name="megaphone" size={44} color="var(--text-3)" />
          <div className="semi mt-16">هنوز تریگری تعریف نشده</div>
          <div className="text-xs mt-8 text-3" style={{ maxWidth: 340, margin: '8px auto 0' }}>
            با ایجاد تریگر، کاربران می‌توانند با فرستادن یک کلمه خاص، اسکریپت فروش مربوط را فعال کنند
          </div>
          <div style={{ marginTop: 20 }}>
            <Button kind="primary" icon="plus" onClick={() => setOpen(true)}>اولین تریگر را بساز</Button>
          </div>
        </div>
      ) : (
        <div className="card mt-16" style={{ padding: 0, overflow: 'hidden' }}>
          <table className="table">
            <thead>
              <tr>
                <th>کلمه کلیدی</th>
                <th>اسکریپت متصل</th>
                <th>پلتفرم</th>
                <th style={{ textAlign: 'center' }}>تعداد اجرا</th>
                <th>تاریخ ساخت</th>
                <th style={{ width: 40 }}></th>
              </tr>
            </thead>
            <tbody>
              {triggers.map(t => (
                <tr key={t.id}>
                  <td>
                    <div className="row gap-10">
                      <div style={{
                        width: 32, height: 32, borderRadius: 8,
                        background: 'rgba(108,99,255,0.14)',
                        display: 'grid', placeItems: 'center', flexShrink: 0
                      }}>
                        <Icon name="hash" size={14} color="#A5B4FC" />
                      </div>
                      <span className="kbd-key semi" style={{ fontSize: 13 }}>
                        {t.keyword}
                      </span>
                    </div>
                  </td>
                  <td>
                    <div className="row gap-8">
                      <div style={{
                        width: 26, height: 26, borderRadius: 6,
                        background: 'rgba(52,211,153,0.12)',
                        display: 'grid', placeItems: 'center', flexShrink: 0
                      }}>
                        <Icon name="file-text" size={12} color="#34D399" />
                      </div>
                      <span className="semi text-sm">{t.script_name || '—'}</span>
                    </div>
                  </td>
                  <td>
                    <span style={{
                      fontSize: 11, padding: '2px 8px', borderRadius: 6,
                      background: platformColor(t.platform) + '22',
                      color: platformColor(t.platform)
                    }}>
                      {platformLabel(t.platform)}
                    </span>
                  </td>
                  <td style={{ textAlign: 'center' }}>
                    <span className="mono semi" style={{
                      padding: '2px 10px', borderRadius: 20,
                      background: t.trigger_count > 0 ? 'rgba(108,99,255,0.14)' : 'transparent',
                      color: t.trigger_count > 0 ? '#A5B4FC' : 'var(--text-3)'
                    }}>
                      {fa(t.trigger_count || 0)}
                    </span>
                  </td>
                  <td className="mono text-xs text-2">
                    {t.created_at ? t.created_at.slice(0, 10) : '—'}
                  </td>
                  <td>
                    <button className="icon-btn" style={{ width: 28, height: 28 }}
                      onClick={() => deleteTrigger(t.id, t.keyword)}
                      title="حذف تریگر">
                      <Icon name="trash-2" size={12} color="#F87171" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* ─── مودال ساخت تریگر ─── */}
      <Modal
        open={open}
        onClose={() => setOpen(false)}
        title="تریگر جدید"
        width={520}
        footer={
          <>
            <Button kind="primary" onClick={submit}>ذخیره تریگر</Button>
            <Button kind="ghost" onClick={() => setOpen(false)}>انصراف</Button>
          </>
        }
      >
        <div className="col gap-16">
          <Field label="کلمه کلیدی">
            <input
              className="input mono"
              value={form.keyword}
              onChange={e => setForm({ ...form, keyword: e.target.value })}
              placeholder="مثلاً: وبینار یا ۱۰ یا طلا"
              onKeyDown={e => e.key === 'Enter' && submit()}
              autoFocus
            />
          </Field>

          <Field label="اسکریپت متصل">
            <select
              className="select"
              value={form.script_id}
              onChange={e => setForm({ ...form, script_id: e.target.value })}
            >
              {scripts.map(s => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>
          </Field>

          <Field label="پلتفرم">
            <select
              className="select"
              value={form.platform}
              onChange={e => setForm({ ...form, platform: e.target.value })}
            >
              <option value="all">همه پلتفرم‌ها</option>
              <option value="telegram">تلگرام</option>
              <option value="bale">بله</option>
              <option value="instagram">اینستاگرام</option>
            </select>
          </Field>

          {form.keyword && form.script_id && (
            <div style={{
              padding: '10px 14px',
              background: 'rgba(52,211,153,0.06)',
              borderRadius: 10,
              borderRight: '3px solid #34D399',
            }}>
              <div className="text-xs" style={{ color: '#34D399', lineHeight: 1.8 }}>
                ✓ وقتی کاربر «{form.keyword}» بفرستد، اسکریپت «
                {scripts.find(s => s.id === form.script_id)?.name || ''}» اجرا می‌شود
              </div>
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
};

window.Campaigns = Campaigns;
