// Scripts page (multiple scripts × 4 tabs each)
const Scripts = () => {
  const { Icon, Button, Toggle, Modal, Field, useToast, SlidePanel } = window.SB_UI;
  const { fa } = window.SB_DATA;
  const [scripts, setScripts] = useState([]);
  const [activeId, setActiveId] = useState(null);
  const [tab, setTab] = useState('prompt');
  const [addOpen, setAddOpen] = useState(false);
  const [chatOpen, setChatOpen] = useState(false);
  const [newName, setNewName] = useState('');
  const [newDesc, setNewDesc] = useState('');
  const [promptText, setPromptText] = useState('');
  const [keyword, setKeyword] = useState('');
  const [saving, setSaving] = useState(false);
  const toast = useToast();
  const active = scripts.find(s => s.id === activeId);

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

  const load = () => {
    fetch('/api/scripts', { headers }).then(r => r.json()).then(d => {
      if (d.success && d.data?.scripts?.length) {
        setScripts(d.data.scripts);
        if (!activeId) {
          setActiveId(d.data.scripts[0].id);
          setPromptText(d.data.scripts[0].system_prompt || '');
        }
      }
    });
  };

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

  useEffect(() => {
    const s = scripts.find(x => x.id === activeId);
    if (s) {
      setPromptText(s.system_prompt || '');
      setKeyword(s.campaign_keyword || '');
    }
  }, [activeId]);

  const tabs = [
    { id: 'prompt', name: 'متن پرامپت', icon: 'file-text' },
    { id: 'objections', name: 'اعتراض‌ها', icon: 'message-square-x' },
    { id: 'personas', name: 'پرسوناها', icon: 'user-square' },
  ];

  const toggleActive = (id, val) => {
    fetch(`/api/scripts/${id}`, { method: 'PUT', headers, body: JSON.stringify({ is_active: val ? 1 : 0 }) })
      .then(r => r.json()).then(d => {
        if (d.success) setScripts(prev => prev.map(s => s.id === id ? { ...s, is_active: val ? 1 : 0 } : s));
      });
  };

  const deleteScript = (id, name) => {
    if (!confirm(`اسکریپت «${name}» حذف شود؟`)) return;
    fetch(`/api/scripts/${id}`, { method: 'DELETE', headers }).then(() => {
      setScripts(prev => prev.filter(s => s.id !== id));
      if (activeId === id) {
        const remaining = scripts.filter(s => s.id !== id);
        if (remaining.length > 0) setActiveId(remaining[0].id);
      }
      toast('اسکریپت حذف شد', 'success');
    });
  };

  const savePrompt = () => {
    if (!activeId) return;
    setSaving(true);
    fetch(`/api/scripts/${activeId}`, {
      method: 'PUT', headers,
      body: JSON.stringify({ system_prompt: promptText, campaign_keyword: keyword.trim() || null })
    }).then(r => r.json()).then(d => {
      if (d.success) {
        setScripts(prev => prev.map(s => s.id === activeId
          ? { ...s, system_prompt: promptText, campaign_keyword: keyword.trim() || null }
          : s
        ));
        toast('اسکریپت ذخیره شد', 'success');
      } else {
        toast('خطا در ذخیره', 'error');
      }
    }).finally(() => setSaving(false));
  };

  const create = (thenOpenChat = false) => {
    if (!newName.trim()) return toast('نام اسکریپت الزامیه', 'error');
    fetch('/api/scripts', { method: 'POST', headers, body: JSON.stringify({ name: newName, system_prompt: newDesc || '...' }) })
      .then(r => r.json()).then(d => {
        if (d.success) {
          setAddOpen(false);
          setNewName('');
          setNewDesc('');
          // لود کن و بعد اگه خواست چت باز کن
          fetch('/api/scripts', { headers }).then(r => r.json()).then(ld => {
            if (ld.success && ld.data?.scripts?.length) {
              setScripts(ld.data.scripts);
              const created = ld.data.scripts.find(s => s.id === d.data.id);
              if (created) {
                setActiveId(created.id);
                setPromptText(created.system_prompt || '');
                if (thenOpenChat) setTimeout(() => setChatOpen(true), 100);
              }
            }
          });
          if (!thenOpenChat) toast('اسکریپت ساخته شد', 'success');
        }
      });
  };

  return (
    <div>
      {/* Script list */}
      <div className="row gap-12" style={{ overflowX: 'auto', paddingBottom: 4 }}>
        {scripts.map(s => {
          const on = activeId === s.id;
          return (
            <div key={s.id}
              className="card card-hover"
              style={{
                padding: 14, minWidth: 240, cursor: 'pointer',
                borderColor: on ? 'var(--primary)' : 'var(--border-soft)',
                background: on ? 'linear-gradient(180deg, rgba(108,99,255,0.16), rgba(108,99,255,0.04))' : undefined,
                position: 'relative', opacity: s.is_active ? 1 : 0.5,
              }}
              onClick={() => setActiveId(s.id)}>
              {on && <span style={{ position: 'absolute', top: 10, left: 10, width: 8, height: 8, borderRadius: 50, background: 'var(--primary-2)', boxShadow: '0 0 10px var(--primary-glow)' }} />}
              <div className="row between" style={{ alignItems: 'flex-start' }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="row gap-6">
                    <div className="semi text-sm" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</div>
                    {s.is_default ? <span style={{ fontSize: 10, padding: '1px 6px', borderRadius: 10, background: 'rgba(99,102,241,0.2)', color: '#818CF8' }}>پیش‌فرض</span> : null}
                    {s.campaign_keyword ? <span style={{ fontSize: 10, padding: '1px 6px', borderRadius: 10, background: 'rgba(52,211,153,0.15)', color: '#34D399' }}>#{s.campaign_keyword}</span> : null}
                  </div>
                  <div className="text-xs text-3 mt-4">{s.updated_at ? s.updated_at.slice(0, 16) : ''}</div>
                </div>
                <div className="row gap-4" onClick={e => e.stopPropagation()}>
                  <Toggle on={!!s.is_active} onChange={(v) => toggleActive(s.id, v)} />
                  {!s.is_default && (
                    <button
                      onClick={() => deleteScript(s.id, s.name)}
                      className="icon-btn"
                      style={{ width: 24, height: 24, color: '#F87171' }}
                      title="حذف">
                      <Icon name="trash-2" size={12} />
                    </button>
                  )}
                </div>
              </div>
            </div>
          );
        })}
        <div onClick={() => setAddOpen(true)}
          className="card card-hover"
          style={{ padding: 14, minWidth: 180, cursor: 'pointer', borderStyle: 'dashed', display: 'grid', placeItems: 'center', color: 'var(--text-3)' }}>
          <div style={{ textAlign: 'center' }}>
            <Icon name="plus" size={22} />
            <div className="text-sm semi mt-8">اسکریپت جدید</div>
          </div>
        </div>
      </div>

      {/* Active script header */}
      {active && (
        <div className="card mt-16" style={{ padding: '18px 22px' }}>
          <div className="row between">
            <div>
              <div className="row gap-12">
                <div style={{ width: 44, height: 44, borderRadius: 12, background: 'linear-gradient(135deg, var(--primary), #4F46E5)', display: 'grid', placeItems: 'center' }}>
                  <Icon name="file-text" size={20} color="#fff" />
                </div>
                <div>
                  <div className="bold" style={{ fontSize: 16 }}>{active.name}</div>
                  <div className="text-xs text-3 mt-4">{active.updated_at ? active.updated_at.slice(0, 16) : ''}</div>
                </div>
              </div>
            </div>
            <div className="row gap-8">
              <Button kind="ghost" icon="bot" onClick={() => setChatOpen(true)}>ساخت با AI</Button>
              <Button kind="primary" icon="save" onClick={savePrompt}>{saving ? 'در حال ذخیره...' : 'ذخیره تغییرات'}</Button>
            </div>
          </div>
        </div>
      )}

      {/* Tabs */}
      {!active && (
        <div className="text-sm text-3 mt-24" style={{ textAlign: 'center', padding: 40 }}>در حال بارگذاری...</div>
      )}
      {active && (
        <React.Fragment>
          <div className="row mt-24">
            <div className="tabs">
              {tabs.map(t => (
                <button key={t.id} className={`tab ${tab === t.id ? 'active' : ''}`} onClick={() => setTab(t.id)}>
                  <Icon name={t.icon} size={13} />&nbsp;&nbsp;{t.name}
                </button>
              ))}
            </div>
          </div>

          <div className="mt-16">
            {tab === 'prompt' && (
              <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
                {/* کلمه کلیدی تریگر */}
                <div style={{ padding: '12px 16px', background: 'rgba(255,255,255,0.03)', borderBottom: '1px solid var(--border-soft)' }} className="row gap-12">
                  <div className="row gap-8" style={{ flex: 1, alignItems: 'center' }}>
                    <span className="text-xs text-3 semi" style={{ whiteSpace: 'nowrap' }}>کلمه کلیدی شروع:</span>
                    <input
                      value={keyword}
                      onChange={e => setKeyword(e.target.value)}
                      placeholder="مثلا: ۱۰ یا وبینار یا طلا"
                      style={{
                        flex: 1, maxWidth: 240, background: 'rgba(255,255,255,0.06)',
                        border: keyword ? '1px solid rgba(99,102,241,0.5)' : '1px solid rgba(255,255,255,0.1)',
                        borderRadius: 7, padding: '5px 10px', color: 'var(--text-1)',
                        fontSize: 13, outline: 'none', direction: 'rtl',
                      }}
                    />
                    {keyword && (
                      <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 10, background: 'rgba(99,102,241,0.2)', color: '#818CF8' }}>
                        هر کاربری که «{keyword}» بفرسته این اسکریپت اجرا می‌شه
                      </span>
                    )}
                  </div>
                  <span className="text-xs text-3 mono">{promptText.length} کاراکتر</span>
                </div>
                <textarea
                  value={promptText}
                  onChange={e => setPromptText(e.target.value)}
                  style={{
                    width: '100%', minHeight: 520, background: 'transparent', border: 'none',
                    padding: '16px 20px', color: 'var(--text-1)', fontSize: 13, lineHeight: 1.8,
                    resize: 'vertical', outline: 'none', direction: 'rtl', fontFamily: 'Vazirmatn, sans-serif',
                    boxSizing: 'border-box',
                  }}
                />
              </div>
            )}
            {tab === 'objections' && <ObjectionsTab />}
            {tab === 'personas' && <PersonasTab />}
          </div>
        </React.Fragment>
      )}

      {chatOpen && (
        <ScriptBuilderChat
          scriptId={activeId}
          currentScript={promptText}
          onApply={(newScript) => { setPromptText(newScript); setScripts(prev => prev.map(s => s.id === activeId ? { ...s, system_prompt: newScript } : s)); }}
          onClose={() => setChatOpen(false)}
          headers={{ 'Content-Type': 'application/json', Authorization: `Bearer ${localStorage.getItem(window.TOKEN_KEY)}` }}
        />
      )}

      <Modal open={addOpen} onClose={() => setAddOpen(false)} title="ساخت اسکریپت جدید" footer={
        <>
          <Button kind="primary" icon="bot" onClick={() => create(true)}>ساخت با AI</Button>
          <Button kind="secondary" onClick={() => create(false)}>ساخت خالی</Button>
          <Button kind="ghost" onClick={() => setAddOpen(false)}>انصراف</Button>
        </>
      }>
        <div className="col gap-16">
          <Field label="نام اسکریپت">
            <input
              className="input"
              placeholder="مثلا اسکریپت کمپین تابستان"
              value={newName}
              onChange={e => setNewName(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && create(true)}
            />
          </Field>
          <div style={{ 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>ساخت با AI</strong> یه چت باز می‌شه — باهاش حرف بزن تا اسکریپتت رو از صفر بسازه.
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};

const QuestionsTab = () => {
  const { Icon, Toggle, Badge } = window.SB_UI;
  const { SCRIPT_QUESTIONS, fa } = window.SB_DATA;
  const [items, setItems] = useState(SCRIPT_QUESTIONS);
  const [dragId, setDragId] = useState(null);
  const onDragStart = (id) => setDragId(id);
  const onDragOver = (e) => e.preventDefault();
  const onDrop = (id) => {
    if (dragId === null || dragId === id) return;
    const from = items.findIndex(x => x.id === dragId);
    const to = items.findIndex(x => x.id === id);
    const next = [...items];
    const [m] = next.splice(from, 1);
    next.splice(to, 0, m);
    setItems(next);
    setDragId(null);
  };

  return (
    <div className="card" style={{ padding: 14 }}>
      <div className="text-xs text-3" style={{ padding: '6px 10px', marginBottom: 8 }}>سوالات به ترتیب از کاربر پرسیده می‌شن. برای تغییر ترتیب درگ کن.</div>
      <div className="col gap-8">
        {items.map((q, i) => (
          <div key={q.id}
            draggable
            onDragStart={() => onDragStart(q.id)}
            onDragOver={onDragOver}
            onDrop={() => onDrop(q.id)}
            style={{
              background: 'rgba(15,15,26,0.4)',
              border: '1px solid var(--border-soft)',
              borderRadius: 12,
              padding: 14,
              display: 'grid',
              gridTemplateColumns: 'auto auto 1fr auto auto',
              gap: 14,
              alignItems: 'center',
              opacity: dragId === q.id ? 0.5 : 1,
            }}>
            <span className="drag-handle"><Icon name="grip-vertical" size={16} /></span>
            <span className="mono text-xs text-3" style={{ minWidth: 24 }}>#{fa(i + 1)}</span>
            <div>
              <div className="text-sm semi">{q.text}</div>
            </div>
            <Badge kind={q.type === 'qualify' ? 'ready solid' : 'online solid'}>
              {q.type === 'qualify' ? 'واجد شرایط' : 'روانی'}
            </Badge>
            <Toggle on={q.active} onChange={(v) => setItems(items.map(x => x.id === q.id ? {...x, active: v} : x))} />
          </div>
        ))}
      </div>
    </div>
  );
};

const ObjectionsTab = () => {
  const { Icon, Button } = window.SB_UI;
  const { OBJECTIONS } = window.SB_DATA;
  const [items, setItems] = useState(OBJECTIONS);
  return (
    <div className="col gap-12">
      <div className="row between" style={{ padding: '0 4px' }}>
        <div className="text-xs text-3">برای ویرایش روی متن کلیک کن.</div>
      </div>
      {items.map(o => (
        <div key={o.id} className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 0 }}>
            <div style={{ padding: 18, background: 'rgba(15,15,26,0.4)', borderLeft: '1px solid var(--border-soft)' }}>
              <div className="text-xs text-3 semi" style={{ marginBottom: 8, textTransform: 'uppercase', letterSpacing: 0.04 }}>اعتراض / Trigger</div>
              <div className="bold" style={{ fontSize: 15 }} contentEditable suppressContentEditableWarning>«{o.trigger}»</div>
            </div>
            <div style={{ padding: 18 }}>
              <div className="row between" style={{ marginBottom: 8 }}>
                <div className="text-xs text-3 semi" style={{ textTransform: 'uppercase', letterSpacing: 0.04 }}>پاسخ توصیه شده</div>
                <button className="icon-btn" style={{ width: 28, height: 28 }}><Icon name="edit-3" size={12} /></button>
              </div>
              <div className="text-sm" style={{ lineHeight: 1.8 }} contentEditable suppressContentEditableWarning>{o.response}</div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

const RulesTab = () => {
  const { Icon, Button } = window.SB_UI;
  const { RULES, PRODUCTS, fa } = window.SB_DATA;
  return (
    <div className="col gap-12">
      <div className="text-xs text-3" style={{ padding: '0 4px' }}>اگر شرط زیر برقرار باشه، محصول مشخص شده پیشنهاد می‌شه.</div>
      {RULES.map(r => (
        <div key={r.id} className="rule-row">
          <span className="rule-kw">اگر</span>
          <select className="select" style={{ width: 'auto' }} defaultValue={r.ifField}>
            <option>بودجه</option><option>هدف</option><option>سابقه</option><option>کانال</option>
          </select>
          <select className="select" style={{ width: 'auto' }} defaultValue={r.op}>
            <option>{'>='}</option><option>{'<'}</option><option>{'='}</option><option>شامل</option>
          </select>
          <input className="input" defaultValue={r.value} />
          <span style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <span className="rule-kw">آنگاه</span>
            <select className="select" style={{ width: 'auto' }} defaultValue={r.then}>
              {PRODUCTS.map(p => <option key={p.id}>{p.name}</option>)}
            </select>
            <button className="icon-btn" style={{ width: 32, height: 32 }}><Icon name="trash-2" size={13} color="#F87171" /></button>
          </span>
        </div>
      ))}
      <button className="btn btn-ghost" style={{ alignSelf: 'flex-start' }}><Icon name="plus" size={14} /> افزودن قانون جدید</button>
    </div>
  );
};

const PersonasTab = () => {
  const { Icon, Button } = window.SB_UI;
  const { PERSONAS } = window.SB_DATA;
  return (
    <div className="grid grid-2 gap-16">
      {PERSONAS.map(p => (
        <div key={p.id} className="persona-card">
          <div className="row gap-16" style={{ alignItems: 'flex-start' }}>
            <div className="persona-avatar" style={{ background: `linear-gradient(135deg, ${p.color}, ${p.color}66)`, color: '#fff' }}>{p.emoji}</div>
            <div style={{ flex: 1 }}>
              <div className="row between">
                <div className="bold" style={{ fontSize: 15 }}>{p.name}</div>
                <button className="icon-btn" style={{ width: 30, height: 30 }}><Icon name="edit-3" size={13} /></button>
              </div>
              <div className="text-xs text-3 mono mt-4">سن: {p.age}</div>
              <div className="text-sm text-2 mt-12" style={{ lineHeight: 1.7 }}>{p.traits}</div>
              <div className="row gap-8 mt-16">
                <button className="btn btn-ghost btn-sm"><Icon name="play" size={12} /> تست در آزمایشگاه</button>
                <button className="btn btn-ghost btn-sm"><Icon name="bar-chart-2" size={12} /> آمار</button>
              </div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

// ─── Script Builder Chat ──────────────────────────────────
const ScriptBuilderChat = ({ scriptId, currentScript, onApply, onClose, headers }) => {
  const { Icon, Button } = window.SB_UI;
  const [messages, setMessages] = useState([
    { role: 'assistant', content: 'سلام! من اینجام تا کمک کنم اسکریپتت رو بسازیم یا بهتر کنیم.\n\nچی می‌خوای تغییر بدی یا بسازی؟' }
  ]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [preview, setPreview] = useState(currentScript);
  const [applied, setApplied] = useState(false);
  const [copied, setCopied] = useState(false);
  const bottomRef = useRef(null);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const send = async () => {
    if (!input.trim() || loading) return;
    const userMsg = { role: 'user', content: input };
    const newMessages = [...messages, userMsg];
    setMessages(newMessages);
    setInput('');
    setLoading(true);
    setApplied(false);

    try {
      const res = await fetch('/api/scripts/build-chat', {
        method: 'POST', headers,
        body: JSON.stringify({
          messages: newMessages.map(m => ({ role: m.role, content: m.content })),
          currentScript: preview,
        }),
      });
      const d = await res.json();
      if (d.success) {
        const reply = d.data.reply;
        const newScript = d.data.suggestedScript;
        setMessages(prev => [...prev, {
          role: 'assistant',
          content: reply,
          hasScript: !!newScript,
        }]);
        if (newScript) {
          setPreview(newScript);
        }
      }
    } finally {
      setLoading(false);
    }
  };

  const handleApply = () => {
    onApply(preview);        // promptText رو در parent آپدیت کن
    setApplied(true);        // نشانگر "اعمال شد" نشون بده
  };

  const handleCopy = () => {
    // روش اول: clipboard API
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(preview).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      }).catch(() => fallbackCopy());
    } else {
      fallbackCopy();
    }
  };

  const fallbackCopy = () => {
    const ta = document.createElement('textarea');
    ta.value = preview;
    ta.style.position = 'fixed';
    ta.style.opacity = '0';
    document.body.appendChild(ta);
    ta.focus();
    ta.select();
    document.execCommand('copy');
    document.body.removeChild(ta);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.85)', display: 'flex', flexDirection: 'row-reverse', alignItems: 'stretch',
    }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'row-reverse', maxWidth: '100%', overflow: 'hidden' }}>

        {/* چت */}
        <div style={{ width: 420, flexShrink: 0, display: 'flex', flexDirection: 'column', background: '#13132a' }}>
          {/* هدر */}
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border-soft)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 34, height: 34, borderRadius: 10, background: 'linear-gradient(135deg,#6C63FF,#4F46E5)', display: 'grid', placeItems: 'center' }}>
              <Icon name="bot" size={16} color="#fff" />
            </div>
            <div style={{ flex: 1 }}>
              <div className="semi" style={{ fontSize: 14 }}>دستیار ساخت اسکریپت</div>
              <div className="text-xs text-3">باهاش حرف بزن، اسکریپت می‌سازه</div>
            </div>
            <button className="icon-btn" onClick={onClose} style={{ width: 30, height: 30 }}><Icon name="x" size={14} /></button>
          </div>

          {/* پیام‌ها */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '16px 14px', display: 'flex', flexDirection: 'column', gap: 12 }}>
            {messages.map((m, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-start' : 'flex-end' }}>
                <div style={{
                  maxWidth: '85%', padding: '10px 14px', borderRadius: m.role === 'user' ? '12px 12px 12px 2px' : '12px 12px 2px 12px',
                  background: m.role === 'user' ? 'rgba(255,255,255,0.07)' : 'rgba(108,99,255,0.2)',
                  fontSize: 13, lineHeight: 1.7, whiteSpace: 'pre-wrap', direction: 'rtl',
                }}>
                  {m.content}
                  {m.suggested && (
                    <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid rgba(255,255,255,0.1)' }}>
                      <button
                        onClick={() => onApply(m.suggested)}
                        style={{ width: '100%', padding: '7px 0', borderRadius: 8, border: 'none', background: 'rgba(52,211,153,0.2)', color: '#34D399', fontSize: 12, cursor: 'pointer' }}>
                        ✓ اعمال این اسکریپت
                      </button>
                    </div>
                  )}
                </div>
              </div>
            ))}
            {loading && (
              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <div style={{ padding: '10px 16px', borderRadius: '12px 12px 2px 12px', background: 'rgba(108,99,255,0.2)', fontSize: 13, color: 'var(--text-3)' }}>
                  در حال فکر کردن...
                </div>
              </div>
            )}
            <div ref={bottomRef} />
          </div>

          {/* ورودی */}
          <div style={{ padding: '12px 14px', borderTop: '1px solid var(--border-soft)', display: 'flex', gap: 8 }}>
            <textarea
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
              placeholder="بنویس چی می‌خوای... (Enter برای ارسال)"
              style={{
                flex: 1, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)',
                borderRadius: 10, padding: '9px 12px', color: 'var(--text-1)', fontSize: 13,
                resize: 'none', outline: 'none', direction: 'rtl', fontFamily: 'Vazirmatn, sans-serif', rows: 2,
              }}
              rows={2}
            />
            <button
              onClick={send} disabled={loading || !input.trim()}
              style={{ width: 40, borderRadius: 10, border: 'none', background: loading ? 'rgba(108,99,255,0.3)' : 'var(--primary)', color: '#fff', cursor: 'pointer' }}>
              <Icon name="send" size={15} />
            </button>
          </div>
        </div>

        {/* پیش‌نمایش اسکریپت */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: '#0c0c1a', borderRight: '1px solid rgba(255,255,255,0.08)' }}>
          {/* هدر */}
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border-soft)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
            <div>
              <div className="semi" style={{ fontSize: 14 }}>پیش‌نمایش اسکریپت</div>
              <div className="text-xs text-3">{preview.length} کاراکتر</div>
            </div>
            <div className="row gap-8">
              <button onClick={handleCopy}
                style={{ padding: '6px 14px', borderRadius: 8, border: 'none', cursor: 'pointer', fontSize: 12,
                  background: copied ? 'rgba(52,211,153,0.2)' : 'rgba(255,255,255,0.08)',
                  color: copied ? '#34D399' : 'var(--text-2)', transition: 'all 0.2s' }}>
                {copied ? '✓ کپی شد' : '📋 کپی'}
              </button>
              <button onClick={handleApply}
                style={{ padding: '6px 16px', borderRadius: 8, border: 'none', cursor: 'pointer', fontSize: 12, fontWeight: 600,
                  background: applied ? 'rgba(52,211,153,0.3)' : 'rgba(52,211,153,0.15)',
                  color: '#34D399', transition: 'all 0.2s' }}>
                {applied ? '✓ اعمال شد — ذخیره کنید' : '↩ اعمال روی اسکریپت'}
              </button>
            </div>
          </div>

          {/* نشانگر اعمال شدن */}
          {applied && (
            <div style={{ padding: '8px 18px', background: 'rgba(52,211,153,0.08)', borderBottom: '1px solid rgba(52,211,153,0.2)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span className="text-xs" style={{ color: '#34D399' }}>✓ اسکریپت اعمال شد. برای ذخیره دائمی دکمه «ذخیره تغییرات» رو بزن.</span>
              <button onClick={onClose} style={{ padding: '3px 10px', borderRadius: 6, border: 'none', background: 'rgba(52,211,153,0.2)', color: '#34D399', fontSize: 11, cursor: 'pointer' }}>بستن و ذخیره</button>
            </div>
          )}

          <textarea
            value={preview}
            onChange={e => { setPreview(e.target.value); setApplied(false); }}
            style={{
              flex: 1, background: 'transparent', border: 'none', padding: '16px 20px',
              color: 'var(--text-1)', fontSize: 13, lineHeight: 1.8, resize: 'none',
              outline: 'none', direction: 'rtl', fontFamily: 'Vazirmatn, sans-serif',
            }}
          />
        </div>
      </div>
    </div>
  );
};

window.Scripts = Scripts;
