// Rules page — قوانین دینامیک بات
const Rules = () => {
  const { Icon, Button } = window.SB_UI;
  const [rules, setRules] = useState([]);
  const [loading, setLoading] = useState(true);
  const [newText, setNewText] = useState('');
  const [newType, setNewType] = useState('guideline');
  const [editId, setEditId] = useState(null);
  const [editText, setEditText] = useState('');

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

  const load = () => {
    setLoading(true);
    fetch('/api/rules', { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setRules(d.data?.rules || []); })
      .finally(() => setLoading(false));
  };

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

  const add = () => {
    if (!newText.trim()) return;
    fetch('/api/rules', { method: 'POST', headers, body: JSON.stringify({ type: newType, text: newText }) })
      .then(r => r.json()).then(d => { if (d.success) { setNewText(''); load(); } });
  };

  const toggle = (rule) => {
    fetch(`/api/rules/${rule.id}`, { method: 'PUT', headers, body: JSON.stringify({ is_active: rule.is_active ? 0 : 1 }) })
      .then(r => r.json()).then(() => load());
  };

  const remove = (id) => {
    if (!confirm('حذف شود؟')) return;
    fetch(`/api/rules/${id}`, { method: 'DELETE', headers }).then(() => load());
  };

  const saveEdit = (id) => {
    if (!editText.trim()) return;
    fetch(`/api/rules/${id}`, { method: 'PUT', headers, body: JSON.stringify({ text: editText }) })
      .then(r => r.json()).then(() => { setEditId(null); load(); });
  };

  const redLines = rules.filter(r => r.type === 'red_line');
  const guidelines = rules.filter(r => r.type === 'guideline');

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

      {/* فرم افزودن */}
      <div className="card" style={{ padding: 20 }}>
        <div className="text-xs text-3 semi" style={{ marginBottom: 14, letterSpacing: 0.04, textTransform: 'uppercase' }}>قانون جدید</div>
        <div className="col gap-12">
          <div className="row gap-8">
            <button
              onClick={() => setNewType('red_line')}
              style={{
                padding: '6px 16px', borderRadius: 8, fontSize: 13, cursor: 'pointer', border: 'none',
                background: newType === 'red_line' ? 'rgba(239,68,68,0.2)' : 'rgba(255,255,255,0.06)',
                color: newType === 'red_line' ? '#F87171' : 'var(--text-2)',
              }}>
              🔴 خط قرمز
            </button>
            <button
              onClick={() => setNewType('guideline')}
              style={{
                padding: '6px 16px', borderRadius: 8, fontSize: 13, cursor: 'pointer', border: 'none',
                background: newType === 'guideline' ? 'rgba(99,102,241,0.2)' : 'rgba(255,255,255,0.06)',
                color: newType === 'guideline' ? '#818CF8' : 'var(--text-2)',
              }}>
              🔵 خط مشی
            </button>
          </div>
          <div className="row gap-8">
            <input
              value={newText}
              onChange={e => setNewText(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && add()}
              placeholder={newType === 'red_line' ? 'مثال: هیچ کانالی معرفی نکن...' : 'مثال: همیشه با شما خطاب کن...'}
              style={{
                flex: 1, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)',
                borderRadius: 8, padding: '9px 14px', color: 'var(--text-1)', fontSize: 14, outline: 'none', direction: 'rtl'
              }}
            />
            <Button kind="primary" icon="plus" onClick={add}>افزودن</Button>
          </div>
        </div>
      </div>

      <div className="grid grid-2 gap-20">
        {/* خط قرمز */}
        <div>
          <div className="row gap-8" style={{ marginBottom: 12 }}>
            <span style={{ fontSize: 16 }}>🔴</span>
            <div className="semi" style={{ color: '#F87171' }}>خط قرمز</div>
            <span className="text-xs text-3">({redLines.length} قانون)</span>
          </div>
          <div className="col gap-8">
            {redLines.length === 0 && <div className="text-sm text-3" style={{ padding: '12px 0' }}>قانونی ثبت نشده</div>}
            {redLines.map(r => (
              <RuleCard key={r.id} rule={r} color="#F87171" bg="rgba(239,68,68,0.08)"
                editId={editId} editText={editText}
                setEditId={setEditId} setEditText={setEditText}
                onToggle={toggle} onDelete={remove} onSave={saveEdit} />
            ))}
          </div>
        </div>

        {/* خط مشی */}
        <div>
          <div className="row gap-8" style={{ marginBottom: 12 }}>
            <span style={{ fontSize: 16 }}>🔵</span>
            <div className="semi" style={{ color: '#818CF8' }}>خط مشی</div>
            <span className="text-xs text-3">({guidelines.length} قانون)</span>
          </div>
          <div className="col gap-8">
            {guidelines.length === 0 && <div className="text-sm text-3" style={{ padding: '12px 0' }}>قانونی ثبت نشده</div>}
            {guidelines.map(r => (
              <RuleCard key={r.id} rule={r} color="#818CF8" bg="rgba(99,102,241,0.08)"
                editId={editId} editText={editText}
                setEditId={setEditId} setEditText={setEditText}
                onToggle={toggle} onDelete={remove} onSave={saveEdit} />
            ))}
          </div>
        </div>
      </div>

      {/* نکته */}
      <div style={{ padding: '12px 16px', background: 'rgba(99,102,241,0.08)', borderRadius: 10, borderRight: '3px solid #818CF8' }}>
        <div className="text-sm" style={{ color: 'var(--text-2)', lineHeight: 1.8 }}>
          قوانین فعال به صورت خودکار به هر مکالمه اضافه می‌شن — بدون نیاز به ری‌استارت سرور.
        </div>
      </div>
    </div>
  );
};

const RuleCard = ({ rule, color, bg, editId, editText, setEditId, setEditText, onToggle, onDelete, onSave }) => {
  const { Icon } = window.SB_UI;
  const isEditing = editId === rule.id;

  return (
    <div style={{
      padding: '10px 14px', borderRadius: 10, background: bg,
      border: `1px solid ${rule.is_active ? color + '30' : 'rgba(255,255,255,0.05)'}`,
      opacity: rule.is_active ? 1 : 0.45,
    }}>
      {isEditing ? (
        <div className="row gap-8">
          <input
            value={editText}
            onChange={e => setEditText(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') onSave(rule.id); if (e.key === 'Escape') setEditId(null); }}
            autoFocus
            style={{
              flex: 1, background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.15)',
              borderRadius: 6, padding: '5px 10px', color: 'var(--text-1)', fontSize: 13, outline: 'none', direction: 'rtl'
            }}
          />
          <button onClick={() => onSave(rule.id)} className="icon-btn" style={{ width: 28, height: 28, color: '#34D399' }}><Icon name="check" size={13} /></button>
          <button onClick={() => setEditId(null)} className="icon-btn" style={{ width: 28, height: 28 }}><Icon name="x" size={13} /></button>
        </div>
      ) : (
        <div className="row between gap-8">
          <span className="text-sm" style={{ flex: 1, lineHeight: 1.6 }}>{rule.text}</span>
          <div className="row gap-4">
            <button onClick={() => { setEditId(rule.id); setEditText(rule.text); }} className="icon-btn" style={{ width: 26, height: 26 }}><Icon name="pencil" size={12} /></button>
            <button onClick={() => onToggle(rule)} className="icon-btn" style={{ width: 26, height: 26, color: rule.is_active ? '#34D399' : 'var(--text-3)' }}>
              <Icon name={rule.is_active ? 'toggle-right' : 'toggle-left'} size={14} />
            </button>
            <button onClick={() => onDelete(rule.id)} className="icon-btn" style={{ width: 26, height: 26, color: '#F87171' }}><Icon name="trash-2" size={12} /></button>
          </div>
        </div>
      )}
    </div>
  );
};

window.Rules = Rules;
