/* Sanjab Studio — ماژول پشتیبانی و چت آنلاین (برگرفته از مخزن وبکستینگ).
   چت‌بات AI برای سؤالات پرتکرار + اتصال به تیکتینگ. خوداتکا؛ window.SJ_SUPPORT.open().
   این ماژول در مخزن وبکستینگ تعریف شده و برای همهٔ سایت‌ها از جمله سنجاب استفاده می‌شود. */
const { Button: SUPButton, Icon: SUPIcon } = window.DesignSystem_7abc08;

(function injectSupportCSS(){
  if (document.getElementById('sj-support-css')) return;
  const el = document.createElement('style');
  el.id = 'sj-support-css';
  el.textContent = `
  .sup-fab{position:fixed;inset:auto auto 24px 24px;z-index:140;display:flex;align-items:center;gap:10px;
    height:58px;padding:0 22px 0 18px;border:none;border-radius:100px;cursor:pointer;font:inherit;font-weight:700;
    font-size:.94rem;color:#1a1205;background:var(--grad-brand,linear-gradient(135deg,var(--brand),var(--brand-deep)));
    box-shadow:0 16px 38px -12px var(--brand);transition:transform .25s var(--ease),box-shadow .25s}
  .sup-fab:hover{transform:translateY(-3px)}
  .sup-fab .ic{width:24px;height:24px;stroke:#1a1205;stroke-width:1.9}
  .sup-fab .sup-dot{position:absolute;inset-block-start:-2px;inset-inline-end:-2px;width:14px;height:14px;border-radius:50%;
    background:var(--green);border:2px solid var(--bg)}
  @media(max-width:560px){.sup-fab .sup-fab-txt{display:none} .sup-fab{padding:0;width:58px;justify-content:center}}

  .sup-panel{position:fixed;inset:auto auto 24px 24px;z-index:150;width:380px;max-width:calc(100vw - 32px);
    height:560px;max-height:calc(100vh - 48px);display:flex;flex-direction:column;overflow:hidden;
    border-radius:24px;background:linear-gradient(180deg,var(--card),var(--card-2));border:1px solid var(--line-2);
    box-shadow:0 40px 90px -28px rgba(0,0,0,.8);animation:supPop .3s var(--ease) both}
  @keyframes supPop{from{opacity:0;transform:translateY(24px) scale(.97)}to{opacity:1;transform:none}}
  .sup-head{display:flex;align-items:center;gap:12px;padding:18px 18px 16px;
    background:linear-gradient(135deg,var(--brand),var(--brand-deep));color:#1a1205}
  .sup-head .av{width:42px;height:42px;flex:0 0 auto;border-radius:13px;display:grid;place-items:center;
    background:rgba(255,255,255,.25);backdrop-filter:blur(6px)}
  .sup-head .av .ic{width:24px;height:24px;stroke:#1a1205;stroke-width:1.9}
  .sup-head b{font-size:1.02rem;font-weight:800;display:block;line-height:1.2}
  .sup-head small{font-size:.74rem;font-weight:600;opacity:.8;display:flex;align-items:center;gap:5px}
  .sup-head small::before{content:'';width:7px;height:7px;border-radius:50%;background:#16331f}
  .sup-head .x{margin-inline-start:auto;width:34px;height:34px;border-radius:9px;display:grid;place-items:center;
    cursor:pointer;background:rgba(0,0,0,.12);border:none;color:#1a1205}
  .sup-head .x .ic{width:18px;height:18px;stroke-width:2.2}

  .sup-tabs{display:flex;gap:6px;padding:10px 14px;border-bottom:1px solid var(--line);background:var(--bg-2)}
  .sup-tabs button{flex:1;padding:9px;border-radius:10px;border:1px solid transparent;background:none;cursor:pointer;
    font:inherit;font-weight:700;font-size:.84rem;color:var(--t2);display:flex;align-items:center;justify-content:center;gap:7px;transition:.18s}
  .sup-tabs button .ic{width:16px;height:16px}
  .sup-tabs button.on{color:var(--brand-2);background:var(--brand-soft);border-color:color-mix(in oklab,var(--brand) 28%,transparent)}

  .sup-body{flex:1;overflow-y:auto;padding:16px}
  .sup-msg{display:flex;gap:9px;margin-bottom:14px}
  .sup-msg .b{max-width:80%;padding:11px 14px;border-radius:15px;font-size:.9rem;line-height:1.7}
  .sup-msg.bot .b{background:var(--surface);border:1px solid var(--line);border-start-start-radius:5px;color:var(--t1)}
  .sup-msg.me{flex-direction:row-reverse}
  .sup-msg.me .b{background:var(--brand-soft);border:1px solid color-mix(in oklab,var(--brand) 26%,transparent);
    color:var(--t1);border-start-end-radius:5px}
  .sup-msg .mav{width:30px;height:30px;flex:0 0 auto;border-radius:9px;display:grid;place-items:center;
    background:var(--grad-mark,linear-gradient(135deg,var(--brand),var(--gold)))}
  .sup-msg .mav .ic{width:17px;height:17px;stroke:#1a1205;stroke-width:1.9}
  .sup-faq-lbl{font-size:.74rem;color:var(--t3);font-weight:600;margin:4px 0 10px}
  .sup-faqs{display:flex;flex-direction:column;gap:8px}
  .sup-faq{text-align:start;padding:11px 14px;border-radius:13px;border:1px solid var(--line);background:var(--card);
    cursor:pointer;font:inherit;font-size:.86rem;color:var(--t1);font-weight:600;transition:.18s;display:flex;align-items:center;gap:9px}
  .sup-faq:hover{border-color:var(--brand);background:var(--brand-soft)}
  .sup-faq .ic{width:16px;height:16px;color:var(--brand);flex:0 0 auto}
  .sup-ai-tag{display:inline-flex;align-items:center;gap:6px;font-size:.7rem;font-weight:700;color:var(--brand-2);
    padding:3px 9px;border-radius:100px;background:var(--brand-soft);margin-bottom:10px}
  .sup-ai-tag .ic{width:13px;height:13px}

  .sup-foot{padding:12px 14px;border-top:1px solid var(--line);background:var(--bg-2)}
  .sup-input{display:flex;gap:9px;align-items:center}
  .sup-input input{flex:1;padding:11px 14px;border-radius:12px;background:var(--card);border:1px solid var(--line-2);
    color:var(--t1);font:inherit;font-size:.9rem}
  .sup-input input:focus{outline:none;border-color:var(--brand);box-shadow:0 0 0 3px var(--brand-soft)}
  .sup-send{width:42px;height:42px;flex:0 0 auto;border-radius:12px;border:none;cursor:pointer;display:grid;place-items:center;
    background:var(--grad-brand,linear-gradient(135deg,var(--brand),var(--brand-deep)))}
  .sup-send .ic{width:20px;height:20px;stroke:#1a1205;stroke-width:2}
  .sup-escalate{display:flex;align-items:center;gap:8px;justify-content:center;margin-top:10px;font-size:.78rem;color:var(--t3)}
  .sup-escalate a{color:var(--brand);font-weight:700;text-decoration:none;cursor:pointer}

  .sup-field{margin-bottom:13px}
  .sup-field label{display:block;font-size:.82rem;color:var(--t2);font-weight:600;margin-bottom:6px}
  .sup-field input,.sup-field select,.sup-field textarea{width:100%;padding:11px 13px;border-radius:12px;
    background:var(--card);border:1px solid var(--line-2);color:var(--t1);font:inherit;font-size:.9rem}
  .sup-field textarea{resize:vertical;min-height:84px}
  .sup-field input:focus,.sup-field select:focus,.sup-field textarea:focus{outline:none;border-color:var(--brand);box-shadow:0 0 0 3px var(--brand-soft)}
  .sup-ok{text-align:center;padding:30px 10px}
  .sup-ok .ic-ok{width:60px;height:60px;margin:0 auto 14px;border-radius:50%;display:grid;place-items:center;
    color:var(--green);background:rgba(45,212,160,.13);border:1px solid color-mix(in oklab,var(--green) 35%,transparent)}
  .sup-ok .ic-ok .ic{width:30px;height:30px;stroke-width:2.4}
  .sup-ok h4{font-size:1.08rem;margin-bottom:8px}
  .sup-ok p{color:var(--t2);font-size:.88rem;line-height:1.8}
  .sup-ok .tk{font-family:'Sora',sans-serif;font-weight:700;color:var(--brand-2);background:var(--brand-soft);
    padding:4px 12px;border-radius:100px;display:inline-block;margin-top:10px}
  `;
  document.head.appendChild(el);
})();

const SUP_FAQS = [
  { q: 'هزینهٔ خدمات سنجاب چقدر است؟', a: 'هزینه‌ها بسته به نوع خدمت متفاوت است؛ خدمات پنل کاربری به‌صورت «سکه‌ای» محاسبه می‌شوند و قیمت هر سکه و هر سرویس در پنل وبکستینگ تعیین شده است. برای پروژه‌های سفارشی، فرم مشاورهٔ رایگان را پر کنید تا کارشناسان قیمت دقیق بدهند.' },
  { q: 'چطور سکه شارژ کنم؟', a: 'وارد داشبورد کاربری شوید و از بخش «کیف پول» یکی از پکیج‌های شارژ را انتخاب کنید. پرداخت از طریق درگاه بانکی یا کیف پول وبکستینگ انجام می‌شود.' },
  { q: 'تبلیغ من کجای سایت نمایش داده می‌شود؟', a: 'در فرم سفارش تبلیغ می‌توانید روی نقشهٔ سایت، منطقهٔ نمایش (هدر، فوتر، شناور، میانه یا پاپ‌آپ) و موضوع تبلیغ را خودتان انتخاب کنید.' },
  { q: 'تسویهٔ درآمد یوتیوب چگونه است؟', a: 'به‌دلیل محدودیت بانکی، درآمد AdSense شما توسط سنجاب دریافت و پس از کسر ۳۰٪ کارمزد، به‌صورت ریالی به حساب ایرانی شما واریز می‌شود.' },
  { q: 'AIStudio چه کارهایی انجام می‌دهد؟', a: 'موشن‌گرافیک، تولید ویدیو و تصویر، نریشن و صداگذاری، کپی‌رایتینگ و زیرنویس خودکار — همگی با هوش مصنوعی و به‌صورت سکه‌ای.' }
];

let _supOpen = null;

function SupportPanel({ onClose }) {
  const [tab, setTab] = React.useState('chat'); // chat | ticket
  const [msgs, setMsgs] = React.useState([
    { who: 'bot', text: 'سلام! من دستیار هوشمند سنجاب هستم 🌰 یکی از سؤال‌های پرتکرار را انتخاب کنید یا سؤال‌تان را بنویسید.' }
  ]);
  const [input, setInput] = React.useState('');
  const bodyRef = React.useRef(null);
  React.useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [msgs]);

  const ask = (faq) => {
    setMsgs(m => [...m, { who: 'me', text: faq.q }]);
    setTimeout(() => setMsgs(m => [...m, { who: 'bot', text: faq.a }]), 450);
  };
  const send = () => {
    const t = input.trim(); if (!t) return;
    setMsgs(m => [...m, { who: 'me', text: t }]); setInput('');
    const hit = SUP_FAQS.find(f => t.length > 2 && (f.q.includes(t) || t.includes(f.q.slice(0,6))));
    setTimeout(() => setMsgs(m => [...m, { who: 'bot',
      text: hit ? hit.a : 'سؤال شما را دریافت کردم. اگر پاسخ سریع نخواستید، می‌توانید از تب «ثبت تیکت» درخواست‌تان را برای کارشناسان ثبت کنید تا پیگیری شود.' }]), 500);
  };

  return (
    <div className="sup-panel" role="dialog" aria-modal="true">
      <div className="sup-head">
        <span className="av"><SUPIcon name="acorn" /></span>
        <div><b>پشتیبانی سنجاب</b><small>آنلاین — پاسخ آنی با AI</small></div>
        <button className="x" onClick={onClose} aria-label="بستن"><SUPIcon name="menu" /></button>
      </div>
      <div className="sup-tabs">
        <button className={tab==='chat'?'on':''} onClick={()=>setTab('chat')}><SUPIcon name="chat" /> گفتگو</button>
        <button className={tab==='ticket'?'on':''} onClick={()=>setTab('ticket')}><SUPIcon name="pen" /> ثبت تیکت</button>
      </div>
      {tab === 'chat' ? (
        <>
          <div className="sup-body" ref={bodyRef}>
            {msgs.map((m, i) => (
              <div className={'sup-msg ' + (m.who==='bot'?'bot':'me')} key={i}>
                {m.who==='bot' && <span className="mav"><SUPIcon name="acorn" /></span>}
                <div className="b">{m.text}</div>
              </div>
            ))}
            <div className="sup-ai-tag"><SUPIcon name="spark" /> سؤال‌های پرتکرار</div>
            <div className="sup-faqs">
              {SUP_FAQS.map((f, i) => (
                <button className="sup-faq" key={i} onClick={()=>ask(f)}><SUPIcon name="bulb" />{f.q}</button>
              ))}
            </div>
          </div>
          <div className="sup-foot">
            <div className="sup-input">
              <input value={input} onChange={e=>setInput(e.target.value)} onKeyDown={e=>{if(e.key==='Enter')send();}} placeholder="سؤال‌تان را بنویسید…" />
              <button className="sup-send" onClick={send} aria-label="ارسال"><SUPIcon name="arrow" /></button>
            </div>
            <div className="sup-escalate">پاسخ نگرفتید؟ <a onClick={()=>setTab('ticket')}>ثبت تیکت برای کارشناس</a></div>
          </div>
        </>
      ) : <TicketForm />}
    </div>
  );
}

function TicketForm() {
  const [sent, setSent] = React.useState(false);
  const ticketNo = React.useMemo(() => 'SJ-' + Math.floor(10000 + Math.random()*89999), []);
  if (sent) {
    return (
      <div className="sup-body">
        <div className="sup-ok">
          <div className="ic-ok"><SUPIcon name="check" /></div>
          <h4>تیکت شما ثبت شد</h4>
          <p>کارشناسان پشتیبانی سنجاب در اولین فرصت پاسخ می‌دهند. پیگیری از طریق ایمیل و داشبورد کاربری امکان‌پذیر است.</p>
          <span className="tk">شمارهٔ تیکت: {ticketNo}</span>
        </div>
      </div>
    );
  }
  return (
    <div className="sup-body">
      <div className="sup-field"><label>موضوع</label>
        <select><option>سؤال دربارهٔ خدمات</option><option>مشکل پرداخت / سکه</option><option>سفارش تبلیغ</option><option>کسب درآمد یوتیوب</option><option>AIStudio</option><option>سایر</option></select></div>
      <div className="sup-field"><label>ایمیل</label><input dir="ltr" placeholder="you@example.com" /></div>
      <div className="sup-field"><label>اولویت</label>
        <select><option>عادی</option><option>مهم</option><option>فوری</option></select></div>
      <div className="sup-field"><label>شرح درخواست</label><textarea placeholder="موضوع را کوتاه توضیح دهید…"></textarea></div>
      <SUPButton block icon="arrow" onClick={()=>setSent(true)}>ثبت تیکت</SUPButton>
    </div>
  );
}

function SupportRoot() {
  const [open, setOpen] = React.useState(false);
  if (window.useLang) window.useLang();
  const tt = (s) => (window.SJ_T ? window.SJ_T.t(s) : s);
  React.useEffect(() => { _supOpen = setOpen; return () => { _supOpen = null; }; }, []);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  return (
    <React.Fragment>
      {open
        ? <SupportPanel onClose={()=>setOpen(false)} />
        : <button className="sup-fab" onClick={()=>setOpen(true)} aria-label="پشتیبانی و چت">
            <span style={{position:'relative',display:'grid',placeItems:'center'}}><SUPIcon name="chat" /><span className="sup-dot"></span></span>
            <span className="sup-fab-txt">{tt('پشتیبانی آنلاین')}</span>
          </button>}
    </React.Fragment>
  );
}

window.SJ_SUPPORT = { open: () => _supOpen && _supOpen(true) };
Object.assign(window, { SupportRoot });
