/* ===========================================================
   راویار — لایهٔ تعامل: پشتیبانی، اعلان‌ها، اشتراک‌گذاری
   =========================================================== */

/* ---- Social glyph row ---- */
function SocialRow({ size = 38, gap = 10, labels = false }) {
  return (
    <div className="row wrap" style={{ gap }}>
      {OMID.SOCIALS.map(s => (
        <a key={s.id} href="#" onClick={e => e.preventDefault()} title={OMID.TX(s)}
          className="row gap-2" style={{ width: labels ? 'auto' : size, height: size, padding: labels ? '0 14px' : 0,
            borderRadius: labels ? 12 : 999, justifyContent: 'center', flexShrink: 0,
            background: 'rgba(231,222,201,.05)', border: '1px solid var(--hairline)', color: s.tint, transition: 'all .16s' }}
          onMouseEnter={e => { e.currentTarget.style.background = s.tint + '22'; e.currentTarget.style.borderColor = s.tint + '66'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'rgba(231,222,201,.05)'; e.currentTarget.style.borderColor = 'var(--hairline)'; }}>
          <Icon name={s.glyph} size={18} />
          {labels && <span style={{ fontSize: 13, color: 'var(--cream-2)', direction: 'ltr' }}>{s.handle}</span>}
        </a>
      ))}
    </div>
  );
}

/* ---- Share menu (story) ---- */
function ShareButton({ story }) {
  const [open, setOpen] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const targets = OMID.SOCIALS.filter(s => ['instagram', 'telegram', 'x', 'youtube'].includes(s.id));
  return (
    <div style={{ position: 'relative' }}>
      <button className="btn btn-ghost" style={{ padding: '13px 18px' }} onClick={() => setOpen(o => !o)}><Icon name="share" size={16} /> {L('اشتراک‌گذاری', 'Share')}</button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
          <div className="panel gold-frame" style={{ position: 'absolute', bottom: 'calc(100% + 10px)', insetInlineStart: 0, zIndex: 50, padding: 14, width: 240, boxShadow: 'var(--shadow-pop)' }}>
            <div className="muted" style={{ fontSize: 12, marginBottom: 10 }}>{L('اشتراک «' + OMID.TX(story) + '» در', 'Share “' + OMID.TX(story) + '” on')}</div>
            <div className="row wrap gap-2" style={{ marginBottom: 12 }}>
              {targets.map(s => (
                <button key={s.id} className="row gap-2" style={{ padding: '8px 12px', borderRadius: 10, background: 'rgba(231,222,201,.05)', border: '1px solid var(--hairline)', color: s.tint, fontSize: 13 }}>
                  <Icon name={s.glyph} size={16} /> <span style={{ color: 'var(--cream-2)' }}>{OMID.TX(s)}</span>
                </button>
              ))}
            </div>
            <button onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }}
              className="row between" style={{ width: '100%', padding: '10px 12px', borderRadius: 10, background: 'rgba(7,13,34,.4)', border: '1px solid var(--hairline)' }}>
              <span style={{ fontSize: 12.5, direction: 'ltr', color: 'var(--muted)' }}>ravyar.ir/s/{story.id}</span>
              <span className="row gap-1" style={{ fontSize: 12.5, color: copied ? 'var(--turq-400)' : 'var(--gold-400)' }}><Icon name={copied ? 'check' : 'link'} size={14} />{copied ? L('کپی شد', 'Copied') : L('کپی', 'Copy')}</span>
            </button>
          </div>
        </>
      )}
    </div>
  );
}

/* ---- Live chat view ---- */
function ChatView() {
  const [msgs, setMsgs] = React.useState([
    { me: false, t: L('سلام! به پشتیبانی راویار خوش آمدید 🌟 چطور می‌توانم کمکتان کنم؟', 'Hi! Welcome to Ravyar support 🌟 How can I help you?'), when: OMID.num('۱۴:۰۲') },
  ]);
  const [val, setVal] = React.useState('');
  const endRef = React.useRef(null);
  React.useEffect(() => { if (endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; }, [msgs]);
  const send = (text) => {
    const t = (text || val).trim(); if (!t) return;
    setMsgs(m => [...m, { me: true, t, when: L('الان', 'now') }]); setVal('');
    setTimeout(() => setMsgs(m => [...m, { me: false, t: L('ممنون از پیام شما؛ کارشناس ما همین حالا بررسی می‌کند و پاسخ می‌دهد. در همین حین می‌توانید وضعیت پرداخت را از کیف پول دنبال کنید.', 'Thanks for your message — an agent is reviewing it now and will reply shortly. Meanwhile you can track your payment status in your wallet.'), when: L('الان', 'now') }]), 900);
  };
  const quick = OMID.getLang() === 'en' ? ['My payment failed', 'My coins dropped', 'Playback problem'] : ['پرداختم ناموفق شد', 'سکه‌ام کم شده', 'مشکل در پخش داستان'];
  return (
    <div className="col" style={{ height: 380 }}>
      <div ref={endRef} className="scroll col gap-2" style={{ flex: 1, overflowY: 'auto', padding: '4px 2px' }}>
        {msgs.map((m, i) => (
          <div key={i} style={{ alignSelf: m.me ? 'flex-start' : 'flex-end', maxWidth: '82%' }}>
            <div style={{ padding: '10px 14px', borderRadius: m.me ? '14px 14px 4px 14px' : '14px 14px 14px 4px', fontSize: 13.5, lineHeight: 1.8,
              background: m.me ? 'linear-gradient(135deg,var(--turq-500),var(--turq-600))' : 'rgba(231,222,201,.06)',
              color: m.me ? '#042a27' : 'var(--cream)', border: m.me ? 'none' : '1px solid var(--hairline)' }}>{m.t}</div>
            <div className="muted" style={{ fontSize: 10.5, marginTop: 3, textAlign: m.me ? 'start' : 'end' }}>{m.when}</div>
          </div>
        ))}
      </div>
      <div className="row gap-1 wrap" style={{ padding: '8px 0' }}>
        {quick.map((q, i) => <button key={i} className="chip" style={{ fontSize: 11.5 }} onClick={() => send(q)}>{q}</button>)}
      </div>
      <div className="row gap-2" style={{ background: 'rgba(7,13,34,.45)', border: '1px solid var(--hairline)', borderRadius: 12, padding: '8px 8px 8px 14px' }}>
        <input value={val} onChange={e => setVal(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} placeholder={L('پیام خود را بنویسید…', 'Type your message…')}
          style={{ flex: 1, background: 'none', border: 'none', outline: 'none', color: 'var(--cream)', fontSize: 13.5 }} />
        <button onClick={() => send()} className="btn btn-turq" style={{ padding: '8px 12px' }}><Icon name="send" size={15} /></button>
      </div>
    </div>
  );
}

/* ---- Ticket form ---- */
function TicketView({ onDone }) {
  const [sent, setSent] = React.useState(false);
  const [topic, setTopic] = React.useState(L('پرداخت و کیف پول', 'Payment & wallet'));
  if (sent) return (
    <div className="col center" style={{ height: 380, gap: 14, textAlign: 'center' }}>
      <div style={{ width: 60, height: 60, borderRadius: 99, display: 'grid', placeItems: 'center', background: 'rgba(28,183,172,.16)', color: 'var(--turq-400)' }}><Icon name="check" size={30} /></div>
      <b style={{ fontSize: 17 }}>{L('تیکت شما ثبت شد', 'Your ticket is submitted')}</b>
      <span className="muted" style={{ fontSize: 13.5, maxWidth: 280, lineHeight: 1.9 }}>{L('کد پیگیری', 'Reference')} <b className="gold fa-num">TK-{OMID.num('۹۲۸۴۱')}</b> — {L('پاسخ تا کمتر از ۲ ساعت در «اعلان‌ها» و ایمیل ارسال می‌شود.', 'A reply will arrive within 2 hours in Notifications and by email.')}</span>
      <button className="btn btn-ghost" onClick={onDone} style={{ marginTop: 6 }}>{L('بازگشت', 'Back')}</button>
    </div>
  );
  return (
    <div className="scroll col gap-3" style={{ height: 380, overflowY: 'auto' }}>
      <label className="col gap-2"><span style={{ fontSize: 12.5, color: 'var(--cream-2)' }}>{L('موضوع', 'Topic')}</span>
        <div className="row gap-1 wrap">
          {(OMID.getLang() === 'en' ? ['Payment & wallet', 'Technical issue', 'Subscription', 'Content', 'Other'] : ['پرداخت و کیف پول', 'مشکل فنی', 'اشتراک', 'محتوا', 'سایر']).map(t => (
            <button key={t} onClick={() => setTopic(t)} className={'chip' + (topic === t ? ' is-active' : '')} style={{ fontSize: 12.5 }}>{t}</button>
          ))}
        </div>
      </label>
      <label className="col gap-2"><span style={{ fontSize: 12.5, color: 'var(--cream-2)' }}>{L('عنوان', 'Subject')}</span>
        <div style={{ background: 'rgba(7,13,34,.45)', border: '1px solid var(--hairline)', borderRadius: 10, padding: '10px 13px' }}>
          <input placeholder={L('خلاصهٔ مشکل…', 'Summary of the issue…')} style={{ width: '100%', background: 'none', border: 'none', outline: 'none', color: 'var(--cream)', fontSize: 13.5 }} /></div>
      </label>
      <label className="col gap-2 grow"><span style={{ fontSize: 12.5, color: 'var(--cream-2)' }}>{L('توضیحات', 'Description')}</span>
        <textarea placeholder={L('جزئیات بیشتر، کد پیگیری پرداخت و…', 'More details, payment reference code, etc.')} style={{ minHeight: 120, resize: 'none', background: 'rgba(7,13,34,.45)', border: '1px solid var(--hairline)', borderRadius: 10, padding: '11px 13px', color: 'var(--cream)', fontSize: 13.5, outline: 'none', lineHeight: 1.8 }} />
      </label>
      <button onClick={() => setSent(true)} className="btn btn-gold" style={{ justifyContent: 'center', padding: 13 }}><Icon name="send" size={15} /> {L('ارسال تیکت', 'Submit ticket')}</button>
    </div>
  );
}

/* ---- FAQ accordion ---- */
function FaqView() {
  const [open, setOpen] = React.useState(0);
  return (
    <div className="col gap-2" style={{ height: 380, overflowY: 'auto' }}>
      {OMID.FAQ.map((f, i) => (
        <div key={i} className="panel" style={{ padding: 0, overflow: 'hidden', border: '1px solid var(--hairline)' }}>
          <button onClick={() => setOpen(open === i ? -1 : i)} className="row between" style={{ width: '100%', padding: '13px 15px', textAlign: 'start' }}>
            <b style={{ fontSize: 13.5 }}>{OMID.TX(f, 'q')}</b>
            <Icon name="chevron" size={14} style={{ transform: open === i ? 'rotate(-90deg)' : 'rotate(90deg)', color: 'var(--gold-400)', flexShrink: 0 }} />
          </button>
          {open === i && <p className="muted" style={{ fontSize: 13, lineHeight: 2, padding: '0 15px 15px' }}>{OMID.TX(f, 'a')}</p>}
        </div>
      ))}
    </div>
  );
}

/* ---- Floating Support Hub ---- */
function SupportHub({ go }) {
  const [open, setOpen] = React.useState(false);
  const [view, setView] = React.useState('home'); // home | chat | ticket | faq
  const titles = { home: L('پشتیبانی راویار', 'Ravyar support'), chat: L('گفتگوی زنده', 'Live chat'), ticket: L('ثبت تیکت', 'Open a ticket'), faq: L('سؤالات متداول', 'FAQ') };
  const openView = (id) => {
    if (id === 'call') return;
    setView(id);
  };
  return (
    <>
      {/* Floating button */}
      <button onClick={() => { setOpen(o => !o); setView('home'); }}
        style={{ position: 'fixed', insetInlineStart: 24, bottom: 24, zIndex: 150, width: 58, height: 58, borderRadius: 999,
          background: 'linear-gradient(135deg,var(--turq-400),var(--turq-600))', color: '#042a27', display: 'grid', placeItems: 'center',
          boxShadow: '0 14px 36px -10px var(--turq-glow), 0 0 0 1px rgba(69,214,200,.4)' }}>
        <Icon name={open ? 'chevron' : 'headset'} size={26} style={{ transform: open ? 'rotate(90deg)' : 'none' }} />
        {!open && <span style={{ position: 'absolute', top: 2, insetInlineEnd: 2, width: 13, height: 13, borderRadius: 99, background: 'var(--gold-400)', border: '2px solid var(--night-850)' }} />}
      </button>

      {open && (
        <div className="panel gold-frame" style={{ position: 'fixed', insetInlineStart: 24, bottom: 94, zIndex: 150, width: 'min(380px, calc(100vw - 48px))',
          maxHeight: 'min(560px, calc(100vh - 130px))', display: 'flex', flexDirection: 'column', padding: 0, overflow: 'hidden', boxShadow: 'var(--shadow-pop)', animation: 'rise .25s ease both' }}>
          {/* header */}
          <div style={{ padding: '16px 18px', background: 'linear-gradient(135deg, rgba(28,183,172,.18), rgba(20,48,80,.4))', borderBottom: '1px solid var(--hairline)' }}>
            <div className="row between">
              <div className="row gap-2">
                {view !== 'home' && <button onClick={() => setView('home')} className="chip" style={{ padding: 6, width: 28, height: 28, justifyContent: 'center' }}><Icon name="chevron" size={15} /></button>}
                <div className="col"><b style={{ fontSize: 15.5 }}>{titles[view]}</b><span className="row gap-1" style={{ fontSize: 11.5, color: 'var(--turq-400)' }}><span style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--turq-400)', boxShadow: '0 0 6px var(--turq-glow)' }} /> {L('آنلاین · پاسخ‌گویی ۲۴ ساعته', 'Online · 24/7 support')}</span></div>
              </div>
              <button onClick={() => setOpen(false)} className="chip" style={{ width: 30, height: 30, justifyContent: 'center', padding: 0 }}><Icon name="plus" size={16} style={{ transform: 'rotate(45deg)' }} /></button>
            </div>
          </div>
          {/* body */}
          <div className="scroll" style={{ padding: 16, overflowY: 'auto', flex: 1 }}>
            {view === 'home' && (
              <div className="col gap-3">
                <div className="col gap-2">
                  {OMID.SUPPORT_CHANNELS.map(c => (
                    <button key={c.id} onClick={() => openView(c.id)} className="row between" style={{ padding: '13px 14px', borderRadius: 14, background: 'rgba(231,222,201,.04)', border: '1px solid var(--hairline)', textAlign: 'start' }}>
                      <div className="row gap-2">
                        <span style={{ width: 38, height: 38, borderRadius: 11, display: 'grid', placeItems: 'center', background: c.tint + '22', color: c.tint }}><Icon name={c.icon} size={19} /></span>
                        <div className="col"><b style={{ fontSize: 14 }}>{OMID.TX(c)}</b><span className="muted" style={{ fontSize: 11.5 }}>{OMID.TX(c, 'sub')}</span></div>
                      </div>
                      <span className="chip" style={{ fontSize: 10.5, padding: '3px 9px', color: c.tint, borderColor: c.tint + '55' }}>{OMID.TX(c, 'meta')}</span>
                    </button>
                  ))}
                </div>
                {/* Payment status shortcut */}
                <button onClick={() => { setOpen(false); go && go('pricing'); }} className="gold-frame" style={{ padding: '13px 15px', borderRadius: 14, textAlign: 'start', background: 'linear-gradient(135deg, rgba(212,169,76,.14), rgba(28,183,172,.08))' }}>
                  <div className="row between">
                    <div className="row gap-2"><CoinGlyph size={22} /><div className="col"><b style={{ fontSize: 13.5 }}>{L('وضعیت پرداخت‌ها و کیف پول', 'Payments & wallet status')}</b><span className="muted" style={{ fontSize: 11.5 }}>{L('پیگیری تراکنش‌های موفق / در انتظار', 'Track successful / pending transactions')}</span></div></div>
                    <Icon name="arrowR" size={16} style={{ color: 'var(--gold-400)' }} />
                  </div>
                </button>
                {/* socials */}
                <div>
                  <div className="muted" style={{ fontSize: 12, marginBottom: 8 }}>{L('ما را دنبال کنید', 'Follow us')}</div>
                  <SocialRow size={36} />
                </div>
              </div>
            )}
            {view === 'chat' && <ChatView />}
            {view === 'ticket' && <TicketView onDone={() => setView('home')} />}
            {view === 'faq' && <FaqView />}
          </div>
        </div>
      )}
    </>
  );
}

/* ---- Notifications panel + bell ---- */
function NotificationBell({ go }) {
  const [open, setOpen] = React.useState(false);
  const [items, setItems] = React.useState(OMID.NOTIFICATIONS);
  const unread = items.filter(n => n.unread).length;
  const markAll = () => setItems(its => its.map(n => ({ ...n, unread: false })));
  const click = (n) => {
    setItems(its => its.map(x => x.id === n.id ? { ...x, unread: false } : x));
    if (n.kind === 'pay') { setOpen(false); go && go('pricing'); }
    if (n.kind === 'content') { setOpen(false); go && go('home'); }
  };
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} className="chip" style={{ width: 38, height: 38, justifyContent: 'center', padding: 0, borderRadius: 999, position: 'relative' }}>
        <Icon name="bell" size={17} />
        {unread > 0 && <span className="fa-num" style={{ position: 'absolute', top: -4, insetInlineEnd: -4, minWidth: 18, height: 18, padding: '0 4px', borderRadius: 99, background: 'var(--ochre-500)', color: '#fff', fontSize: 10.5, fontWeight: 700, display: 'grid', placeItems: 'center', border: '2px solid var(--night-850)' }}>{OMID.num(unread)}</span>}
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 100 }} />
          <div className="panel gold-frame" style={{ position: 'absolute', top: 'calc(100% + 10px)', insetInlineEnd: 0, zIndex: 110, width: 'min(360px, calc(100vw - 32px))', padding: 0, overflow: 'hidden', boxShadow: 'var(--shadow-pop)', animation: 'rise .2s ease both' }}>
            <div className="row between" style={{ padding: '14px 16px', borderBottom: '1px solid var(--hairline)' }}>
              <b style={{ fontSize: 15 }}>{L('اعلان‌ها', 'Notifications')} {unread > 0 && <span className="fa-num muted" style={{ fontSize: 12, fontWeight: 400 }}>· {OMID.num(unread)} {L('جدید', 'new')}</span>}</b>
              {unread > 0 && <button onClick={markAll} className="muted" style={{ fontSize: 12 }}>{L('خواندن همه', 'Mark all read')}</button>}
            </div>
            <div className="scroll col" style={{ maxHeight: 360, overflowY: 'auto' }}>
              {items.map(n => (
                <button key={n.id} onClick={() => click(n)} className="row gap-2" style={{ padding: '12px 16px', borderBottom: '1px solid var(--hairline)', textAlign: 'start', position: 'relative',
                  background: n.unread ? 'rgba(69,214,200,.05)' : 'transparent' }}>
                  <span style={{ width: 34, height: 34, borderRadius: 10, display: 'grid', placeItems: 'center', background: n.tint + '22', color: n.tint, flexShrink: 0 }}><Icon name={n.icon} size={16} /></span>
                  <div className="col grow"><span style={{ fontSize: 13, lineHeight: 1.7 }}>{OMID.TX(n)}</span><span className="muted" style={{ fontSize: 11, marginTop: 2 }}>{OMID.TX(n, 'when')}</span></div>
                  {n.unread && <span style={{ width: 8, height: 8, borderRadius: 99, background: 'var(--turq-400)', flexShrink: 0, marginTop: 6 }} />}
                </button>
              ))}
            </div>
            <button className="row center gap-1" style={{ width: '100%', padding: '12px', fontSize: 12.5, color: 'var(--gold-400)' }}><Icon name="bell" size={13} /> {L('تنظیمات اعلان‌ها', 'Notification settings')}</button>
          </div>
        </>
      )}
    </div>
  );
}

Object.assign(window, { SocialRow, ShareButton, SupportHub, NotificationBell });
