// ── App shell: nav, more/settings, business switcher, tweaks ──

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "مونوکروم",
  "dark": false,
  "radius": 18,
  "density": "متعادل"
}/*EDITMODE-END*/;

const TABS = [
  { id: 'home',      label: 'داشبورد',  icon: 'home' },
  { id: 'inbox',     label: 'گفتگوها',  icon: 'chat' },
  { id: 'customers', label: 'مشتریان',  icon: 'users' },
  { id: 'more',      label: 'بیشتر',    icon: 'more' },
];
const TAB_TITLE = { inbox: 'گفتگوها', customers: 'مشتریان', more: 'بیشتر' };

function TopBar({ biz, onSwitch, dark, onBell, hasNotif }) {
  return (
    <div style={{
      paddingTop: 52, padding: '52px 16px 10px', display: 'flex',
      alignItems: 'center', justifyContent: 'space-between',
      background: 'var(--surface)', borderBottom: '1px solid var(--line)',
    }}>
      <button onClick={onSwitch} style={{
        display: 'flex', alignItems: 'center', gap: 9, background: 'none',
        border: 'none', cursor: 'pointer', font: 'inherit', padding: 0,
      }}>
        <div style={{
          width: 34, height: 34, borderRadius: 10, background: 'var(--accent)',
          color: 'var(--accent-ink)', display: 'flex', alignItems: 'center',
          justifyContent: 'center', fontWeight: 800, fontSize: 16,
        }}>{biz.mono}</div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)', display: 'flex', alignItems: 'center', gap: 4, whiteSpace: 'nowrap' }}>
            {biz.name}<Icon name="chevron-down" size={14} style={{ color: 'var(--ink-3)' }} />
          </div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-3)', whiteSpace: 'nowrap', direction: 'ltr', textAlign: 'right' }}>{biz.channel}</div>
        </div>
      </button>
      <button onClick={onBell} style={{
        position: 'relative', width: 40, height: 40, borderRadius: '50%',
        background: 'var(--field)', border: '1px solid var(--line)', cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)',
      }}>
        <Icon name="bell" size={20} />
        {hasNotif && <span style={{ position: 'absolute', top: 9, left: 10, width: 7, height: 7, borderRadius: '50%', background: 'var(--accent)', border: '2px solid var(--surface)' }} />}
      </button>
    </div>
  );
}

function BottomNav({ tab, onTab }) {
  return (
    <div style={{
      display: 'flex', borderTop: '1px solid var(--line)', background: 'var(--surface)',
      padding: '8px 8px 26px', flexShrink: 0,
    }}>
      {TABS.map(t => {
        const on = tab === t.id;
        return (
          <button key={t.id} onClick={() => onTab(t.id)} style={{
            flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            background: 'none', border: 'none', cursor: 'pointer', padding: '6px 0',
            color: on ? 'var(--ink)' : 'var(--ink-3)',
          }}>
            <Icon name={t.icon} size={23} sw={on ? 2 : 1.6} />
            <span style={{ fontSize: 10, fontWeight: on ? 700 : 500 }}>{t.label}</span>
          </button>
        );
      })}
    </div>
  );
}

function BizSheet({ current, onPick, onClose, onAdd }) {
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 200, background: 'rgba(0,0,0,0.4)',
      display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'var(--surface)', borderTopLeftRadius: 24, borderTopRightRadius: 24,
        padding: '10px 16px 34px', borderTop: '1px solid var(--line)',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--line-2)', margin: '4px auto 16px' }} />
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 12 }}>انتخاب کسب‌وکار</div>
        {BUSINESSES.map(b => {
          const on = b.id === current.id;
          return (
            <button key={b.id} onClick={() => onPick(b)} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 12, font: 'inherit',
              background: on ? 'var(--surface-2)' : 'none', border: '1px solid ' + (on ? 'var(--line-2)' : 'transparent'),
              borderRadius: 'var(--r-sm)', padding: '11px 12px', cursor: 'pointer', marginBottom: 6, textAlign: 'right',
            }}>
              <div style={{ width: 40, height: 40, borderRadius: 11, background: on ? 'var(--accent)' : 'var(--surface-2)', color: on ? 'var(--accent-ink)' : 'var(--ink)', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800 }}>{b.mono}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--ink)' }}>{b.name}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{b.channel} · {fa((b.members || 0).toLocaleString('en'))} مشتری</div>
              </div>
              {on && <Icon name="check" size={20} style={{ color: 'var(--accent)' }} />}
            </button>
          );
        })}
        <button onClick={onAdd} style={{
          width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          font: 'inherit', fontSize: 13.5, fontWeight: 600, color: 'var(--ink-2)', marginTop: 6,
          background: 'var(--field)', border: '1px dashed var(--line-2)', borderRadius: 'var(--r-sm)', padding: '13px', cursor: 'pointer',
        }}><Icon name="plus" size={18} />افزودن کسب‌وکار جدید</button>
      </div>
    </div>
  );
}

function GroupRow({ icon, title, detail, right, onClick, last }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', display: 'flex', alignItems: 'center', gap: 12, font: 'inherit',
      background: 'none', border: 'none', borderBottom: last ? 'none' : '1px solid var(--line)',
      padding: '13px 14px', cursor: onClick ? 'pointer' : 'default', textAlign: 'right',
    }}>
      <div style={{ width: 32, height: 32, borderRadius: 9, background: 'var(--surface-2)', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)', flexShrink: 0 }}>
        <Icon name={icon} size={17} />
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)' }}>{title}</div>
        {detail && <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 1 }}>{detail}</div>}
      </div>
      {right}
    </button>
  );
}

function MoreScreen({ biz, dark, onToggleDark, onSwitch, assistant, onOpenAssistant, onOpenScreen }) {
  return (
    <div style={{ padding: '0 14px 16px' }}>
      {/* owner */}
      <Card style={{ display: 'flex', alignItems: 'center', gap: 13, marginBottom: 18 }}>
        <Avatar mono="ع" size={52} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--ink)' }}>علی رضایی</div>
          <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>مدیر · ۰۹۱۲ ۳۴۵ ۶۷۸۹</div>
        </div>
        <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--accent-ink)', background: 'var(--accent)', padding: '4px 10px', borderRadius: 999 }}>پلن حرفه‌ای</span>
      </Card>

      <SectionLabel>کسب‌وکار فعال</SectionLabel>
      <Card pad={false} style={{ overflow: 'hidden', marginBottom: 18 }}>
        <GroupRow icon="building" title={biz.name} detail={biz.kind + ' · ' + biz.channel} onClick={onSwitch}
          right={<Icon name="chevron-left" size={18} style={{ color: 'var(--ink-3)' }} />} />
        <GroupRow icon="robot" title="مدیریت کانال‌ها" detail={biz.channel} onClick={() => onOpenScreen('channels')}
          right={<Icon name="chevron-left" size={18} style={{ color: 'var(--ink-3)' }} />} />
        <GroupRow icon="users" title="اعضای تیم" detail="۳ اپراتور فعال" onClick={() => onOpenScreen('team')} last
          right={<Icon name="chevron-left" size={18} style={{ color: 'var(--ink-3)' }} />} />
      </Card>

      <SectionLabel>نمایش</SectionLabel>
      <Card pad={false} style={{ overflow: 'hidden', marginBottom: 18 }}>
        <GroupRow icon={dark ? 'moon' : 'sun'} title="حالت تیره" last
          right={
            <button onClick={onToggleDark} style={{
              width: 46, height: 28, borderRadius: 999, border: 'none', cursor: 'pointer', position: 'relative',
              background: dark ? 'var(--accent)' : 'var(--surface-2)', transition: 'background .2s', flexShrink: 0,
            }}>
              <span style={{
                position: 'absolute', top: 3, width: 22, height: 22, borderRadius: '50%', background: '#fff',
                boxShadow: '0 1px 3px rgba(0,0,0,0.25)', transition: 'all .2s',
                right: dark ? 3 : 21,
              }} />
            </button>
          } />
      </Card>

      <SectionLabel>هوش مصنوعی</SectionLabel>
      <Card pad={false} style={{ overflow: 'hidden', marginBottom: 18 }}>
        <GroupRow icon="robot" title="دستیار فروش هوشمند" detail={assistant ? 'روشن — پاسخ خودکار فعال' : 'خاموش'} onClick={onOpenAssistant} last
          right={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
            <span style={{ fontSize: 11, fontWeight: 600, color: assistant ? 'var(--ink)' : 'var(--ink-3)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: assistant ? 'var(--accent)' : 'var(--ink-3)' }} />{assistant ? 'روشن' : 'خاموش'}
            </span>
            <Icon name="chevron-left" size={18} style={{ color: 'var(--ink-3)' }} />
          </span>} />
      </Card>

      <SectionLabel>پلتفرم</SectionLabel>
      <Card pad={false} style={{ overflow: 'hidden', marginBottom: 18 }}>
        <GroupRow icon="bolt" title="اتوماسیون و فلوساز" onClick={() => onOpenScreen('automation')} right={<Icon name="chevron-left" size={18} style={{ color: 'var(--ink-3)' }} />} />
        <GroupRow icon="shield" title="امنیت و دسترسی‌ها" onClick={() => onOpenScreen('security')} last right={<Icon name="chevron-left" size={18} style={{ color: 'var(--ink-3)' }} />} />
      </Card>

      <button style={{
        width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        font: 'inherit', fontSize: 13.5, fontWeight: 600, color: 'var(--ink-2)',
        background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r)', padding: '14px', cursor: 'pointer',
      }}><Icon name="logout" size={18} />خروج از حساب</button>
      <div style={{ textAlign: 'center', fontSize: 10.5, color: 'var(--ink-3)', marginTop: 16 }}>روبیکا CRM · نسخه ۱.۰ · ۱۴۰۴</div>
    </div>
  );
}

function ScreenHeader({ title, onBack }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 12px', borderBottom: '1px solid var(--line)', background: 'var(--surface)' }}>
      <button onClick={onBack} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink)', padding: 4, display: 'flex' }}>
        <Icon name="chevron-right" size={24} />
      </button>
      <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)' }}>{title}</span>
    </div>
  );
}

function SettingRadio({ label, value, options, onChange }) {
  return (
    <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--line)' }}>
      <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 9 }}>{label}</div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {options.map(o => {
          const on = o === value;
          return (
            <button key={o} onClick={() => onChange(o)} style={{
              font: 'inherit', fontSize: 12.5, fontWeight: on ? 700 : 500, cursor: 'pointer',
              padding: '7px 13px', borderRadius: 999,
              border: '1px solid ' + (on ? 'var(--accent)' : 'var(--line-2)'),
              background: on ? 'var(--accent)' : 'var(--surface)',
              color: on ? 'var(--accent-ink)' : 'var(--ink-2)',
            }}>{o}</button>
          );
        })}
      </div>
    </div>
  );
}

function AssistantSettings({ assistant, onToggle, onBack }) {
  const [tone, setTone] = useState('دوستانه');
  const [scope, setScope] = useState('فقط سؤال‌های متداول');
  const [handoff, setHandoff] = useState('بعد از ۲ پیام');
  const [welcome, setWelcome] = useState('سلام 🌿 به پشتیبانی خوش آمدید؛ چطور می‌تونم کمکتون کنم؟');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="دستیار فروش هوشمند" onBack={onBack} />
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--bg)', padding: '14px' }}>
        {/* master toggle */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12, padding: '14px',
          background: 'var(--surface)', borderRadius: 'var(--r)',
          border: '1px solid ' + (assistant ? 'var(--accent)' : 'var(--line)'), marginBottom: 18,
        }}>
          <div style={{ width: 40, height: 40, borderRadius: 11, flexShrink: 0,
            background: assistant ? 'var(--accent)' : 'var(--surface-2)', color: assistant ? 'var(--accent-ink)' : 'var(--ink-2)',
            border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="robot" size={21} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--ink)' }}>پاسخ‌دهی خودکار</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{assistant ? 'فعال است' : 'غیرفعال است'}</div>
          </div>
          <button onClick={onToggle} style={{
            width: 46, height: 28, borderRadius: 999, border: 'none', cursor: 'pointer', position: 'relative',
            background: assistant ? 'var(--accent)' : 'var(--surface-2)', transition: 'background .2s', flexShrink: 0,
          }}>
            <span style={{ position: 'absolute', top: 3, width: 22, height: 22, borderRadius: '50%', background: '#fff',
              boxShadow: '0 1px 3px rgba(0,0,0,0.25)', transition: 'all .2s', right: assistant ? 3 : 21 }} />
          </button>
        </div>

        <SectionLabel>رفتار دستیار</SectionLabel>
        <Card pad={false} style={{ overflow: 'hidden', marginBottom: 18 }}>
          <SettingRadio label="لحن پاسخ" value={tone} options={['رسمی', 'دوستانه', 'کوتاه']} onChange={setTone} />
          <SettingRadio label="محدوده‌ی پاسخ خودکار" value={scope} options={['همه‌ی گفتگوها', 'فقط سؤال‌های متداول', 'فقط خارج از ساعت کاری']} onChange={setScope} />
          <div style={{ padding: '12px 14px' }}>
            <SettingRadio label="واگذاری به اپراتور انسانی" value={handoff} options={['هرگز', 'بعد از ۲ پیام', 'در صورت نارضایتی']} onChange={setHandoff} />
          </div>
        </Card>

        <SectionLabel>پیام خوش‌آمد</SectionLabel>
        <Card style={{ marginBottom: 18 }}>
          <textarea value={welcome} onChange={e => setWelcome(e.target.value)} rows={3} style={{
            width: '100%', border: '1px solid var(--line)', background: 'var(--field)', borderRadius: 'var(--r-sm)',
            padding: '11px 13px', font: 'inherit', fontSize: 13, color: 'var(--ink)', outline: 'none', resize: 'none', lineHeight: 1.8,
          }} />
        </Card>

        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.8, padding: '0 2px' }}>
          <Icon name="info" size={15} style={{ flexShrink: 0, marginTop: 2 }} />
          دستیار از محتوای تعامل هر مشتری برای پاسخ شخصی‌سازی‌شده استفاده می‌کند و سرنخ‌ها را برای پیگیری انسانی علامت‌گذاری می‌کند.
        </div>
      </div>
    </div>
  );
}

const ADD_PLATFORMS = [
  { id: 'rubika',   label: 'روبیکا', mono: 'R', hint: 'اتصال از طریق ربات روبیکا' },
  { id: 'telegram', label: 'تلگرام', mono: 'T', hint: 'اتصال از طریق ربات تلگرام (BotFather)' },
  { id: 'bale',     label: 'بله',    mono: 'ب', hint: 'اتصال از طریق ربات بله' },
];

function AddBusiness({ onBack, onDone }) {
  const [step, setStep] = useState(1);
  const [name, setName] = useState('');
  const [bizId, setBizId] = useState(null);
  const [busy, setBusy] = useState(false);
  const [channels, setChannels] = useState([]);   // کانال‌های متصل‌شده
  const [open, setOpen] = useState(null);          // پلتفرمی که در حال وارد کردن توکنش هستیم
  const [token, setToken] = useState('');
  const [err, setErr] = useState('');

  async function createBiz() {
    if (!name.trim() || busy) return;
    setBusy(true); setErr('');
    try {
      const r = await fetch('/api/businesses', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: name.trim() }) });
      const d = await r.json();
      if (d.ok) { setBizId(d.id); setStep(2); } else setErr(d.error || 'خطا در ساخت کسب‌وکار');
    } catch (e) { setErr('خطا در اتصال به سرور'); }
    setBusy(false);
  }

  async function connectChannel(platform) {
    if (!token.trim() || busy) return;
    setBusy(true); setErr('');
    try {
      const r = await fetch('/api/businesses/' + bizId + '/channels', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ platform, token: token.trim() }) });
      const d = await r.json();
      if (d.ok) { setChannels(cs => [...cs.filter(c => c.platform !== platform), { platform, label: d.label, username: d.username }]); setOpen(null); setToken(''); }
      else setErr(d.error || 'توکن نامعتبر است');
    } catch (e) { setErr('توکن نامعتبر یا سرور در دسترس نیست'); }
    setBusy(false);
  }

  const connectedOf = (p) => channels.find(c => c.platform === p);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title={step === 1 ? 'کسب‌وکار جدید' : 'اتصال کانال‌ها'} onBack={step === 2 ? () => setStep(1) : onBack} />
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--bg)', padding: '14px' }}>

        {step === 1 && (
          <div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginBottom: 9, marginRight: 2 }}>نام کسب‌وکار</div>
            <input value={name} onChange={e => setName(e.target.value)} placeholder="مثلاً فروشگاه آوین" style={{
              width: '100%', border: '1px solid var(--line-2)', background: 'var(--field)', borderRadius: 'var(--r-sm)',
              padding: '12px 14px', font: 'inherit', fontSize: 14, color: 'var(--ink)', outline: 'none',
            }} />
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 8, marginRight: 2, lineHeight: 1.8 }}>
              بعد از ساخت کسب‌وکار، می‌توانی کانال‌های پیام‌رسان (روبیکا، تلگرام، بله) را زیر آن وصل کنی.
            </div>
            {err && <div style={{ color: '#d9534f', fontSize: 12, marginTop: 10 }}>{err}</div>}
            <button onClick={createBiz} disabled={!name.trim() || busy} style={{
              width: '100%', marginTop: 18, font: 'inherit', fontSize: 14, fontWeight: 700,
              cursor: name.trim() && !busy ? 'pointer' : 'default',
              background: name.trim() && !busy ? 'var(--accent)' : 'var(--surface-2)',
              color: name.trim() && !busy ? 'var(--accent-ink)' : 'var(--ink-3)',
              border: 'none', borderRadius: 'var(--r)', padding: '14px',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
            }}><Icon name="arrow-up" size={17} style={{ transform: 'rotate(90deg)' }} />{busy ? 'در حال ساخت…' : 'ساخت و ادامه'}</button>
          </div>
        )}

        {step === 2 && (
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r)', marginBottom: 16 }}>
              <div style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--accent)', color: 'var(--accent-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800 }}>{(name || '؟').slice(0, 1)}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--ink)' }}>{name}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{channels.length ? fa(channels.length) + ' کانال متصل' : 'هنوز کانالی وصل نشده'}</div>
              </div>
            </div>

            <SectionLabel>کانال‌های پیام‌رسان</SectionLabel>
            {ADD_PLATFORMS.map(p => {
              const c = connectedOf(p.id);
              const isOpen = open === p.id;
              return (
                <div key={p.id} style={{ background: 'var(--surface)', border: '1px solid ' + (c ? 'var(--accent)' : 'var(--line)'), borderRadius: 'var(--r)', marginBottom: 10, overflow: 'hidden' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
                    <div style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--surface-2)', border: '1px solid var(--line)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800 }}>{p.mono}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{p.label}</div>
                      <div style={{ fontSize: 11, color: c ? 'var(--accent)' : 'var(--ink-3)' }}>{c ? '@' + c.username + ' متصل شد' : p.hint}</div>
                    </div>
                    {c ? <Icon name="check" size={20} style={{ color: 'var(--accent)' }} />
                       : <button onClick={() => { setOpen(isOpen ? null : p.id); setToken(''); setErr(''); }} style={{
                           font: 'inherit', fontSize: 12.5, fontWeight: 700, color: 'var(--accent-ink)', background: 'var(--accent)',
                           border: 'none', borderRadius: 10, padding: '8px 14px', cursor: 'pointer',
                         }}>{isOpen ? 'بستن' : 'اتصال'}</button>}
                  </div>
                  {isOpen && !c && (
                    <div style={{ padding: '0 14px 14px' }}>
                      <input value={token} onChange={e => setToken(e.target.value)} placeholder={'توکن ربات ' + p.label} dir="ltr" style={{
                        width: '100%', border: '1px solid var(--line-2)', background: 'var(--field)', borderRadius: 'var(--r-sm)',
                        padding: '11px 13px', font: 'inherit', fontSize: 13, color: 'var(--ink)', outline: 'none', textAlign: 'left',
                      }} />
                      {err && <div style={{ color: '#d9534f', fontSize: 11.5, marginTop: 8 }}>{err}</div>}
                      <button onClick={() => connectChannel(p.id)} disabled={!token.trim() || busy} style={{
                        width: '100%', marginTop: 10, font: 'inherit', fontSize: 13, fontWeight: 700,
                        cursor: token.trim() && !busy ? 'pointer' : 'default',
                        background: token.trim() && !busy ? 'var(--accent)' : 'var(--surface-2)',
                        color: token.trim() && !busy ? 'var(--accent-ink)' : 'var(--ink-3)',
                        border: 'none', borderRadius: 10, padding: '11px',
                      }}>{busy ? 'در حال بررسی توکن…' : 'بررسی و اتصال'}</button>
                    </div>
                  )}
                </div>
              );
            })}

            <button onClick={() => onDone(bizId)} style={{
              width: '100%', marginTop: 12, font: 'inherit', fontSize: 14, fontWeight: 700,
              background: 'var(--accent)', color: 'var(--accent-ink)', border: 'none', borderRadius: 'var(--r)',
              padding: '14px', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
            }}><Icon name="check" size={18} />{channels.length ? 'تمام' : 'بعداً وصل می‌کنم'}</button>
          </div>
        )}
      </div>
    </div>
  );
}

const NOTIF_KIND = {
  app:    { label: 'نرم‌افزار', color: 'var(--accent)' },
  rubika: { label: 'روبیکا',    color: '#7c5cff' },
};

function NotificationsScreen({ onBack }) {
  const [items, setItems] = useState(NOTIFICATIONS);
  const unread = items.filter(n => n.unread).length;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="اعلان‌ها" onBack={onBack} />
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--bg)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px' }}>
          <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>
            {unread ? fa(unread) + ' اعلان خوانده‌نشده' : 'همه‌ی اعلان‌ها خوانده شده'}
          </span>
          {unread > 0 && (
            <button onClick={() => setItems(it => it.map(n => ({ ...n, unread: false })))} style={{
              font: 'inherit', fontSize: 11.5, fontWeight: 600, color: 'var(--accent)',
              background: 'none', border: 'none', cursor: 'pointer',
            }}>علامت‌گذاری همه به‌عنوان خوانده‌شده</button>
          )}
        </div>
        {items.map((n, i) => {
          const k = NOTIF_KIND[n.kind] || NOTIF_KIND.app;
          return (
            <div key={n.id} onClick={() => setItems(it => it.map(x => x.id === n.id ? { ...x, unread: false } : x))} style={{
              display: 'flex', gap: 12, padding: '14px 16px', cursor: 'pointer',
              borderTop: i ? '1px solid var(--line)' : '1px solid var(--line)',
              background: n.unread ? 'var(--surface)' : 'transparent',
            }}>
              <div style={{ width: 38, height: 38, borderRadius: 11, flexShrink: 0, background: 'var(--surface-2)', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)' }}>
                <Icon name={n.icon} size={19} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 3 }}>
                  <span style={{ fontSize: 9.5, fontWeight: 700, color: k.color, border: '1px solid ' + k.color, borderRadius: 5, padding: '1px 6px' }}>{k.label}</span>
                  <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)', lineHeight: 1.4 }}>{n.title}</span>
                  {n.unread && <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--accent)', flexShrink: 0, marginRight: 'auto' }} />}
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.8 }}>{n.body}</div>
                <div style={{ fontSize: 10.5, color: 'var(--ink-3)', marginTop: 5 }}>{n.time}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function TeamScreen({ onBack }) {
  const [toast, setToast] = useState('');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', position: 'relative' }}>
      {toast && <Toast msg={toast} />}
      <ScreenHeader title="اعضای تیم" onBack={onBack} />
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--bg)', padding: '14px' }}>
        <div style={{ display: 'flex', gap: 'var(--gap)', marginBottom: 18 }}>
          <Card style={{ flex: 1, textAlign: 'center' }}>
            <div style={{ fontSize: 24, fontWeight: 800, color: 'var(--ink)' }}>{fa(TEAM.length)}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-2)', marginTop: 2 }}>اپراتور</div>
          </Card>
          <Card style={{ flex: 1, textAlign: 'center' }}>
            <div style={{ fontSize: 24, fontWeight: 800, color: 'var(--ink)' }}>{fa(TEAM.filter(u => u.online).length)}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-2)', marginTop: 2 }}>آنلاین</div>
          </Card>
        </div>
        <SectionLabel>اعضا</SectionLabel>
        <Card pad={false} style={{ overflow: 'hidden', marginBottom: 18 }}>
          {TEAM.map((u, i) => (
            <div key={u.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderTop: i ? '1px solid var(--line)' : 'none' }}>
              <div style={{ position: 'relative' }}>
                <Avatar mono={u.mono} size={42} />
                <span style={{ position: 'absolute', bottom: 0, right: 0, width: 11, height: 11, borderRadius: '50%', background: u.online ? '#1f8a5b' : 'var(--ink-3)', border: '2px solid var(--surface)' }} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{u.name}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 1 }}>{u.role} · {fa(u.convs)} مکالمه · پاسخ‌دهی {fa(u.rate)}٪</div>
              </div>
            </div>
          ))}
        </Card>
        <button onClick={() => setToast('دعوت‌نامه ارسال شد')} style={{
          width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          font: 'inherit', fontSize: 13.5, fontWeight: 700, color: 'var(--accent-ink)',
          background: 'var(--accent)', border: 'none', borderRadius: 'var(--r)', padding: '14px', cursor: 'pointer',
        }}><Icon name="plus" size={18} />دعوت عضو جدید</button>
      </div>
    </div>
  );
}

function TicketsScreen({ onBack }) {
  const PR = { 'بالا': '#d9534f', 'متوسط': 'var(--ink-2)', 'پایین': 'var(--ink-3)' };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="تیکت‌ها و پشتیبانی" onBack={onBack} />
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--bg)', padding: '14px' }}>
        {TICKETS.map(t => (
          <Card key={t.id} style={{ marginBottom: 10 }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10 }}>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.5 }}>{t.subject}</span>
              <span style={{ fontSize: 10, fontWeight: 700, flexShrink: 0, color: t.status === 'open' ? 'var(--accent-ink)' : 'var(--ink-2)', background: t.status === 'open' ? 'var(--accent)' : 'var(--surface-2)', borderRadius: 999, padding: '3px 9px' }}>
                {t.status === 'open' ? 'باز' : 'حل‌شده'}
              </span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8, fontSize: 11.5, color: 'var(--ink-3)' }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: PR[t.priority] }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: PR[t.priority] }} />اولویت {t.priority}
              </span>
              <span>·</span><span>{t.customer}</span><span>·</span><span>{t.time}</span>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function AutomationScreen({ onBack }) {
  const [flows, setFlows] = useState(AUTOMATIONS);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="اتوماسیون و فلوساز" onBack={onBack} />
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--bg)', padding: '14px' }}>
        <SectionLabel>فلوهای فعال</SectionLabel>
        <Card pad={false} style={{ overflow: 'hidden' }}>
          {flows.map((f, i) => (
            <div key={f.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', borderTop: i ? '1px solid var(--line)' : 'none' }}>
              <div style={{ width: 32, height: 32, borderRadius: 9, background: 'var(--surface-2)', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)', flexShrink: 0 }}>
                <Icon name="bolt" size={16} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{f.name}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>{f.trigger} · {fa(f.runs)} اجرا</div>
              </div>
              <button onClick={() => setFlows(fl => fl.map(x => x.id === f.id ? { ...x, on: !x.on } : x))} style={{
                width: 46, height: 28, borderRadius: 999, border: 'none', cursor: 'pointer', position: 'relative', flexShrink: 0,
                background: f.on ? 'var(--accent)' : 'var(--surface-2)', transition: 'background .2s',
              }}>
                <span style={{ position: 'absolute', top: 3, width: 22, height: 22, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,0.25)', transition: 'all .2s', right: f.on ? 3 : 21 }} />
              </button>
            </div>
          ))}
        </Card>
        <button style={{
          width: '100%', marginTop: 18, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          font: 'inherit', fontSize: 13.5, fontWeight: 600, color: 'var(--ink-2)',
          background: 'var(--field)', border: '1px dashed var(--line-2)', borderRadius: 'var(--r)', padding: '13px', cursor: 'pointer',
        }}><Icon name="plus" size={18} />ساخت فلوی جدید</button>
      </div>
    </div>
  );
}

function SecurityScreen({ onBack }) {
  const [twoFA, setTwoFA] = useState(true);
  const Sw = ({ on, onClick }) => (
    <button onClick={onClick} style={{ width: 46, height: 28, borderRadius: 999, border: 'none', cursor: 'pointer', position: 'relative', flexShrink: 0, background: on ? 'var(--accent)' : 'var(--surface-2)', transition: 'background .2s' }}>
      <span style={{ position: 'absolute', top: 3, width: 22, height: 22, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,0.25)', transition: 'all .2s', right: on ? 3 : 21 }} />
    </button>
  );
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="امنیت و دسترسی‌ها" onBack={onBack} />
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--bg)', padding: '14px' }}>
        <SectionLabel>ورود و احراز هویت</SectionLabel>
        <Card pad={false} style={{ overflow: 'hidden', marginBottom: 18 }}>
          <GroupRow icon="shield" title="احراز هویت دو مرحله‌ای" detail={twoFA ? 'فعال' : 'غیرفعال'} last right={<Sw on={twoFA} onClick={() => setTwoFA(v => !v)} />} />
        </Card>
        <SectionLabel>نشست‌های فعال</SectionLabel>
        <Card pad={false} style={{ overflow: 'hidden', marginBottom: 18 }}>
          <GroupRow icon="phone" title="آیفون ۱۵ · تهران" detail="این دستگاه · هم‌اکنون فعال" right={<span style={{ fontSize: 11, fontWeight: 600, color: '#1f8a5b' }}>فعلی</span>} />
          <GroupRow icon="grid" title="مرورگر کروم · ویندوز" detail="۲ روز پیش" last right={<span style={{ fontSize: 11, color: '#d9534f' }}>خروج</span>} />
        </Card>
        <SectionLabel>دسترسی نقش‌ها</SectionLabel>
        <Card pad={false} style={{ overflow: 'hidden' }}>
          <GroupRow icon="users" title="مدیر" detail="دسترسی کامل" />
          <GroupRow icon="users" title="اپراتور ارشد" detail="گفتگوها، مشتریان، گزارش‌ها" />
          <GroupRow icon="users" title="اپراتور" detail="فقط گفتگوها" last />
        </Card>
      </div>
    </div>
  );
}

function BotScreen({ biz, onBack }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="بات متصل" onBack={onBack} />
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--bg)', padding: '14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px', background: 'var(--surface)', border: '1px solid var(--accent)', borderRadius: 'var(--r)', marginBottom: 18 }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--accent)', color: 'var(--accent-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="robot" size={22} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--ink)' }}>{biz.name} Bot</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 2 }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#1f8a5b' }} />آنلاین · در حال جمع‌آوری داده
            </div>
          </div>
        </div>
        <SectionLabel>اطلاعات اتصال</SectionLabel>
        <Card pad={false} style={{ overflow: 'hidden', marginBottom: 18 }}>
          <GroupRow icon="grid" title="کانال متصل" detail={biz.channel} right={<Icon name="chevron-left" size={18} style={{ color: 'var(--ink-3)' }} />} />
          <GroupRow icon="shield" title="توکن ربات" detail="••••••••••3d4e5f" />
          <GroupRow icon="users" title="اعضای کانال" detail={fa(biz.members.toLocaleString('en')) + ' عضو'} last />
        </Card>
        <SectionLabel>دسترسی‌ها</SectionLabel>
        <Card pad={false} style={{ overflow: 'hidden' }}>
          <GroupRow icon="send" title="ارسال پیام" detail="فعال" right={<Icon name="check" size={18} style={{ color: 'var(--accent)' }} />} />
          <GroupRow icon="chat" title="مدیریت پیام‌ها" detail="فعال" last right={<Icon name="check" size={18} style={{ color: 'var(--accent)' }} />} />
        </Card>
      </div>
    </div>
  );
}

function Toast({ msg }) {
  return (
    <div style={{
      position: 'absolute', bottom: 22, left: '50%', transform: 'translateX(-50%)', zIndex: 50,
      background: 'var(--ink)', color: 'var(--bg)', fontSize: 12.5, fontWeight: 600,
      padding: '10px 18px', borderRadius: 999, boxShadow: '0 4px 16px rgba(0,0,0,0.22)', whiteSpace: 'nowrap',
    }}>{msg}</div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const dark = t.dark;
  const [tab, setTab] = useState('home');
  const [bizId, setBizId] = useState(window.__bizId || (BUSINESSES[0] && BUSINESSES[0].id));
  const biz = BUSINESSES.find(b => b.id === bizId) || BUSINESSES[0] || { id: '', name: 'کسب‌وکار', kind: '', mono: '؟', channel: 'بدون کانال', members: 0, channels: [] };
  useEffect(() => { window.__bizId = biz.id; }, [biz.id]);
  function switchBiz(b) { setBizId(b.id); window.__bizId = b.id; setSheet(false); if (window.loadRealData) window.loadRealData(); }
  const [sheet, setSheet] = useState(false);
  const [convId, setConvId] = useState(null);
  const [custId, setCustId] = useState(null);
  const [read, setRead] = useState({});
  const [assistant, setAssistant] = useState(false);
  const [settings, setSettings] = useState(false);
  const [addBiz, setAddBiz] = useState(false);
  const [notif, setNotif] = useState(false);
  const [screen, setScreen] = useState(null);

  const theme = makeTheme(dark, t);
  const conv = CONVERSATIONS.find(c => c.id === convId);
  const cust = CUSTOMERS.find(c => c.id === custId);
  const convs = CONVERSATIONS.map(c => read[c.id] ? { ...c, unread: 0 } : c);

  function openConv(id) { setRead(r => ({ ...r, [id]: true })); setConvId(id); }
  const overlay = conv || cust || settings || addBiz || notif || screen;

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: dark ? '#070707' : '#e7e7e4', padding: 20 }}>
      <IOSDevice dark={dark}>
        <div dir="rtl" style={{ ...theme, height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)', color: 'var(--ink)', position: 'relative' }}>
          {/* main tabbed UI */}
          <div style={{ height: '100%', display: 'flex', flexDirection: 'column', visibility: overlay ? 'hidden' : 'visible' }}>
            <TopBar biz={biz} dark={dark} onSwitch={() => setSheet(true)} onBell={() => setNotif(true)} hasNotif={NOTIFICATIONS.some(n => n.unread)} />
            <div style={{ flex: 1, overflowY: 'auto', paddingTop: 14 }}>
              {tab !== 'home' && (
                <h1 style={{ fontSize: 26, fontWeight: 800, color: 'var(--ink)', letterSpacing: '-.02em', padding: '0 18px 10px', margin: 0 }}>{TAB_TITLE[tab]}</h1>
              )}
              {tab === 'home' && <Dashboard biz={biz} onOpenConv={openConv} onSwitchBiz={() => setSheet(true)} onTab={setTab} />}
              {tab === 'inbox' && <InboxList convs={convs} onOpen={openConv} assistant={assistant} onToggleAssistant={() => setAssistant(a => !a)} />}
              {tab === 'customers' && <CustomersList onOpen={setCustId} />}
              {tab === 'more' && <MoreScreen biz={biz} dark={dark} onToggleDark={() => setTweak('dark', !dark)} onSwitch={() => setSheet(true)} assistant={assistant} onOpenAssistant={() => setSettings(true)} onOpenScreen={setScreen} />}
            </div>
            <BottomNav tab={tab} onTab={setTab} />
          </div>

          {/* conversation overlay */}
          {conv && (
            <div style={{ position: 'absolute', inset: 0, zIndex: 100, background: 'var(--bg)', paddingTop: 44 }}>
              <ConversationView conv={conv} assistant={assistant} onBack={() => setConvId(null)} onOpenCustomer={(id) => { setConvId(null); setCustId(id); }} />
            </div>
          )}
          {/* AI assistant settings overlay */}
          {settings && (
            <div style={{ position: 'absolute', inset: 0, zIndex: 120, background: 'var(--bg)', paddingTop: 44 }}>
              <AssistantSettings assistant={assistant} onToggle={() => setAssistant(a => !a)} onBack={() => setSettings(false)} />
            </div>
          )}
          {/* add business overlay */}
          {addBiz && (
            <div style={{ position: 'absolute', inset: 0, zIndex: 120, background: 'var(--bg)', paddingTop: 44 }}>
              <AddBusiness onBack={() => setAddBiz(false)} onDone={(newId) => { setAddBiz(false); if (newId) { setBizId(newId); window.__bizId = newId; } if (window.loadRealData) window.loadRealData(); }} />
            </div>
          )}
          {/* notifications overlay */}
          {notif && (
            <div style={{ position: 'absolute', inset: 0, zIndex: 120, background: 'var(--bg)', paddingTop: 44 }}>
              <NotificationsScreen onBack={() => setNotif(false)} />
            </div>
          )}
          {/* platform / team / settings sub-screens */}
          {screen && (
            <div style={{ position: 'absolute', inset: 0, zIndex: 120, background: 'var(--bg)', paddingTop: 44 }}>
              {screen === 'team' && <TeamScreen onBack={() => setScreen(null)} />}
              {screen === 'tickets' && <TicketsScreen onBack={() => setScreen(null)} />}
              {screen === 'automation' && <AutomationScreen onBack={() => setScreen(null)} />}
              {screen === 'security' && <SecurityScreen onBack={() => setScreen(null)} />}
              {screen === 'bot' && <BotScreen biz={biz} onBack={() => setScreen(null)} />}
              {screen === 'channels' && <ChannelsScreen biz={biz} onBack={() => setScreen(null)} />}
            </div>
          )}
          {/* customer profile overlay */}
          {cust && !conv && (
            <div style={{ position: 'absolute', inset: 0, zIndex: 100, background: 'var(--bg)', paddingTop: 44 }}>
              <CustomerProfile cu={cust} onBack={() => setCustId(null)} onMessage={(cid) => {
                const cv = CONVERSATIONS.find(c => c.customerId === cid);
                setCustId(null); if (cv) openConv(cv.id);
              }} />
            </div>
          )}

          {sheet && <BizSheet current={biz} onPick={switchBiz} onClose={() => setSheet(false)} onAdd={() => { setSheet(false); setAddBiz(true); }} />}
        </div>
      </IOSDevice>

      <TweaksPanel>
        <TweakSection label="ظاهر" />
        <TweakToggle label="حالت تیره" value={t.dark} onChange={v => setTweak('dark', v)} />
        <TweakSelect label="رنگ اکسنت" value={t.accent} options={Object.keys(ACCENTS)} onChange={v => setTweak('accent', v)} />
        <TweakSection label="چیدمان" />
        <TweakSlider label="گردی گوشه‌ها" value={t.radius} min={4} max={28} unit="px" onChange={v => setTweak('radius', v)} />
        <TweakRadio label="تراکم" value={t.density} options={['فشرده', 'متعادل', 'راحت']} onChange={v => setTweak('density', v)} />
      </TweaksPanel>
    </div>
  );
}

// ── صفحه‌ی ورود / ثبت‌نام ───────────────────────────────────────
function LoginScreen({ onAuthed }) {
  const [mode, setMode] = useState('login'); // login | signup
  const [name, setName] = useState('');
  const [bizName, setBizName] = useState('');
  const [id, setId] = useState('');
  const [pw, setPw] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');

  async function submit() {
    setErr(''); setBusy(true);
    try {
      const url = mode === 'login' ? '/api/auth/login' : '/api/auth/signup';
      const body = mode === 'login'
        ? { identifier: id.trim(), password: pw }
        : { name: name.trim(), businessName: bizName.trim(), identifier: id.trim(), password: pw };
      const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
      const d = await r.json();
      if (d.token) { localStorage.setItem('crm_token', d.token); onAuthed(); }
      else setErr(d.error || 'خطا');
    } catch (e) { setErr('اتصال به سرور برقرار نشد'); }
    setBusy(false);
  }

  const field = (ph, val, set, type) => (
    <input value={val} onChange={e => set(e.target.value)} placeholder={ph} type={type || 'text'} style={{
      width: '100%', border: '1px solid #ddd', background: '#f7f7f8', borderRadius: 12,
      padding: '13px 14px', font: 'inherit', fontSize: 14, color: '#1a1a1a', outline: 'none', marginBottom: 10, boxSizing: 'border-box',
    }} />
  );

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '0 22px', background: '#f4f4f5' }}>
      <div style={{ fontSize: 26, fontWeight: 800, color: '#1a1a1a', textAlign: 'center', marginBottom: 6 }}>روبیکا CRM</div>
      <div style={{ fontSize: 13, color: '#999', textAlign: 'center', marginBottom: 26 }}>
        {mode === 'login' ? 'به حساب خود وارد شوید' : 'حساب جدید بسازید'}
      </div>
      {mode === 'signup' && field('نام شما', name, setName)}
      {mode === 'signup' && field('نام کسب‌وکار', bizName, setBizName)}
      {field('شماره موبایل یا ایمیل', id, setId)}
      {field('رمز عبور', pw, setPw, 'password')}
      {err ? <div style={{ color: '#d9534f', fontSize: 12.5, marginBottom: 10, textAlign: 'center' }}>{err}</div> : null}
      <button onClick={submit} disabled={busy} style={{
        width: '100%', font: 'inherit', fontSize: 15, fontWeight: 700, cursor: 'pointer',
        background: '#1a1a1a', color: '#fff', border: 'none', borderRadius: 16, padding: '14px',
      }}>{busy ? 'لطفاً صبر کنید…' : (mode === 'login' ? 'ورود' : 'ثبت‌نام')}</button>
      <button onClick={() => { setMode(mode === 'login' ? 'signup' : 'login'); setErr(''); }} style={{
        marginTop: 14, font: 'inherit', fontSize: 13, color: '#555', background: 'none', border: 'none', cursor: 'pointer',
      }}>{mode === 'login' ? 'حساب نداری؟ ثبت‌نام کن' : 'حساب داری؟ وارد شو'}</button>
    </div>
  );
}

// ── اتصال کانال به کسب‌وکار (قابل استفاده در آنبوردینگ و تنظیمات) ──
const CONNECT_PLATFORMS = [
  { id: 'rubika', label: 'روبیکا', mono: 'R', hint: 'اتصال از طریق ربات روبیکا' },
  { id: 'telegram', label: 'تلگرام', mono: 'T', hint: 'اتصال از طریق ربات تلگرام (BotFather)' },
  { id: 'bale', label: 'بله', mono: 'ب', hint: 'اتصال از طریق ربات بله' },
];

function ConnectChannel({ businessId, connected, onConnected }) {
  const [open, setOpen] = useState(null);
  const [token, setToken] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');

  async function connect(platform) {
    if (!token.trim() || busy) return;
    setBusy(true); setErr('');
    try {
      const r = await fetch('/api/businesses/' + businessId + '/channels', {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ platform, token: token.trim() }),
      });
      const d = await r.json();
      if (d.ok) { setOpen(null); setToken(''); onConnected && onConnected(d); }
      else setErr(d.error || 'توکن نامعتبر است');
    } catch (e) { setErr('اتصال به سرور برقرار نشد'); }
    setBusy(false);
  }

  const isConn = (p) => (connected || []).some(c => c.platform === p || c.label === p);

  return (
    <div>
      {CONNECT_PLATFORMS.map(p => {
        const c = (connected || []).find(x => x.platform === p.id);
        const isOpen = open === p.id;
        return (
          <div key={p.id} style={{ background: '#fff', border: '1px solid ' + (c ? '#1a1a1a' : '#ececec'), borderRadius: 16, marginBottom: 10, overflow: 'hidden' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
              <div style={{ width: 38, height: 38, borderRadius: 11, background: '#f7f7f8', border: '1px solid #ececec', color: '#1a1a1a', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800 }}>{p.mono}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: '#1a1a1a' }}>{p.label}</div>
                <div style={{ fontSize: 11, color: c ? '#1a1a1a' : '#999' }}>{c ? 'متصل شد ✓' : p.hint}</div>
              </div>
              {c ? <Icon name="check" size={20} style={{ color: '#1a1a1a' }} />
                 : <button onClick={() => { setOpen(isOpen ? null : p.id); setToken(''); setErr(''); }} style={{ font: 'inherit', fontSize: 12.5, fontWeight: 700, color: '#fff', background: '#1a1a1a', border: 'none', borderRadius: 10, padding: '8px 14px', cursor: 'pointer' }}>{isOpen ? 'بستن' : 'اتصال'}</button>}
            </div>
            {isOpen && !c && (
              <div style={{ padding: '0 14px 14px' }}>
                <input value={token} onChange={e => setToken(e.target.value)} placeholder={'توکن ربات ' + p.label} dir="ltr" style={{ width: '100%', border: '1px solid #ddd', background: '#f7f7f8', borderRadius: 12, padding: '11px 13px', font: 'inherit', fontSize: 13, color: '#1a1a1a', outline: 'none', textAlign: 'left', boxSizing: 'border-box' }} />
                {err ? <div style={{ color: '#d9534f', fontSize: 11.5, marginTop: 8 }}>{err}</div> : null}
                <button onClick={() => connect(p.id)} disabled={!token.trim() || busy} style={{ width: '100%', marginTop: 10, font: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer', background: '#1a1a1a', color: '#fff', border: 'none', borderRadius: 10, padding: '11px' }}>{busy ? 'در حال بررسی توکن…' : 'بررسی و اتصال'}</button>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// صفحه‌ی مدیریت کانال‌ها (همیشه در دسترس از «بیشتر»)
function ChannelsScreen({ biz, onBack }) {
  const channels = (biz && biz.channels) || [];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="مدیریت کانال‌ها" onBack={onBack} />
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--bg)', padding: 14 }}>
        <SectionLabel>کانال‌های متصل</SectionLabel>
        {channels.length === 0 && (
          <div style={{ textAlign: 'center', color: 'var(--ink-3)', fontSize: 12.5, padding: '18px 0' }}>هنوز کانالی وصل نشده</div>
        )}
        {channels.map((c, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 12, padding: '12px 14px', marginBottom: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--accent)' }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{c.label}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{c.handle || 'فعال'}</div>
            </div>
          </div>
        ))}
        <div style={{ marginTop: 14 }}><SectionLabel>افزودن کانال جدید</SectionLabel></div>
        <ConnectChannel businessId={biz && biz.id} connected={channels} onConnected={() => { if (window.loadRealData) window.loadRealData(); }} />
      </div>
    </div>
  );
}

function Onboarding({ businessId, bizName, onDone }) {
  const [connected, setConnected] = useState([]);
  return (
    <div style={{ height: '100%', overflowY: 'auto', background: '#f4f4f5', padding: '40px 20px 24px' }}>
      <div style={{ fontSize: 22, fontWeight: 800, color: '#1a1a1a', textAlign: 'center', marginBottom: 6 }}>به روبیکا CRM خوش آمدی! 🌿</div>
      <div style={{ fontSize: 13, color: '#777', textAlign: 'center', marginBottom: 24, lineHeight: 1.9 }}>
        برای شروع، اولین کانال پیام‌رسانت را به «{bizName || 'کسب‌وکارت'}» وصل کن تا گفتگوها اینجا بیایند.
      </div>
      <ConnectChannel businessId={businessId} connected={connected} onConnected={(d) => setConnected(c => [...c, d])} />
      <button onClick={() => onDone()} style={{ width: '100%', marginTop: 14, font: 'inherit', fontSize: 15, fontWeight: 700, cursor: 'pointer', background: connected.length ? '#1a1a1a' : '#e7e7e7', color: connected.length ? '#fff' : '#999', border: 'none', borderRadius: 16, padding: '14px' }}>
        {connected.length ? 'ورود به پنل' : 'فعلاً رد کن'}
      </button>
    </div>
  );
}

function AuthGate() {
  const [authed, setAuthed] = useState(!!localStorage.getItem('crm_token'));
  const [phase, setPhase] = useState('init');
  const [biz, setBiz] = useState(null);

  window.crmLogout = () => { localStorage.removeItem('crm_token'); window.__bizId = null; setBiz(null); setAuthed(false); };

  useEffect(() => {
    if (!authed) { setPhase('login'); return; }
    setPhase('loading');
    fetch('/api/businesses').then(r => r.json()).then(list => {
      const b = Array.isArray(list) ? list[0] : null;
      if (b) { window.__bizId = b.id; setBiz(b); }
      const hasChannel = b && b.channels && b.channels.length > 0;
      if (hasChannel) { if (window.loadRealData) window.loadRealData(); setPhase('app'); }
      else setPhase('onboarding');
    }).catch(() => setPhase('app'));
  }, [authed]);

  if (!authed) return <IOSDevice><LoginScreen onAuthed={() => setAuthed(true)} /></IOSDevice>;
  if (phase === 'loading' || phase === 'init')
    return <IOSDevice><div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999', background: '#f4f4f5' }}>در حال بارگذاری…</div></IOSDevice>;
  if (phase === 'onboarding')
    return <IOSDevice><Onboarding businessId={biz && biz.id} bizName={biz && biz.name} onDone={() => { if (window.loadRealData) window.loadRealData(); setPhase('app'); }} /></IOSDevice>;
  return <App />;
}

window.__root = ReactDOM.createRoot(document.getElementById('root'));
window.__root.render(<AuthGate />);
// به ماژول داده اجازه می‌دهد بعد از گرفتن داده‌ی واقعی، رابط را تازه کند
window.__refresh = () => window.__root.render(<AuthGate />);
if (typeof window.loadRealData === 'function' && localStorage.getItem('crm_token')) window.loadRealData();
