/* ── Zafa — Vendor app: dashboard, services, boost, editor, subscription ── */

const SUB_STATES = {
  active: { en: 'Active', ar: 'نشط', tone: '#2E9E6B', bg: '#E6F4EC', ic: 'check' },
  pending: { en: 'Pending payment', ar: 'بانتظار الدفع', tone: '#A9711F', bg: '#FBF3DC', ic: 'spark' },
  expired: { en: 'Expired · hidden', ar: 'منتهٍ · مخفي', tone: '#C0392B', bg: '#FBEAE7', ic: 'x' }
};

/* default seeded services for the vendor */
const seedServices = () => [
{ id: 's1', cat: 'flowers', en: 'Bridal bouquets', ar: 'باقات العروس', price: 1700, boosted: true, paused: false },
{ id: 's2', cat: 'flowers', en: 'Ceremony arches', ar: 'أقواس الزفاف', price: 3400, boosted: false, paused: false },
{ id: 's3', cat: 'decor', en: 'Reception centerpieces', ar: 'محور الطاولات', price: 2550, boosted: false, paused: true }];


/* ── Vendor bottom dock ── */
function VendorDock({ vtab, setVtab }) {
  const { lang } = useZafa();
  const Item = ({ id, icon, label }) => {
    const on = vtab === id;
    return (
      <button className={`z-dock-item${on ? ' z-dock-item--on' : ''}`} onClick={() => setVtab(id)}>
        <Icon name={icon} size={23} stroke={on ? 2.2 : 1.8} />
        <span>{label}</span>
      </button>);

  };
  return (
    <div className="z-dock-wrap">
      <div className="z-dock">
        <Item id="dash" icon="grid" label={L(lang, 'Dashboard', 'اللوحة')} />
        <Item id="services" icon="store" label={L(lang, 'Services', 'الخدمات')} />
        <button className="z-dock-fab" onClick={() => setVtab('analytics')} aria-label="Analytics"><Icon name="analytics" size={24} stroke={2.1} /></button>
        <Item id="messages" icon="chat" label={L(lang, 'Messages', 'الرسائل')} />
        <Item id="editor" icon="user" label={L(lang, 'Profile', 'الملف')} />
      </div>
    </div>);

}

/* stat tile */
function VStat({ ic, bg, col, value, label }) {
  return (
    <div className="z-card" style={{ flex: 1, padding: '15px 12px', textAlign: 'center' }}>
      <span style={{ width: 34, height: 34, borderRadius: 10, background: bg, color: col, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 7 }}><Icon name={ic} size={18} /></span>
      <p className="serif" style={{ margin: 0, fontSize: 21, fontWeight: 700 }}>{value}</p>
      <p style={{ margin: '2px 0 0', fontSize: 11.5, fontWeight: 600, color: 'var(--ink-2)' }}>{label}</p>
    </div>);

}

/* ── Vendor Messages (inbox + thread, reply to customers) ── */
const SEED_CONVOS = [
{ id: 'c1', name: 'Sara Al Mansoori', nameAr: 'سارة المنصوري', cat: 'flowers', time: '2m', unread: 2,
  msgs: [
  { me: false, t: 'Hi! Are you available on 14 March for a garden wedding?', ar: 'مرحباً! هل أنت متاح في ١٤ مارس لحفل في حديقة؟' },
  { me: false, t: 'We\u2019re expecting around 200 guests.', ar: 'نتوقّع حوالي ٢٠٠ ضيف.' }]
},
{ id: 'c2', name: 'Omar & Layla', nameAr: 'عمر وليلى', cat: 'flowers', time: '1h', unread: 0,
  msgs: [
  { me: false, t: 'Could you share a quote for ceremony arches?', ar: 'هل يمكنك إرسال عرض سعر لأقواس الزفاف؟' },
  { me: true, t: 'Of course — arches start from AED 3,400. I\u2019ll send options shortly.', ar: 'بالطبع — الأقواس تبدأ من ٣٤٠٠ درهم. سأرسل الخيارات قريباً.' }]
},
{ id: 'c3', name: 'Fatima H.', nameAr: 'فاطمة ح.', cat: 'flowers', time: 'Yesterday', unread: 0,
  msgs: [{ me: false, t: 'Loved your portfolio! Do you travel to Abu Dhabi?', ar: 'أحببت أعمالك! هل تسافر إلى أبوظبي؟' }] }];


function VThread({ convo, onBack }) {
  const { lang } = useZafa();
  const [msgs, setMsgs] = React.useState(convo.msgs);
  const [input, setInput] = React.useState('');
  const ref = React.useRef(null);
  React.useEffect(() => {const el = ref.current;if (el) el.scrollTop = el.scrollHeight;}, [msgs]);
  const send = () => {const t = input.trim();if (!t) return;setMsgs((m) => [...m, { me: true, t, ar: t }]);setInput('');};
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ padding: '8px 18px 10px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--line-2)', background: '#fff' }}>
        <button onClick={onBack} className="z-glass" style={{ background: '#fff', border: '1px solid var(--line)', flexShrink: 0 }}><Icon name="left" size={20} className="flip-x" /></button>
        <div style={{ width: 42, height: 42, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, background: 'var(--rose-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--rose-deep)' }}><Icon name="user" size={22} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <p className="serif" style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>{L(lang, convo.name, convo.nameAr)}</p>
          <p style={{ margin: '1px 0 0', fontSize: 11.5, color: '#2E9E6B', fontWeight: 600 }}>{L(lang, 'Customer', 'عميل')}</p>
        </div>
      </div>
      <div ref={ref} className="z-scroll no-bar" style={{ flex: 1, padding: '18px 16px 8px' }}>
        {msgs.map((m, i) =>
        <div key={i} className="fade-up" style={{ display: 'flex', justifyContent: m.me ? 'flex-end' : 'flex-start', marginBottom: 12 }}>
            <div style={{ maxWidth: '80%', padding: '11px 14px', borderRadius: m.me ? '18px 18px 4px 18px' : '18px 18px 18px 4px', background: m.me ? 'var(--rose)' : '#fff', color: 'var(--ink)', fontSize: 14.5, lineHeight: 1.45, boxShadow: 'var(--sh-sm)', border: m.me ? 'none' : '1px solid var(--line-2)', textWrap: 'pretty' }}>{L(lang, m.t, m.ar)}</div>
          </div>
        )}
      </div>
      <div style={{ padding: '10px 16px 26px', borderTop: '1px solid var(--line)', background: '#fff' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--bg)', border: '1.5px solid var(--line)', borderRadius: 999, padding: '5px 6px 5px 8px' }}>
          <button title="attach" style={{ width: 38, height: 38, borderRadius: 11, border: 'none', cursor: 'pointer', background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="image" size={19} /></button>
          <input value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && send()} placeholder={L(lang, 'Message…', 'رسالة…')} style={{ flex: 1, border: 'none', outline: 'none', background: 'none', fontFamily: 'var(--sans)', fontSize: 15, color: 'var(--ink)', minWidth: 0 }} />
          <button onClick={send} disabled={!input.trim()} style={{ width: 42, height: 42, borderRadius: '50%', border: 'none', cursor: 'pointer', background: input.trim() ? 'var(--rose)' : 'var(--line)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="arrow" size={19} className="flip-x" /></button>
        </div>
      </div>
    </div>);

}

function VMessages({ open, setOpen }) {
  const { lang } = useZafa();
  const convo = SEED_CONVOS.find((c) => c.id === open);
  if (convo) return <VThread convo={convo} onBack={() => setOpen(null)} />;
  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)' }}>
      <div style={{ padding: '8px 20px 4px' }}><h1 className="h1" style={{ margin: 0, fontSize: 25 }}>{L(lang, 'Messages', 'الرسائل')}</h1></div>
      <p className="sec" style={{ padding: '6px 20px 0', fontSize: 13 }}>{L(lang, 'Customers who messaged you about your services', 'العملاء الذين راسلوك حول خدماتك')}</p>
      <div style={{ padding: '14px 20px 28px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {SEED_CONVOS.map((c) =>
        <button key={c.id} onClick={() => setOpen(c.id)} className="z-card" style={{ padding: 14, display: 'flex', gap: 12, alignItems: 'center', cursor: 'pointer', textAlign: 'start', border: 'none' }}>
            <div style={{ width: 48, height: 48, borderRadius: '50%', flexShrink: 0, background: 'var(--rose-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--rose-deep)' }}><Icon name="user" size={24} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
                <p className="serif" style={{ margin: 0, fontSize: 15.5, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{L(lang, c.name, c.nameAr)}</p>
                <span className="muted" style={{ fontSize: 11.5, flexShrink: 0 }}>{c.time}</span>
              </div>
              <p className="sec" style={{ margin: '3px 0 0', fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: c.unread ? 600 : 400, color: c.unread ? 'var(--ink)' : 'var(--ink-2)' }}>{L(lang, c.msgs[c.msgs.length - 1].t, c.msgs[c.msgs.length - 1].ar)}</p>
            </div>
            {c.unread > 0 && <span style={{ flexShrink: 0, minWidth: 20, height: 20, borderRadius: 99, background: 'var(--rose-deep)', color: '#fff', fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 6px' }}>{c.unread}</span>}
          </button>
        )}
      </div>
    </div>);

}

/* 6 ── Dashboard */
function VDashboard({ tier, sub, setSub, level, profile, go }) {
  const { lang } = useZafa();
  const tr = TIERS[tier];const ss = SUB_STATES[sub];
  const lv = LEVELS[level];
  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)' }}>
      <div style={{ padding: '8px 20px 4px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <p className="eyebrow" style={{ marginBottom: 4 }}>{L(lang, 'Vendor dashboard', 'لوحة المزوّد')}</p>
          <h1 className="h1" style={{ margin: 0, fontSize: 25 }}>{profile.name || L(lang, 'Your business', 'نشاطك')}</h1>
        </div>
        <span className={`z-badge z-badge--${lv.tone}`} style={{ fontSize: 11, padding: '5px 10px' }}>{lv.tone === 'gold' && <Icon name="star" size={11} fill="currentColor" stroke={0} />}{L(lang, lv.en, lv.ar)}</span>
      </div>

      {/* KPIs — top of dashboard */}
      <div style={{ padding: '14px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Last 30 days', 'آخر ٣٠ يوماً')}</p>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {[
            { ic: 'user', bg: '#FCE7EE', col: 'var(--rose-deep)', v: '1,284', lbl: L(lang, 'Profile views', 'مشاهدات الملف') },
            { ic: 'chat', bg: '#E6F4EC', col: '#2E9E6B', v: '46', lbl: L(lang, 'Enquiries', 'الاستفسارات') },
            { ic: 'heart', bg: '#FBF3DC', col: '#A9711F', v: '312', lbl: L(lang, 'Wishlist saves', 'حفظ المفضلة') },
            { ic: 'star', bg: '#DFE1E5', col: '#2C3550', v: '3', lbl: L(lang, 'Performance level', 'مستوى الأداء') }].
          map((m) => (
            <div key={m.lbl} className="z-card" style={{ padding: 14 }}>
              <span style={{ width: 34, height: 34, borderRadius: 10, background: m.bg, color: m.col, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={m.ic} size={18} /></span>
              <p className="serif" style={{ margin: '10px 0 0', fontSize: 24, fontWeight: 700 }}>{m.v}</p>
              <p style={{ margin: '1px 0 0', fontSize: 12, fontWeight: 600, color: 'var(--ink-2)' }}>{m.lbl}</p>
            </div>
          ))}
        </div>
      </div>

      {/* subscription status banner */}
      <div style={{ padding: '14px 20px 4px' }}>
        <div className="z-card" style={{ padding: 16 }}>
          <button onClick={() => go('sub')} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'start', padding: 0 }}>
            <span style={{ width: 40, height: 40, borderRadius: 12, background: ss.bg, color: ss.tone, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={ss.ic} size={20} stroke={2.2} /></span>
            <div style={{ flex: 1 }}>
              <p style={{ margin: 0, fontSize: 14.5, fontWeight: 700 }}>{L(lang, tr.en, tr.ar)} {L(lang, 'plan', 'باقة')}</p>
              <p style={{ margin: '1px 0 0', fontSize: 12.5, fontWeight: 600, color: ss.tone }}>{L(lang, ss.en, ss.ar)} · <span style={{ color: 'var(--rose-deep)' }}>{L(lang, 'Manage', 'إدارة')}</span></p>
            </div>
            <span className="serif" style={{ fontSize: 17, fontWeight: 700 }}>AED {tr.price}<span className="muted" style={{ fontSize: 12, fontWeight: 500 }}>/{L(lang, 'mo', 'ش')}</span></span>
          </button>
          {sub === 'expired' && <p className="sec" style={{ margin: '12px 0 0', fontSize: 12.5, lineHeight: 1.45, padding: '10px 12px', borderRadius: 10, background: '#FBEAE7', color: '#C0392B' }}>{L(lang, 'Your profile is hidden from customers. Renew to go live again.', 'ملفك مخفي عن العملاء. جدّد لإعادة الظهور.')}</p>}
          {sub === 'pending' && <p className="sec" style={{ margin: '12px 0 0', fontSize: 12.5, lineHeight: 1.45, padding: '10px 12px', borderRadius: 10, background: '#FBF3DC', color: '#A9711F' }}>{L(lang, 'Payment is being confirmed. Your profile will go live shortly.', 'يجري تأكيد الدفع. سيظهر ملفك قريباً.')}</p>}
          {sub !== 'active' && <div style={{ marginTop: 12 }}><Btn variant="rose" sm onClick={() => go('sub')} style={{ width: '100%' }}>{sub === 'expired' ? L(lang, 'Renew now', 'جدّد الآن') : L(lang, 'Complete payment', 'أكمل الدفع')}</Btn></div>}
        </div>
      </div>

      {/* level / standing */}
      <div style={{ padding: '16px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Your standing', 'مكانتك')}</p>
        <div className="z-card" style={{ padding: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <span style={{ fontSize: 13.5, fontWeight: 600 }}>{L(lang, lv.en, lv.ar)}</span>
            <span className="muted" style={{ fontSize: 12.5 }}>{L(lang, 'Next:', 'التالي:')} {L(lang, (LEVELS[Object.keys(LEVELS)[Math.max(0, Object.keys(LEVELS).indexOf(level) - 1)]] || lv).en, (LEVELS[Object.keys(LEVELS)[Math.max(0, Object.keys(LEVELS).indexOf(level) - 1)]] || lv).ar)}</span>
          </div>
          <div style={{ height: 8, borderRadius: 99, background: 'var(--line)', overflow: 'hidden' }}><div style={{ width: '68%', height: '100%', background: 'var(--rose)' }} /></div>
          <p className="sec" style={{ margin: '10px 0 0', fontSize: 12.5, lineHeight: 1.45 }}>{L(lang, 'Keep response time low and ratings high to climb to the next level.', 'حافظ على سرعة الرد والتقييم العالي للارتقاء للمستوى التالي.')}</p>
        </div>
      </div>

      {/* engagement summary */}
      <div style={{ padding: '16px 20px 4px' }}>
        <div className="z-card" style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chat" size={19} /></span>
          <div style={{ flex: 1 }}>
            <p style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>18 {L(lang, 'customers negotiated', 'عميلاً تفاوضوا')}</p>
            <p className="muted" style={{ margin: '1px 0 0', fontSize: 12 }}>{L(lang, 'via WhatsApp & in-app chat', 'عبر واتساب والدردشة')}</p>
          </div>
        </div>
      </div>

      {/* analytics CTA */}
      <div style={{ padding: '16px 20px 120px' }}>
        <div onClick={() => go('analytics')} style={{ cursor: 'pointer', borderRadius: 20, padding: 18, background: '#2C3550', color: '#fff', display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ width: 44, height: 44, borderRadius: 13, background: 'var(--rose)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="grid" size={23} stroke={2.1} /></span>
          <div style={{ flex: 1 }}>
            <p className="serif" style={{ margin: 0, fontSize: 18, fontWeight: 600, color: '#fff' }}>{L(lang, 'View analytics', 'عرض التحليلات')}</p>
            <p style={{ margin: '2px 0 0', fontSize: 12.5, color: 'rgba(255,255,255,.8)' }}>{L(lang, 'Track views, enquiries & top services', 'تابع المشاهدات والاستفسارات')}</p>
          </div>
          <Icon name="arrow" size={20} className="flip-x" style={{ color: '#ffffff' }} />
        </div>
      </div>
    </div>);

}

/* 7 ── Analytics (replaces Boost profile) */
function VAnalytics({ tier, level }) {
  const { lang } = useZafa();
  const [range, setRange] = React.useState('30d');
  const ranges = [['7d', L(lang, '7 days', '٧ أيام')], ['30d', L(lang, '30 days', '٣٠ يوماً')], ['90d', L(lang, '90 days', '٩٠ يوماً')]];
  const bars = [42, 58, 50, 74, 66, 88, 95]; // last 7 days views
  const barColors = ['#F6B0C6', '#E79AB4', '#C9A6C8', '#A98432', '#6E7E62', '#C36B5A', '#C8607E'];
  const days = L(lang, ['M', 'T', 'W', 'T', 'F', 'S', 'S'], ['ن', 'ث', 'ر', 'خ', 'ج', 'س', 'ح']);
  const max = Math.max(...bars);
  const contacts = [
  [L(lang, 'WhatsApp', 'واتساب'), 54, '#25D366'], [L(lang, 'Email', 'البريد'), 23, '#2A6FDB'],
  [L(lang, 'Phone', 'الهاتف'), 14, '#5A4F54'], [L(lang, 'Instagram', 'إنستغرام'), 9, '#C13584']];

  const journey = [
  [L(lang, 'Level 1', 'المستوى ١'), L(lang, 'Jan 2026', 'يناير ٢٠٢٦'), 'done'],
  [L(lang, 'Level 2', 'المستوى ٢'), L(lang, 'Mar 2026', 'مارس ٢٠٢٦'), 'done'],
  [L(lang, 'Level 3', 'المستوى ٣'), L(lang, 'May 2026', 'مايو ٢٠٢٦'), 'current'],
  [L(lang, 'Level 4', 'المستوى ٤'), L(lang, 'Soon', 'قريباً'), 'next']];

  const metrics = [
  { ic: 'user', bg: '#FCE7EE', col: '#C8607E', v: '1,284', lbl: L(lang, 'Profile views', 'مشاهدات الملف'), d: '+12%' },
  { ic: 'chat', bg: '#E6F4EC', col: '#2E9E6B', v: '46', lbl: L(lang, 'Enquiries', 'الاستفسارات'), d: '+8%' },
  { ic: 'heart', bg: '#F1ECDF', col: '#A98432', v: '312', lbl: L(lang, 'Saves', 'الحفظ'), d: '+21%' },
  { ic: 'spark', bg: '#DFE1E5', col: '#2C3550', v: '3.6%', lbl: L(lang, 'Conversion', 'التحويل'), d: '+0.4%' }];

  const sources = [
  [L(lang, 'Search', 'البحث'), 46], [L(lang, 'Categories', 'الفئات'), 28], [L(lang, 'Featured', 'المميّز'), 18], [L(lang, 'Direct', 'مباشر'), 8]];

  const topSvc = [
  [L(lang, 'Bridal bouquets', 'باقات العروس'), 540], [L(lang, 'Ceremony arches', 'أقواس الزفاف'), 312], [L(lang, 'Centerpieces', 'محور الطاولات'), 198]];

  const maxSvc = Math.max(...topSvc.map((s) => s[1]));
  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)' }}>
      <div style={{ padding: '8px 20px 4px' }}><h1 className="h1" style={{ margin: 0, fontSize: 25 }}>{L(lang, 'Analytics', 'التحليلات')}</h1></div>
      <p className="sec" style={{ padding: '6px 20px 0', fontSize: 13 }}>{L(lang, 'How your profile is performing', 'أداء ملفك')}</p>

      {/* range chips */}
      <div className="no-bar" style={{ display: 'flex', gap: 9, overflowX: 'auto', padding: '14px 20px 4px' }}>
        {ranges.map(([k, lbl]) => <Chip key={k} on={range === k} onClick={() => setRange(k)}>{lbl}</Chip>)}
      </div>

      {/* metric grid */}
      <div style={{ padding: '12px 20px 4px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {metrics.map((m) =>
        <div key={m.lbl} className="z-card" style={{ padding: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ width: 34, height: 34, borderRadius: 10, background: m.bg, color: m.col, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={m.ic} size={18} /></span>
              <span style={{ fontSize: 11.5, fontWeight: 700, color: '#2E9E6B' }}>{m.d}</span>
            </div>
            <p className="serif" style={{ margin: '10px 0 0', fontSize: 24, fontWeight: 700 }}>{m.v}</p>
            <p style={{ margin: '1px 0 0', fontSize: 12, fontWeight: 600, color: 'var(--ink-2)' }}>{m.lbl}</p>
          </div>
        )}
      </div>

      {/* views bar chart */}
      <div style={{ padding: '16px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 12 }}>{L(lang, 'Profile views · last 7 days', 'المشاهدات · آخر ٧ أيام')}</p>
        <div className="z-card" style={{ padding: '18px 16px 14px' }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 8, height: 130 }}>
            {bars.map((v, i) =>
            <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, height: '100%', justifyContent: 'flex-end' }}>
                <div style={{ width: '100%', maxWidth: 26, height: `${v / max * 100}%`, borderRadius: 7, background: barColors[i % barColors.length] }} />
                <span className="muted" style={{ fontSize: 11, fontWeight: 600 }}>{days[i]}</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* traffic sources */}
      <div style={{ padding: '16px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 12 }}>{L(lang, 'Where views come from', 'مصادر المشاهدات')}</p>
        <div className="z-card" style={{ padding: '6px 16px' }}>
          {sources.map(([nm, pct], i, a) =>
          <div key={nm} style={{ padding: '12px 0', borderBottom: i < a.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 13.5 }}><span style={{ fontWeight: 500 }}>{nm}</span><span style={{ fontWeight: 700, color: barColors[i % barColors.length] }}>{pct}%</span></div>
              <div style={{ height: 7, borderRadius: 99, background: 'var(--line)', overflow: 'hidden' }}><div style={{ width: `${pct}%`, height: '100%', background: barColors[i % barColors.length] }} /></div>
            </div>
          )}
        </div>
      </div>

      {/* top services */}
      <div style={{ padding: '16px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 12 }}>{L(lang, 'Top 5 services by views', 'أفضل ٥ خدمات مشاهدة')}</p>
        <div className="z-card" style={{ padding: '6px 16px' }}>
          {topSvc.map(([nm, v], i, a) =>
          <div key={nm} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 0', borderBottom: i < a.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
              <span style={{ width: 24, height: 24, borderRadius: 8, background: barColors[i % barColors.length] + '22', color: barColors[i % barColors.length], display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 800, flexShrink: 0 }}>{i + 1}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <p style={{ margin: 0, fontSize: 14, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{nm}</p>
                <div style={{ height: 5, borderRadius: 99, background: 'var(--line)', overflow: 'hidden', marginTop: 5 }}><div style={{ width: `${v / maxSvc * 100}%`, height: '100%', background: barColors[i % barColors.length] }} /></div>
              </div>
              <span className="muted" style={{ fontSize: 12.5, fontWeight: 600, flexShrink: 0 }}>{v}</span>
            </div>
          )}
        </div>
      </div>

      {/* how customers contact you */}
      <div style={{ padding: '16px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 12 }}>{L(lang, 'How customers contact you', 'كيف يتواصل العملاء معك')}</p>
        <div className="z-card" style={{ padding: 16 }}>
          <div style={{ display: 'flex', height: 14, borderRadius: 99, overflow: 'hidden', marginBottom: 14 }}>
            {contacts.map(([nm, pct, cl]) => <div key={nm} style={{ width: `${pct}%`, background: cl }} />)}
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px 16px' }}>
            {contacts.map(([nm, pct, cl]) =>
            <div key={nm} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                <span style={{ width: 9, height: 9, borderRadius: '50%', background: cl, flexShrink: 0 }} />
                <span style={{ fontSize: 13, fontWeight: 500 }}>{nm}</span>
                <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--rose-deep)' }}>{pct}%</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* performance journey */}
      <div style={{ padding: '16px 20px 120px' }}>
        <p className="lbl" style={{ marginBottom: 12 }}>{L(lang, 'Performance journey', 'رحلة الأداء')}</p>
        <div className="z-card" style={{ padding: '20px 12px 16px' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start' }}>
            {journey.map(([lvl, date, st], i) => {
              const active = st === 'done' || st === 'current';
              return (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', position: 'relative' }}>
                  {/* connector */}
                  {i < journey.length - 1 && <span style={{ position: 'absolute', top: 17, insetInlineStart: '50%', width: '100%', height: 3, background: journey[i + 1][2] !== 'next' ? 'var(--rose)' : 'var(--line)' }} />}
                  {/* node */}
                  <div style={{ width: 36, height: 36, borderRadius: '50%', flexShrink: 0, zIndex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
                    background: st === 'next' ? '#fff' : 'var(--rose-deep)', border: st === 'next' ? '2.5px solid var(--line)' : 'none', boxShadow: st === 'current' ? '0 0 0 4px var(--rose-100)' : 'none' }}>
                    {active && <Icon name="check" size={18} stroke={3} style={{ color: '#fff' }} />}
                  </div>
                  <p style={{ margin: '8px 0 0', fontSize: 12, fontWeight: 700, color: st === 'next' ? 'var(--muted)' : 'var(--ink)', textAlign: 'center' }}>{lvl}</p>
                  <p className="muted" style={{ margin: '1px 0 0', fontSize: 10.5, textAlign: 'center' }}>{date}</p>
                  {st === 'current' && <span className="z-badge z-badge--ink" style={{ marginTop: 6, fontSize: 9, background: 'var(--rose-deep)' }}>{L(lang, 'You', 'أنت')}</span>}
                </div>);

            })}
          </div>
        </div>
      </div>
    </div>);

}

/* 7b ── Boost (profile) */
function VBoost({ onBack }) {
  const { lang, t } = useZafa();
  const opts = [
  { id: 'b1', days: 3, fee: 90, en: '3 days', ar: '٣ أيام' },
  { id: 'b2', days: 7, fee: 180, en: '1 week', ar: 'أسبوع', best: true },
  { id: 'b3', days: 14, fee: 320, en: '2 weeks', ar: 'أسبوعان' }];

  const [sel, setSel] = React.useState('b2');
  const [state, setState] = React.useState('idle'); // idle | done
  const o = opts.find((x) => x.id === sel);
  if (state === 'done') {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '30px 28px 40px', background: 'var(--bg)', textAlign: 'center' }}>
        <div style={{ width: 104, height: 104, borderRadius: '50%', background: 'var(--rose-100)', color: '#2E9E6B', display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'pop .5s' }}><Icon name="check" size={52} stroke={2.6} /></div>
        <h1 className="h1" style={{ margin: '24px 0 10px' }}>{L(lang, 'Boost active!', 'الترويج مفعّل!')}</h1>
        <p className="sec" style={{ margin: 0, fontSize: 15, lineHeight: 1.55, maxWidth: 290 }}>{L(lang, `Your profile is featured for ${L(lang, o.en, o.ar)}. Expect a spike in views.`, `ملفك مميّز لمدة ${L(lang, o.en, o.ar)}. توقّع ارتفاعاً في المشاهدات.`)}</p>
        <div style={{ marginTop: 26, width: '100%', maxWidth: 300 }}><Btn variant="rose" onClick={onBack}>{L(lang, 'Back to dashboard', 'العودة للوحة')}</Btn></div>
      </div>);

  }
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ padding: '6px 20px 6px' }}><ScreenHeader title={L(lang, 'Boost profile', 'ترويج الملف')} onBack={onBack} /></div>
      <div className="z-scroll no-bar" style={{ flex: 1, padding: '8px 20px 20px' }}>
        <div style={{ borderRadius: 20, padding: 18, background: 'var(--rose-soft)', marginBottom: 20 }}>
          <span style={{ width: 44, height: 44, borderRadius: 13, background: 'var(--rose)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}><Icon name="spark" size={23} stroke={2.1} /></span>
          <h2 className="serif" style={{ margin: '0 0 8px', fontSize: 20, fontWeight: 600 }}>{L(lang, 'What a boost does', 'ماذا يفعل الترويج')}</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {L(lang, ['Top placement in the feed & category pages', 'A glowing “Boosted” badge on your profile', 'Up to 5× more views and enquiries'], ['ظهور بأعلى القائمة وصفحات الفئات', 'شارة «مُروّج» لامعة على ملفك', 'حتى ٥ أضعاف المشاهدات والطلبات']).map((p, i) =>
            <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}><Icon name="check" size={16} stroke={2.4} style={{ color: 'var(--rose-deep)', flexShrink: 0, marginTop: 2 }} /><span style={{ fontSize: 13.5, fontWeight: 500 }}>{p}</span></div>
            )}
          </div>
        </div>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Choose duration', 'اختر المدة')}</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {opts.map((op) => {
            const on = sel === op.id;
            return (
              <button key={op.id} onClick={() => setSel(op.id)} style={{ textAlign: 'start', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12, padding: 15, borderRadius: 16, background: '#fff', border: on ? '2px solid var(--ink)' : '1.5px solid var(--line)' }}>
                <span style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, border: on ? 'none' : '2px solid var(--line)', background: on ? 'var(--ink)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{on && <Icon name="check" size={14} stroke={3} style={{ color: '#fff' }} />}</span>
                <div style={{ flex: 1 }}><span style={{ fontWeight: 700, fontSize: 15 }}>{L(lang, op.en, op.ar)}</span>{op.best && <span className="z-badge z-badge--gold" style={{ marginInlineStart: 8, fontSize: 9.5 }}>{L(lang, 'Popular', 'الأكثر')}</span>}</div>
                <span className="serif" style={{ fontSize: 18, fontWeight: 700 }}>AED {op.fee}</span>
              </button>);

          })}
        </div>
      </div>
      <div style={{ padding: '12px 20px 26px', borderTop: '1px solid var(--line)', background: '#fff' }}>
        <Btn variant="rose" icon="spark" onClick={() => setState('done')}>{L(lang, 'Boost now', 'روّج الآن')} · AED {o.fee}</Btn>
      </div>
    </div>);

}

/* 9–11 ── Services list (add, pause, delete) */
function VServices({ services, setServices, go, onExit, onOpen }) {
  const { lang } = useZafa();
  const [fcat, setFcat] = React.useState('all');
  const toggle = (id) => setServices((s) => s.map((x) => x.id === id ? { ...x, paused: !x.paused } : x));
  const del = (id) => setServices((s) => s.filter((x) => x.id !== id));
  // categories present across the vendor's services, in a sensible order
  const order = ['flowers', 'hospitality', 'lighting', 'stage', 'photography'];
  const present = [...new Set(services.map((x) => x.cat))];
  const catIds = ['all', ...order.filter((c) => present.includes(c)), ...present.filter((c) => !order.includes(c))];
  const shown = fcat === 'all' ? services : services.filter((x) => x.cat === fcat);
  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)' }}>
      <div style={{ padding: '8px 20px 4px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onExit} className="z-glass" style={{ background: '#fff', border: '1px solid var(--line)', flexShrink: 0 }}><Icon name="left" size={20} className="flip-x" /></button>
        <h1 className="h1" style={{ margin: 0, fontSize: 25, flex: 1 }}>{L(lang, 'My services', 'خدماتي')}</h1>
        <button onClick={() => go('addservice')} className="z-btn z-btn--rose z-btn--sm" style={{ width: 'auto' }}><Icon name="plus" size={17} stroke={2.4} />{L(lang, 'Add more', 'أضف المزيد')}</button>
      </div>

      {/* service category filter */}
      <div className="no-bar" style={{ display: 'flex', gap: 9, overflowX: 'auto', padding: '12px 20px 2px' }}>
        {catIds.map((id) => {
          const c = id === 'all' ? null : catOf(id);
          return <Chip key={id} on={fcat === id} icon={c ? c.icon : 'grid'} onClick={() => setFcat(id)}>{id === 'all' ? L(lang, 'All', 'الكل') : L(lang, c.en, c.ar)}</Chip>;
        })}
      </div>

      <p className="sec" style={{ padding: '10px 20px 0', fontSize: 13 }}>{shown.length} {L(lang, 'services · post as many as your plan allows', 'خدمة · أضف بقدر ما تسمح باقتك')}</p>
      <div style={{ padding: '14px 20px 28px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {shown.map((s) => {
          const cat = catOf(s.cat) || CATEGORIES[0];
          return (
            <div key={s.id} onClick={() => onOpen(s.id)} className="z-card" style={{ padding: 12, display: 'flex', gap: 12, alignItems: 'center', opacity: s.paused ? 0.62 : 1, cursor: 'pointer' }}>
              <div style={{ width: 60, height: 60, borderRadius: 13, overflow: 'hidden', flexShrink: 0, position: 'relative' }}>
                <CoverArt theme="rose" icon={cat.icon} cat={s.cat} id={`vs-${s.id}`} seed={'vs' + s.id} radius={12} w={160} h={160} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                  <p style={{ margin: 0, fontWeight: 600, fontSize: 14.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{L(lang, s.en, s.ar)}</p>
                  {s.boosted && <span className="z-badge z-badge--gold" style={{ fontSize: 9 }}><Icon name="spark" size={9} stroke={2.4} />{L(lang, 'Boosted', 'مُروّج')}</span>}
                </div>
                <p className="muted" style={{ margin: '2px 0 0', fontSize: 12.5 }}>{L(lang, cat.en, cat.ar)} · {L(lang, 'from', 'من')} AED {s.price.toLocaleString()}</p>
                {s.paused && <p style={{ margin: '4px 0 0', fontSize: 11.5, fontWeight: 600, color: '#A9711F' }}>{L(lang, 'Paused — hidden from customers', 'متوقّف — مخفي')}</p>}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <button onClick={(e) => { e.stopPropagation(); toggle(s.id); }} title="pause" style={vsIconBtn}><Icon name={s.paused ? 'check' : 'list'} size={16} /></button>
                <button onClick={(e) => { e.stopPropagation(); del(s.id); }} title="delete" style={{ ...vsIconBtn, color: '#C0392B' }}><Icon name="trash" size={16} /></button>
              </div>
            </div>);

        })}
        {shown.length === 0 && <EmptyState icon="store" title={L(lang, 'No services here', 'لا خدمات هنا')} sub={L(lang, 'Add a service in this category to appear in the marketplace.', 'أضف خدمة في هذه الفئة للظهور في السوق.')} cta={L(lang, 'Add a service', 'أضف خدمة')} onCta={() => go('addservice')} />}
      </div>
    </div>);

}
const vsIconBtn = { width: 34, height: 34, borderRadius: 10, border: '1px solid var(--line)', background: '#fff', cursor: 'pointer', color: 'var(--ink-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' };

/* ── Service details (vendor view) ── */
function VServiceDetail({ service, setServices, onBack, onBoost, onEdit }) {
  const { lang } = useZafa();
  const s = service;
  const cat = catOf(s.cat) || CATEGORIES[0];
  const toggle = () => setServices((arr) => arr.map((x) => x.id === s.id ? { ...x, paused: !x.paused } : x));
  const del = () => { setServices((arr) => arr.filter((x) => x.id !== s.id)); onBack(); };
  const desc = s.desc || L(lang,
    `Professional ${cat.en.toLowerCase()} crafted for your special day. Includes consultation, setup, and on-site coordination by our experienced team.`,
    `${cat.ar} احترافية ليومك المميّز. تشمل الاستشارة والتجهيز والتنسيق في الموقع من فريقنا المتمرّس.`);
  const incl = L(lang,
    ['Free initial consultation', 'Custom design & setup', 'On-site coordination', 'Teardown & cleanup'],
    ['استشارة أولية مجانية', 'تصميم وتجهيز مخصّص', 'تنسيق في الموقع', 'الفك والتنظيف']);
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div className="z-scroll no-bar" style={{ flex: 1 }}>
        {/* cover */}
        <div style={{ position: 'relative', height: 210 }}>
          <CoverArt theme="rose" icon={cat.icon} cat={s.cat} src={window.ASSET('svcDetail')} id={`vsd-${s.id}`} seed={'vs' + s.id} radius={0} w={800} h={420} />
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, rgba(0,0,0,.22), rgba(0,0,0,0) 45%)' }} />
          <button onClick={onBack} className="z-glass" style={{ position: 'absolute', top: 16, insetInlineStart: 18 }}><Icon name="left" size={20} className="flip-x" /></button>
          <div style={{ position: 'absolute', top: 16, insetInlineEnd: 18, display: 'flex', gap: 8 }}>
            {s.boosted && <span className="z-badge z-badge--gold"><Icon name="spark" size={10} stroke={2.4} />{L(lang, 'Boosted', 'مُروّج')}</span>}
            <span className="z-badge" style={{ background: s.paused ? 'rgba(169,113,31,.92)' : 'rgba(46,158,107,.92)', color: '#fff' }}>{s.paused ? L(lang, 'Paused', 'متوقّف') : L(lang, 'Live', 'نشط')}</span>
          </div>
        </div>

        <div style={{ padding: '18px 20px 8px' }}>
          <span style={{ color: 'var(--rose-deep)', fontWeight: 700, fontSize: 13 }}>{L(lang, cat.en, cat.ar)}</span>
          <h1 className="h1" style={{ margin: '6px 0 8px', fontSize: 26 }}>{L(lang, s.en, s.ar)}</h1>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <span className="muted" style={{ fontSize: 13.5 }}>{L(lang, 'Starting from', 'يبدأ من')}</span>
            <span className="serif" style={{ fontSize: 24, fontWeight: 700 }}>AED {s.price.toLocaleString()}</span>
          </div>
        </div>

        {/* performance row */}
        <div style={{ padding: '12px 20px 4px', display: 'flex', gap: 10 }}>
          <VStat ic="user" bg="#FCE7EE" col="var(--rose-deep)" value="486" label={L(lang, 'Views', 'مشاهدات')} />
          <VStat ic="chat" bg="#E6F4EC" col="#2E9E6B" value="18" label={L(lang, 'Enquiries', 'استفسارات')} />
          <VStat ic="heart" bg="#FBF3DC" col="#A9711F" value="74" label={L(lang, 'Saves', 'حفظ')} />
        </div>

        {/* description */}
        <div style={{ padding: '18px 20px 4px' }}>
          <p className="lbl" style={{ marginBottom: 8 }}>{L(lang, 'Description', 'الوصف')}</p>
          <p className="sec" style={{ margin: 0, fontSize: 14, lineHeight: 1.55, textWrap: 'pretty' }}>{desc}</p>
        </div>

        {/* what's included */}
        <div style={{ padding: '18px 20px 4px' }}>
          <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'What\u2019s included', 'ما يشمله')}</p>
          <div className="z-card" style={{ padding: '4px 16px' }}>
            {incl.map((it, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '13px 0', borderBottom: i < incl.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
                <span style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="check" size={16} stroke={2.4} /></span>
                <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{it}</span>
              </div>
            ))}
          </div>
        </div>

        {/* gallery */}
        <div style={{ padding: '18px 20px 8px' }}>
          <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Gallery', 'المعرض')}</p>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
            {[0, 1, 2].map((i) => <div key={i} style={{ aspectRatio: '1', borderRadius: 12, overflow: 'hidden' }}><CoverArt theme="rose" icon={cat.icon} cat={s.cat} id={`vsd-g-${s.id}-${i}`} seed={'vsg' + i + s.id} radius={12} w={200} h={200} /></div>)}
          </div>
        </div>

        {/* boost upsell */}
        {!s.boosted && (
          <div style={{ padding: '10px 20px 8px' }}>
            <div onClick={onBoost} style={{ cursor: 'pointer', borderRadius: 16, padding: 15, background: '#FBF3DC', border: '1.5px solid #E7CD8E', display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ width: 38, height: 38, borderRadius: 11, background: '#C8A24A', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="spark" size={20} stroke={2.1} /></span>
              <div style={{ flex: 1 }}>
                <p style={{ margin: 0, fontWeight: 700, fontSize: 14, color: '#7A5E1C' }}>{L(lang, 'Boost this service', 'روّج هذه الخدمة')}</p>
                <p style={{ margin: '2px 0 0', fontSize: 12, color: '#8A6D1F' }}>{L(lang, 'Reach up to 5× more customers', 'وصول حتى ٥ أضعاف العملاء')}</p>
              </div>
              <Icon name="arrow" size={18} className="flip-x" style={{ color: '#A9711F' }} />
            </div>
          </div>
        )}
        <div style={{ height: 12 }} />
      </div>

      {/* action footer */}
      <div style={{ padding: '12px 20px 26px', borderTop: '1px solid var(--line)', background: '#fff', display: 'flex', gap: 12 }}>
        <button onClick={del} title="delete" style={{ width: 54, height: 54, borderRadius: 14, border: '1.5px solid #E8C7C0', background: '#fff', cursor: 'pointer', color: '#C0392B', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="trash" size={20} /></button>
        <button onClick={() => onEdit && onEdit(s)} title="edit" style={{ width: 54, height: 54, borderRadius: 14, border: '1.5px solid var(--line)', background: '#fff', cursor: 'pointer', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="edit" size={20} /></button>
        <button onClick={toggle} className="z-btn z-btn--outline" style={{ flex: 1, gap: 8 }}><Icon name={s.paused ? 'check' : 'list'} size={18} />{s.paused ? L(lang, 'Resume', 'استئناف') : L(lang, 'Pause', 'إيقاف')}</button>
      </div>
    </div>);

}

/* 10 ── Add service (with boost radio) */
function VAddService({ onSave, onBack, initial }) {
  const { lang } = useZafa();
  const [name, setName] = React.useState(initial ? (lang === 'ar' ? initial.ar : initial.en) : '');
  const [desc, setDesc] = React.useState(initial && initial.desc ? initial.desc : '');
  const [cat, setCat] = React.useState(initial ? initial.cat : 'flowers');
  const [price, setPrice] = React.useState(initial ? String(initial.price) : '');
  const [q, setQ] = React.useState('');
  const [boost, setBoost] = React.useState(initial && initial.boosted ? 'boost' : 'regular');
  const [added, setAdded] = React.useState(0);
  const editing = !!initial;
  const list = CATEGORIES.filter((c) => !q || L(lang, c.en, c.ar).toLowerCase().includes(q.toLowerCase()));
  const valid = name.trim() && price;
  const build = () => ({ id: initial ? initial.id : 'n' + Date.now(), cat, en: name, ar: name, desc, price: Number(price), boosted: boost === 'boost', paused: initial ? initial.paused : false });
  const reset = () => {setName('');setDesc('');setPrice('');setBoost('regular');setQ('');};
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ padding: '6px 20px 6px' }}><ScreenHeader title={editing ? L(lang, 'Edit service', 'تعديل الخدمة') : L(lang, 'Add a service', 'إضافة خدمة')} onBack={onBack} /></div>
      <div className="z-scroll no-bar" style={{ flex: 1, padding: '8px 20px 20px' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <AdField label={L(lang, 'Service name', 'اسم الخدمة')}><input className="z-input" value={name} onChange={(e) => setName(e.target.value)} placeholder={L(lang, 'e.g. Bridal bouquets', 'مثال: باقات العروس')} /></AdField>
          <AdField label={L(lang, 'Description', 'الوصف')}><textarea value={desc} onChange={(e) => setDesc(e.target.value)} rows={3} className="z-input" style={{ height: 'auto', padding: '13px 16px', resize: 'none', lineHeight: 1.5 }} placeholder={L(lang, 'Describe what this service includes…', 'صف ما تتضمّنه هذه الخدمة…')} /></AdField>
          <div>
            <p className="lbl" style={{ marginBottom: 9 }}>{L(lang, 'Category', 'الفئة')}</p>
            <div style={{ marginBottom: 10 }}><SearchField value={q} onChange={(e) => setQ(e.target.value)} placeholder={L(lang, 'Search categories', 'ابحث في الفئات')} /></div>
            <div className="no-bar" style={{ display: 'flex', flexWrap: 'wrap', gap: 9, maxHeight: 150, overflowY: 'auto' }}>
              {list.map((c) => <Chip key={c.id} on={cat === c.id} icon={c.icon} onClick={() => setCat(c.id)}>{L(lang, c.en, c.ar)}</Chip>)}
            </div>
          </div>
          <AdField label={L(lang, 'Starting price (AED)', 'السعر يبدأ من (درهم)')}><input className="z-input" inputMode="numeric" value={price} onChange={(e) => setPrice(e.target.value.replace(/\D/g, '').slice(0, 6))} placeholder="1700" style={{ direction: 'ltr', textAlign: lang === 'ar' ? 'right' : 'left' }} /></AdField>
          <div>
            <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Promote this service', 'روّج هذه الخدمة')}</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <BoostOption on={boost === 'boost'} onClick={() => setBoost('boost')} icon="spark" gold title={L(lang, 'Boost now', 'روّج الآن')} desc={L(lang, 'Feature this service at the top of its category & the feed, with a Boosted badge — up to 5× more views.', 'اعرض هذه الخدمة بأعلى فئتها والقائمة مع شارة «مُروّج» — حتى ٥ أضعاف المشاهدات.')} price={L(lang, '+ AED 180', '+ ١٨٠ درهم')} />
              <BoostOption on={boost === 'regular'} onClick={() => setBoost('regular')} icon="list" title={L(lang, 'Regular post', 'إعلان عادي')} desc={L(lang, 'Appears in standard order within its category.', 'يظهر بالترتيب الاعتيادي في فئته.')} price={L(lang, 'Included', 'مشمول')} />
            </div>
          </div>
        </div>
      </div>
      <div style={{ padding: '12px 20px 26px', borderTop: '1px solid var(--line)', background: '#fff' }}>
        {added > 0 && <p className="sec" style={{ margin: '0 0 10px', fontSize: 12.5, fontWeight: 600, textAlign: 'center' }}>{added} {L(lang, 'service(s) added', 'خدمة مضافة')}</p>}
        <div style={{ display: 'flex', gap: 12 }}>
          {!editing && <button className="z-btn z-btn--outline" disabled={!valid} style={{ flex: '0 0 auto', width: 'auto', padding: '0 18px', gap: 7, opacity: valid ? 1 : 0.45, pointerEvents: valid ? 'auto' : 'none' }} onClick={() => {onSave(build());setAdded((n) => n + 1);reset();}}>
            <Icon name="plus" size={18} stroke={2.4} />{L(lang, 'Add more', 'أضف المزيد')}
          </button>}
          <Btn variant="rose" disabled={!valid && added === 0} onClick={() => {if (valid) onSave(build());onBack();}}>{editing ? L(lang, 'Save changes', 'حفظ التغييرات') : L(lang, 'Publish service', 'نشر الخدمة')}</Btn>
        </div>
      </div>
    </div>);

}

/* Edit business info — full page opened from the editor's pencil */
function VEditBasics({ profile, setProfile, onBack }) {
  const { lang } = useZafa();
  const th = THEMES[profile.theme] || THEMES.rose;
  const [name, setName] = React.useState(profile.name || '');
  const [details, setDetails] = React.useState(profile.details || '');
  const [theme, setTheme] = React.useState(profile.theme || 'rose');
  const [contacts, setContacts] = React.useState(profile.contacts || {});
  const setC = (k, v) => setContacts((s) => ({ ...s, [k]: v }));
  const save = () => { setProfile((p) => ({ ...p, name, details, theme, contacts })); onBack(); };
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ padding: '8px 20px 6px' }}><ScreenHeader title={L(lang, 'Edit business info', 'تعديل معلومات النشاط')} onBack={onBack} /></div>
      <div className="z-scroll no-bar" style={{ flex: 1, padding: '8px 20px 20px' }}>
        <div style={{ position: 'relative', height: 130, borderRadius: 18, overflow: 'hidden', marginBottom: 40 }}>
          <CoverArt theme={theme} icon="flower" id="eb-cover" seed={'ebc' + theme} radius={18} w={600} h={260} />
          <Img id="eb-cover-up" radius={18} ph="" style={{ position: 'absolute', inset: 0 }} />
          <span className="z-glass" style={{ position: 'absolute', top: 10, insetInlineEnd: 10, width: 34, height: 34, pointerEvents: 'none' }}><Icon name="image" size={17} /></span>
          <div style={{ position: 'absolute', bottom: -28, insetInlineStart: 18, width: 70, height: 70, borderRadius: 18, overflow: 'hidden', border: '3px solid var(--bg)', background: th.soft }}>
            <CoverArt theme={theme} icon="flower" src={monogramURI(name || 'My Studio', theme)} id="eb-logo" radius={15} w={140} h={140} />
            <Img id="eb-logo-up" radius={15} ph="" style={{ position: 'absolute', inset: 0 }} />
          </div>
        </div>
        <p className="muted" style={{ fontSize: 11.5, margin: '0 0 18px', textAlign: 'center' }}>{L(lang, 'Tap the cover or logo to upload', 'اضغط الغلاف أو الشعار للرفع')}</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <AdField label={L(lang, 'Business name', 'اسم النشاط')}><input className="z-input" value={name} onChange={(e) => setName(e.target.value)} placeholder={L(lang, 'Your business', 'نشاطك')} /></AdField>
          <AdField label={L(lang, 'Tagline', 'الوصف')}><textarea value={details} onChange={(e) => setDetails(e.target.value)} rows={2} className="z-input" style={{ height: 'auto', padding: '13px 16px', resize: 'none', lineHeight: 1.5 }} placeholder={L(lang, 'One line about your work', 'سطر عن عملك')} /></AdField>
          <div>
            <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Page color theme', 'لون الصفحة')}</p>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              {THEME_KEYS.map((k) => <button key={k} onClick={() => setTheme(k)} style={{ width: 40, height: 40, borderRadius: '50%', cursor: 'pointer', background: THEMES[k].accent, border: theme === k ? '3px solid var(--ink)' : '3px solid #fff', boxShadow: 'var(--sh-sm)' }} />)}
            </div>
          </div>

          {/* contact channels */}
          <div>
            <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Contact channels', 'قنوات التواصل')}</p>
            <div className="z-card" style={{ padding: '4px 16px' }}>
              {[['whatsapp', 'WhatsApp', '#25D366', '+971 50 123 4567'], ['phone', L(lang, 'Mobile', 'الجوال'), 'var(--rose-deep)', '+971 4 123 4567'], ['mail', L(lang, 'Email', 'البريد'), '#5A4F54', 'hello@business.com'], ['instagram', 'Instagram', '#C13584', '@yourhandle'], ['link', L(lang, 'Other link', 'رابط آخر'), '#2C3550', 'https://']].map(([k, lbl, cl, ph], i, arr) => {
                const enabled = contacts[k] !== false;
                const val = (contacts[k + '_v'] != null) ? contacts[k + '_v'] : '';
                return (
                  <div key={k} style={{ padding: '12px 0', borderBottom: i < arr.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                      <span style={{ width: 32, height: 32, borderRadius: 9, background: cl, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={k} size={16} style={{ color: '#ffffff' }} /></span>
                      <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{lbl}</span>
                      <button onClick={() => setC(k, enabled ? false : true)} style={{ width: 46, height: 27, borderRadius: 99, border: 'none', cursor: 'pointer', background: enabled ? 'var(--rose)' : 'var(--line)', position: 'relative', transition: 'background .15s', flexShrink: 0 }}>
                        <span style={{ position: 'absolute', top: 3, insetInlineStart: enabled ? 22 : 3, width: 21, height: 21, borderRadius: '50%', background: '#fff', transition: 'inset-inline-start .15s', boxShadow: '0 1px 3px rgba(0,0,0,.2)' }} />
                      </button>
                    </div>
                    {enabled && (
                      <input className="z-input" value={val} onChange={(e) => setC(k + '_v', e.target.value)} placeholder={ph}
                        style={{ height: 46, marginTop: 10, direction: k === 'mail' || k === 'link' || k === 'instagram' ? 'ltr' : 'ltr', textAlign: lang === 'ar' ? 'right' : 'left' }} />
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
      <div style={{ padding: '12px 20px 26px', borderTop: '1px solid var(--line)', background: '#fff' }}>
        <Btn variant="rose" onClick={save}>{L(lang, 'Save changes', 'حفظ التغييرات')}</Btn>
      </div>
    </div>);

}

/* 8 ── Profile editor (cover, logo, theme, services, contacts + live preview) */
function VProfileEditor({ profile, setProfile, tier, setTier, sub, setSub, onBack, onEditMode }) {
  const { lang } = useZafa();
  const th = THEMES[profile.theme] || THEMES.rose;
  const [editBasics, setEditBasicsRaw] = React.useState(false);
  const setEditBasics = (v) => { setEditBasicsRaw(v); onEditMode && onEditMode(v); };
  const setContact = (k, v) => setProfile((p) => ({ ...p, contacts: { ...p.contacts, [k]: v } }));
  const contacts = profile.contacts || {};
  const tr = TIERS[tier] || TIERS.standard;const ss = SUB_STATES[sub] || SUB_STATES.active;
  const other = tier === 'standard' ? 'upper' : 'standard';const otr = TIERS[other];
  const billing = [
  ['8 Jun 2026', tr.en, tr.price], ['8 May 2026', tr.en, tr.price], ['8 Apr 2026', TIERS.standard.en, TIERS.standard.price]];

  if (editBasics) return <VEditBasics profile={profile} setProfile={setProfile} onBack={() => setEditBasics(false)} />;

  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)' }}>
      <div style={{ padding: '8px 20px 4px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onBack} className="z-glass" style={{ background: '#fff', border: '1px solid var(--line)', flexShrink: 0 }}><Icon name="left" size={20} className="flip-x" /></button>
        <h1 className="h1" style={{ margin: 0, fontSize: 25 }}>{L(lang, 'Edit profile', 'تعديل الملف')}</h1>
      </div>

      {/* live preview */}
      <div style={{ padding: '14px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Live preview', 'معاينة حيّة')}</p>
        <div className="z-card" style={{ overflow: 'hidden', padding: 0 }}>
          <div style={{ position: 'relative', height: 110 }}>
            <CoverArt theme={profile.theme} icon="flower" id="ed-cover" seed={'edc' + profile.theme} radius={0} w={600} h={240} />
            <button onClick={() => setEditBasics(true)} className="z-glass" style={{ position: 'absolute', top: 10, insetInlineEnd: 10, width: 34, height: 34, border: 'none', cursor: 'pointer' }}><Icon name="edit" size={17} /></button>
            <div style={{ position: 'absolute', bottom: -22, insetInlineStart: 16, width: 56, height: 56, borderRadius: 16, overflow: 'hidden', border: '3px solid #fff', background: th.soft }}>
              <CoverArt theme={profile.theme} icon="flower" src={monogramURI(profile.name || 'My Studio', profile.theme)} id="ed-logo" radius={13} w={120} h={120} />
            </div>
          </div>
          <div style={{ padding: '28px 16px 16px' }}>
            <h3 className="serif" style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{profile.name || L(lang, 'Your business', 'نشاطك')}</h3>
            <p className="sec" style={{ margin: '4px 0 0', fontSize: 12.5, lineHeight: 1.4 }}>{profile.details || L(lang, 'Your short tagline appears here.', 'يظهر وصفك المختصر هنا.')}</p>
            <div style={{ display: 'flex', gap: 7, marginTop: 10 }}>
              {[['whatsapp', '#25D366'], ['phone', th.accent], ['mail', '#5A4F54'], ['instagram', '#C13584']].filter(([k]) => contacts[k] !== false).map(([ic, cl]) => <span key={ic} style={{ width: 30, height: 30, borderRadius: 9, background: cl, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={ic} size={15} style={{ color: '#ffffff' }} /></span>)}
            </div>
          </div>
        </div>
      </div>

      {/* cover + logo upload */}
      <div style={{ padding: '16px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Cover & logo', 'الغلاف والشعار')}</p>
        <div style={{ display: 'flex', gap: 10 }}>
          <div style={{ flex: 1, height: 84, borderRadius: 14, overflow: 'hidden', border: '1.5px dashed var(--rose-200)', position: 'relative' }}>
            <Img id="ed-cover-up" radius={14} ph="" />
            <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4, color: 'var(--muted)', pointerEvents: 'none' }}><Icon name="image" size={20} /><span style={{ fontSize: 11, fontWeight: 600 }}>{L(lang, 'Cover', 'الغلاف')}</span></div>
          </div>
          <div style={{ width: 84, height: 84, borderRadius: 14, overflow: 'hidden', border: '1.5px dashed var(--rose-200)', position: 'relative', flexShrink: 0 }}>
            <Img id="ed-logo-up" radius={14} ph="" />
            <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4, color: 'var(--muted)', pointerEvents: 'none' }}><Icon name="plus" size={18} stroke={2.4} /><span style={{ fontSize: 11, fontWeight: 600 }}>{L(lang, 'Logo', 'الشعار')}</span></div>
          </div>
        </div>
      </div>

      {/* theme color */}
      <div style={{ padding: '16px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Page color theme', 'لون الصفحة')}</p>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          {THEME_KEYS.map((k) => {
            const on = profile.theme === k;
            return <button key={k} onClick={() => setProfile((p) => ({ ...p, theme: k }))} style={{ width: 40, height: 40, borderRadius: '50%', cursor: 'pointer', background: THEMES[k].accent, border: on ? '3px solid var(--ink)' : '3px solid #fff', boxShadow: 'var(--sh-sm)' }} />;
          })}
        </div>
      </div>

      {/* basic fields */}
      <div style={{ padding: '16px 20px 4px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <AdField label={L(lang, 'Business name', 'اسم النشاط')}><input className="z-input" value={profile.name || ''} onChange={(e) => setProfile((p) => ({ ...p, name: e.target.value }))} placeholder={L(lang, 'Your business', 'نشاطك')} /></AdField>
        <AdField label={L(lang, 'Tagline', 'الوصف')}><input className="z-input" value={profile.details || ''} onChange={(e) => setProfile((p) => ({ ...p, details: e.target.value }))} placeholder={L(lang, 'One line about your work', 'سطر عن عملك')} /></AdField>
      </div>

      {/* contact channels */}
      <div style={{ padding: '16px 20px 28px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Contact channels', 'قنوات التواصل')}</p>
        <div className="z-card" style={{ padding: '4px 16px' }}>
          {[['whatsapp', 'WhatsApp', '#25D366'], ['phone', L(lang, 'Mobile', 'الجوال'), 'var(--rose-deep)'], ['mail', L(lang, 'Email', 'البريد'), '#5A4F54'], ['instagram', 'Instagram', '#C13584'], ['link', L(lang, 'Other link', 'رابط آخر'), '#2C3550']].map(([k, lbl, cl], i, arr) => {
            const enabled = contacts[k] !== false;
            return (
              <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 0', borderBottom: i < arr.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
                <span style={{ width: 32, height: 32, borderRadius: 9, background: cl, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={k} size={16} style={{ color: '#ffffff' }} /></span>
                <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{lbl}</span>
                <button onClick={() => setContact(k, enabled ? false : true)} style={{ width: 46, height: 27, borderRadius: 99, border: 'none', cursor: 'pointer', background: enabled ? 'var(--rose)' : 'var(--line)', position: 'relative', transition: 'background .15s' }}>
                  <span style={{ position: 'absolute', top: 3, insetInlineStart: enabled ? 22 : 3, width: 21, height: 21, borderRadius: '50%', background: '#fff', transition: 'inset-inline-start .15s', boxShadow: '0 1px 3px rgba(0,0,0,.2)' }} />
                </button>
              </div>);

          })}
        </div>
      </div>

      {/* subscription plan */}
      <div style={{ padding: '4px 20px 120px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Subscription plan', 'باقة الاشتراك')}</p>

        {/* change plan — moved to top */}
        <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
          {Object.entries(TIERS).map(([id, tt]) => {
            const cur = tier === id;
            return (
              <div key={id} style={{ flex: 1, borderRadius: 16, padding: 14, background: cur ? 'var(--rose-soft)' : '#fff', border: cur ? '2px solid var(--rose)' : '1.5px solid var(--line)', position: 'relative' }}>
                {cur && <span className="z-badge z-badge--rose" style={{ position: 'absolute', top: 12, insetInlineEnd: 12, fontSize: 9 }}>{L(lang, 'Current', 'الحالية')}</span>}
                <p className="serif" style={{ margin: 0, fontSize: 17, fontWeight: 600 }}>{L(lang, tt.en, tt.ar)}</p>
                <p className="muted" style={{ margin: '2px 0 14px', fontSize: 12.5 }}>AED {tt.price}/{L(lang, 'mo', 'ش')}</p>
                {cur ?
                <div style={{ textAlign: 'center', fontSize: 13, fontWeight: 700, color: 'var(--rose-deep)' }}>{L(lang, 'Active plan', 'الباقة المفعّلة')}</div> :
                <button onClick={() => setTier(id)} style={{ width: '100%', height: 42, borderRadius: 12, border: '1.5px solid var(--rose)', background: '#fff', cursor: 'pointer', color: 'var(--rose-deep)', fontWeight: 700, fontSize: 14, fontFamily: 'var(--sans)' }}>{L(lang, 'Switch', 'تبديل')}</button>}
              </div>);
          })}
        </div>

        {/* current plan removed */}

        {/* billing history */}
        <div className="z-card" style={{ padding: '6px 16px', marginBottom: 12 }}>
          <p className="eyebrow" style={{ margin: '12px 0 4px' }}>{L(lang, 'Billing history', 'سجل الفواتير')}</p>
          {billing.map(([date, plan, price], i) =>
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: i < billing.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <p style={{ margin: 0, fontSize: 13.5, fontWeight: 600 }}>{date}</p>
                <p className="muted" style={{ margin: '1px 0 0', fontSize: 12 }}>{L(lang, plan, plan)} {L(lang, 'Plan', 'باقة')}</p>
              </div>
              <span style={{ fontSize: 13.5, fontWeight: 700 }}>AED {Number(price).toFixed(2)}</span>
              <span style={{ fontSize: 10.5, fontWeight: 700, color: '#2E9E6B', background: '#E6F4EC', padding: '3px 8px', borderRadius: 999 }}>{L(lang, 'Paid', 'مدفوع')}</span>
              <button title="download" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--muted)', display: 'flex', padding: 2 }}><Icon name="share" size={17} style={{ transform: 'rotate(180deg)' }} /></button>
            </div>
          )}
        </div>

        {/* cancel subscription */}
        <div style={{ borderRadius: 16, padding: 16, border: '1.5px solid #F0C9C0', background: '#FCF1EE' }}>
          <p style={{ margin: 0, fontSize: 14, fontWeight: 700, color: '#C0392B', display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="warn" size={17} stroke={2.2} />{L(lang, 'Cancel subscription', 'إلغاء الاشتراك')}</p>
          <p className="sec" style={{ margin: '8px 0 14px', fontSize: 12.5, lineHeight: 1.45 }}>{L(lang, 'Your listing will be removed if you cancel. All profile data will be saved for 30 days.', 'سيُزال إعلانك عند الإلغاء. تُحفظ بيانات ملفك لمدة ٣٠ يوماً.')}</p>
          <button onClick={() => setSub && setSub('expired')} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', padding: '0 22px', height: 44, borderRadius: 999, border: '1.5px solid #E0A99F', background: '#fff', cursor: 'pointer', color: '#C0392B', fontWeight: 600, fontSize: 14, fontFamily: 'var(--sans)' }}>{L(lang, 'Cancel subscription', 'إلغاء الاشتراك')}</button>
        </div>
      </div>
    </div>);

}

/* Payment method details — full page */
function VPaymentMethods({ onBack }) {
  const { lang } = useZafa();
  const [cards, setCards] = React.useState([
    { id: 'c1', brand: 'Visa', last: '4242', exp: '08/27', primary: true },
    { id: 'c2', brand: 'Mastercard', last: '5588', exp: '03/26', primary: false }]);

  const makePrimary = (id) => setCards((s) => s.map((c) => ({ ...c, primary: c.id === id })));
  const del = (id) => setCards((s) => s.filter((c) => c.id !== id));
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ padding: '8px 20px 6px' }}><ScreenHeader title={L(lang, 'Payment method', 'طريقة الدفع')} onBack={onBack} /></div>
      <div className="z-scroll no-bar" style={{ flex: 1, padding: '8px 20px 28px' }}>
        {cards.filter((c) => c.primary).map((c) =>
        <div key={c.id} style={{ borderRadius: 20, padding: 20, marginBottom: 18, color: '#fff', position: 'relative', overflow: 'hidden', background: 'linear-gradient(135deg,#2A2227,#1B1418)', boxShadow: 'var(--sh)' }}>
            <div style={{ position: 'absolute', width: 180, height: 180, borderRadius: '50%', background: 'radial-gradient(circle,rgba(246,176,198,.4),transparent 70%)', top: -60, insetInlineEnd: -40 }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ width: 38, height: 28, borderRadius: 6, background: 'linear-gradient(135deg,#E7CD8E,#C8A24A)' }} />
              <span style={{ fontWeight: 700, fontSize: 15 }}>{c.brand}</span>
            </div>
            <p style={{ margin: '22px 0 14px', fontSize: 19, letterSpacing: '.12em', fontFamily: 'monospace', direction: 'ltr' }}>•••• •••• •••• {c.last}</p>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, color: 'rgba(255,255,255,.75)' }}>
              <span>{L(lang, 'Primary card', 'البطاقة الأساسية')}</span><span>{c.exp}</span>
            </div>
          </div>
        )}
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Your cards', 'بطاقاتك')}</p>
        <div className="z-card" style={{ padding: '4px 16px', marginBottom: 16 }}>
          {cards.map((c, i) =>
          <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 0', borderBottom: i < cards.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
              <span style={{ width: 38, height: 26, borderRadius: 6, background: c.brand === 'Visa' ? '#1A1F71' : '#EB001B', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, fontWeight: 800, flexShrink: 0 }}>{c.brand === 'Visa' ? 'VISA' : 'MC'}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <p style={{ margin: 0, fontSize: 13.5, fontWeight: 600, direction: 'ltr', textAlign: lang === 'ar' ? 'right' : 'left' }}>•••• {c.last}</p>
                <p className="muted" style={{ margin: '1px 0 0', fontSize: 11.5 }}>{L(lang, 'Expires', 'تنتهي')} {c.exp}</p>
              </div>
              {c.primary ?
            <span className="z-badge z-badge--rose" style={{ fontSize: 9 }}>{L(lang, 'Primary', 'أساسية')}</span> :
            <button onClick={() => makePrimary(c.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--rose-deep)', fontWeight: 600, fontSize: 12.5, fontFamily: 'var(--sans)' }}>{L(lang, 'Set primary', 'تعيين أساسية')}</button>}
              <button onClick={() => del(c.id)} title="remove" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--muted)', display: 'flex', padding: 2 }}><Icon name="trash" size={16} /></button>
            </div>
          )}
        </div>
        <Btn variant="outline" icon="plus" onClick={() => {}}>{L(lang, 'Add a new card', 'إضافة بطاقة جديدة')}</Btn>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 18, padding: '11px 14px', borderRadius: 12, background: 'var(--rose-soft)' }}>
          <Icon name="shield" size={17} style={{ color: 'var(--rose-deep)', flexShrink: 0 }} />
          <span style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.4 }}>{L(lang, 'Payments are encrypted and processed securely.', 'تتم معالجة المدفوعات بأمان وتشفير.')}</span>
        </div>
      </div>
    </div>);

}

/* Billing history details — full page */
function VBillingHistory({ tier, onBack }) {
  const { lang } = useZafa();
  const tr = TIERS[tier] || TIERS.standard;
  const rows = [
    { date: '8 Jun 2026', plan: tr.en, price: tr.price, status: 'paid', inv: 'INV-2026-0608' },
    { date: '8 May 2026', plan: tr.en, price: tr.price, status: 'paid', inv: 'INV-2026-0508' },
    { date: '8 Apr 2026', plan: 'Standard', price: 149, status: 'paid', inv: 'INV-2026-0408' },
    { date: '8 Mar 2026', plan: 'Standard', price: 149, status: 'paid', inv: 'INV-2026-0308' },
    { date: '8 Feb 2026', plan: 'Standard', price: 149, status: 'refunded', inv: 'INV-2026-0208' }];

  const paidTotal = rows.filter((r) => r.status === 'paid').reduce((a, r) => a + r.price, 0);
  const stTone = { paid: ['#2E9E6B', '#E6F4EC'], refunded: ['#A9711F', '#FBF3DC'] };
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ padding: '8px 20px 6px' }}><ScreenHeader title={L(lang, 'Billing history', 'سجل الفواتير')} onBack={onBack} /></div>
      <div className="z-scroll no-bar" style={{ flex: 1, padding: '8px 20px 28px' }}>
        <div className="z-card" style={{ padding: 16, marginBottom: 18, display: 'flex', alignItems: 'center', gap: 13 }}>
          <span style={{ width: 44, height: 44, borderRadius: 13, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="card" size={22} /></span>
          <div style={{ flex: 1 }}>
            <p className="muted" style={{ margin: 0, fontSize: 12.5 }}>{L(lang, 'Total paid', 'الإجمالي المدفوع')}</p>
            <p className="serif" style={{ margin: '2px 0 0', fontSize: 22, fontWeight: 700 }}>AED {paidTotal.toLocaleString()}</p>
          </div>
          <span className="muted" style={{ fontSize: 12 }}>{rows.length} {L(lang, 'invoices', 'فاتورة')}</span>
        </div>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Invoices', 'الفواتير')}</p>
        <div className="z-card" style={{ padding: '4px 16px' }}>
          {rows.map((r, i) =>
          <div key={r.inv} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 0', borderBottom: i < rows.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <p style={{ margin: 0, fontSize: 13.5, fontWeight: 600 }}>{r.date}</p>
                <p className="muted" style={{ margin: '1px 0 0', fontSize: 11.5 }}>{L(lang, r.plan, r.plan)} {L(lang, 'Plan', 'باقة')} · {r.inv}</p>
              </div>
              <div style={{ textAlign: lang === 'ar' ? 'left' : 'right' }}>
                <p style={{ margin: 0, fontSize: 13.5, fontWeight: 700 }}>AED {r.price}</p>
                <span style={{ fontSize: 9.5, fontWeight: 700, color: stTone[r.status][0], background: stTone[r.status][1], padding: '2px 7px', borderRadius: 999 }}>{L(lang, r.status === 'paid' ? 'Paid' : 'Refunded', r.status === 'paid' ? 'مدفوع' : 'مُسترد')}</span>
              </div>
              <button title="download" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--muted)', display: 'flex', padding: 2, flexShrink: 0 }}><Icon name="share" size={17} style={{ transform: 'rotate(180deg)' }} /></button>
            </div>
          )}
        </div>
      </div>
    </div>);

}

/* 12 ── Subscription management */
function VSubscription({ tier, setTier, sub, setSub, go }) {
  const { lang } = useZafa();
  const tr = TIERS[tier];const ss = SUB_STATES[sub];
  const [sub2, setSub2] = React.useState(null); // 'payment' | 'billing'
  if (sub2 === 'payment') return <VPaymentMethods onBack={() => setSub2(null)} />;
  if (sub2 === 'billing') return <VBillingHistory tier={tier} onBack={() => setSub2(null)} />;
  const other = tier === 'standard' ? 'upper' : 'standard';
  const otr = TIERS[other];
  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)' }}>
      <div style={{ padding: '8px 20px 4px' }}><h1 className="h1" style={{ margin: 0, fontSize: 25 }}>{L(lang, 'Subscription', 'الاشتراك')}</h1></div>

      {/* current plan */}
      <div style={{ padding: '14px 20px 4px' }}>
        <div className="z-card" style={{ padding: 18, position: 'relative', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
            <span className={`z-badge z-badge--${tr.tone === 'gold' ? 'gold' : 'rose'}`} style={{ fontSize: 11, padding: '5px 10px' }}>{L(lang, tr.en, tr.ar)}</span>
            <span style={{ fontSize: 12, fontWeight: 700, color: ss.tone, display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 7, height: 7, borderRadius: '50%', background: ss.tone }} />{L(lang, ss.en, ss.ar)}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, margin: '10px 0' }}>
            <span className="serif" style={{ fontSize: 30, fontWeight: 700 }}>AED {tr.price}</span><span className="muted" style={{ fontSize: 13.5 }}>/ {L(lang, 'month', 'شهر')}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--ink-2)' }}>
            <Icon name="calendar" size={15} style={{ color: 'var(--rose-deep)' }} />
            {sub === 'expired' ? L(lang, 'Expired on 1 Jun 2026', 'انتهى في ١ يونيو ٢٠٢٦') : L(lang, 'Renews on 1 Jul 2026', 'يتجدّد في ١ يوليو ٢٠٢٦')}
          </div>
        </div>
      </div>

      {/* upgrade/downgrade */}
      <div style={{ padding: '16px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{tier === 'standard' ? L(lang, 'Upgrade', 'ترقية') : L(lang, 'Change plan', 'تغيير الباقة')}</p>
        <div className="z-card" style={{ padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span className={`z-badge z-badge--${otr.tone === 'gold' ? 'gold' : 'rose'}`} style={{ fontSize: 11, padding: '5px 10px' }}>{L(lang, otr.en, otr.ar)}</span>
            <div style={{ flex: 1 }}><p className="sec" style={{ margin: 0, fontSize: 12.5 }}>{L(lang, otr.tagEn, otr.tagAr)}</p></div>
            <span className="serif" style={{ fontSize: 17, fontWeight: 700 }}>AED {otr.price}</span>
          </div>
          <div style={{ marginTop: 12 }}><Btn variant={other === 'upper' ? 'ink' : 'outline'} sm onClick={() => setTier(other)} style={{ width: '100%' }}>{tier === 'standard' ? L(lang, 'Upgrade to', 'الترقية إلى') : L(lang, 'Switch to', 'التبديل إلى')} {L(lang, otr.en, otr.ar)}</Btn></div>
        </div>
      </div>

      {/* manage */}
      <div style={{ padding: '16px 20px 4px' }}>
        <div className="z-card" style={{ padding: '2px 16px' }}>
          {[['card', L(lang, 'Payment method', 'طريقة الدفع'), '•••• 4242', 'payment'], ['list', L(lang, 'Billing history', 'سجل الفواتير'), '', 'billing']].map(([ic, lbl, val, dest], i, a) =>
          <button key={lbl} onClick={() => setSub2(dest)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px 0', background: 'none', border: 'none', borderBottom: i < a.length - 1 ? '1px solid var(--line-2)' : 'none', cursor: 'pointer', textAlign: 'start' }}>
              <span style={{ width: 32, height: 32, borderRadius: 9, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={ic} size={17} /></span>
              <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{lbl}</span>
              {val && <span className="muted" style={{ fontSize: 13 }}>{val}</span>}
              <Icon name="right" size={16} className="flip-x" style={{ color: 'var(--muted)' }} />
            </button>
          )}
        </div>
      </div>

      {/* demo state toggle */}
      <div style={{ padding: '16px 20px 28px' }}>
        <div style={{ padding: 12, borderRadius: 14, background: 'var(--rose-soft)', border: '1px dashed var(--rose-200)' }}>
          <p style={{ margin: '0 0 8px', fontSize: 12, fontWeight: 700, color: 'var(--rose-deep)', letterSpacing: '.04em' }}>{L(lang, 'DEMO · subscription state', 'تجربة · حالة الاشتراك')}</p>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {Object.keys(SUB_STATES).map((k) => <Chip key={k} on={sub === k} onClick={() => setSub(k)}>{L(lang, SUB_STATES[k].en, SUB_STATES[k].ar)}</Chip>)}
          </div>
        </div>
      </div>
    </div>);

}

/* ── Orchestrator ── */
function VendorApp({ onExit, initialPhase, initialVtab }) {
  const { lang } = useZafa();
  const [phase, setPhase] = React.useState(initialPhase || 'become'); // become|verify|account|business|plan|pay|app
  const [tier, setTier] = React.useState('standard');
  const [sub, setSub] = React.useState('active');
  const [profile, setProfile] = React.useState({ name: '', details: '', cats: [], theme: 'rose', contacts: {} });
  const [services, setServices] = React.useState(seedServices);
  const [vtab, setVtabRaw] = React.useState(initialVtab || 'dash');
  const [prevTab, setPrevTab] = React.useState('dash');
  const setVtab = (id) => {setVtabRaw((cur) => {setPrevTab(cur);return id;});};
  const [changePlan, setChangePlan] = React.useState(null); // target tier id when changing plan
  const [msgOpen, setMsgOpen] = React.useState(null); // open conversation id (hides dock)
  const [editMode, setEditMode] = React.useState(false); // edit-business-info page (hides dock)
  const [svcOpen, setSvcOpen] = React.useState(null); // open service id (detail page)
  const [editSvc, setEditSvc] = React.useState(null); // service object being edited
  const [vstack, setVstack] = React.useState([]); // app sub-screens
  const go = (name) => setVstack((s) => [...s, name]);
  const back = () => setVstack((s) => s.slice(0, -1));

  // funnel
  if (phase === 'become') return <VBecome onNext={() => setPhase('verify')} onExit={onExit} />;
  if (phase === 'verify') return <VVerify onNext={() => setPhase('account')} onBack={() => setPhase('become')} />;
  if (phase === 'account') return <VCreateAccount onNext={() => setPhase('business')} onBack={() => setPhase('verify')} />;
  if (phase === 'business') return <VBusiness profile={profile} setProfile={setProfile} onNext={() => setPhase('plan')} onBack={() => setPhase('account')} />;
  if (phase === 'plan') return <VTiers tier={tier} setTier={setTier} onNext={() => setPhase('pay')} onBack={() => setPhase('business')} />;
  if (phase === 'pay') return <VSubPay tier={tier} onActivated={() => {setPhase('app');setVtab('services');setVstack(['addservice']);}} onBack={() => setPhase('plan')} />;

  // changing subscription plan → payment flow
  if (changePlan) return <VSubPay tier={changePlan} changeMode onActivated={() => {setTier(changePlan);setSub('active');setChangePlan(null);}} onBack={() => setChangePlan(null)} />;

  // activated app
  const level = tier === 'upper' ? 'premium' : 'established';
  let screen,showDock = false;
  const top = vstack[vstack.length - 1];
  if (top === 'addservice') screen = <VAddService onBack={back} onSave={(s) => {setServices((p) => [s, ...p]);back();}} />;else
  if (editSvc) {screen = <VAddService initial={editSvc} onBack={() => setEditSvc(null)} onSave={(s) => { setServices((p) => p.map((x) => x.id === s.id ? s : x)); setEditSvc(null); }} />;}else
  if (svcOpen && services.find((x) => x.id === svcOpen)) {screen = <VServiceDetail service={services.find((x) => x.id === svcOpen)} setServices={setServices} onBack={() => setSvcOpen(null)} onEdit={(s) => setEditSvc(s)} onBoost={() => { setSvcOpen(null); setVtab('analytics'); }} />;}else
  {
    showDock = true;
    screen = vtab === 'dash' ? <VDashboard tier={tier} sub={sub} setSub={setSub} level={level} profile={profile} go={(g) => g === 'sub' ? setVtab('sub') : g === 'analytics' ? setVtab('analytics') : go(g)} /> :
    vtab === 'services' ? <VServices services={services} setServices={setServices} go={go} onExit={() => setVtab(prevTab)} onOpen={(id) => setSvcOpen(id)} /> :
    vtab === 'messages' ? <VMessages open={msgOpen} setOpen={setMsgOpen} /> :
    vtab === 'editor' ? <VProfileEditor profile={profile} setProfile={setProfile} tier={tier} setTier={(t) => setChangePlan(t)} sub={sub} setSub={setSub} onBack={() => setVtab(prevTab)} onEditMode={setEditMode} /> :
    vtab === 'sub' ? <VSubscription tier={tier} setTier={(t) => setChangePlan(t)} sub={sub} setSub={setSub} go={go} /> :
    <VAnalytics tier={tier} level={level} />;
    if (vtab === 'messages' && msgOpen) showDock = false;
    if (vtab === 'editor' && editMode) showDock = false;
  }
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', position: 'relative' }}>
      <div style={{ flex: 1, minHeight: 0 }}>{screen}</div>
      {showDock && <VendorDock vtab={['analytics', 'sub'].includes(vtab) ? 'dash' : vtab} setVtab={setVtab} />}
    </div>);

}

Object.assign(window, { VendorApp, VendorDock, VDashboard, VBoost, VServices, VAddService, VProfileEditor, VSubscription });