/* Sanjab Studio — Auth & Consult modals (modeled on the Webcasting login, Sanjab amber).
   Self-contained: injects its own modal CSS, exposes window.SJ_AUTH.{openLogin,openConsult}. */
const { Button: SJButton, Icon: SJIcon } = window.DesignSystem_7abc08;

(function injectAuthCSS(){
  if (document.getElementById('sj-auth-css')) return;
  const el = document.createElement('style');
  el.id = 'sj-auth-css';
  el.textContent = `
  .sj-modal-scrim{position:fixed;inset:0;z-index:300;display:grid;place-items:center;padding:20px;
    background:rgba(6,9,13,.62);backdrop-filter:blur(5px);animation:sjScrim .2s ease both}
  @keyframes sjScrim{from{opacity:0}to{opacity:1}}
  .sj-modal{width:100%;max-width:440px;border-radius:var(--r-xl,26px);overflow:hidden;
    background:linear-gradient(180deg,var(--card),var(--card-2));border:1px solid var(--line-2);
    box-shadow:0 40px 90px -30px rgba(0,0,0,.8);animation:sjPop .28s var(--ease) both}
  @keyframes sjPop{from{opacity:0;transform:translateY(16px) scale(.98)}to{opacity:1;transform:none}}
  .sj-modal-head{display:flex;align-items:center;justify-content:space-between;gap:12px;
    padding:20px 22px 6px}
  .sj-modal-head .ttl{display:flex;align-items:center;gap:11px;font-weight:800;font-size:1.12rem}
  .sj-modal-head .mk{width:38px;height:38px;border-radius:11px;display:grid;place-items:center;
    background:var(--grad-mark,linear-gradient(135deg,var(--brand),var(--gold)));box-shadow:0 8px 20px -8px var(--brand)}
  .sj-modal-head .mk .ic{width:22px;height:22px;stroke:#1a1205;stroke-width:1.9}
  .sj-x{width:36px;height:36px;border-radius:10px;display:grid;place-items:center;cursor:pointer;
    background:var(--surface);border:1px solid var(--line);color:var(--t2);transition:.2s}
  .sj-x:hover{color:var(--t1);border-color:var(--line-2)}
  .sj-x .ic{width:18px;height:18px}
  .sj-modal-body{padding:14px 22px 24px}
  .sj-seg{display:grid;grid-template-columns:1fr 1fr;gap:8px;padding:5px;border-radius:15px;
    background:var(--bg-2);border:1px solid var(--line);margin-bottom:18px}
  .sj-seg button{padding:11px;border-radius:11px;border:none;background:none;cursor:pointer;font:inherit;
    font-weight:700;font-size:.92rem;color:var(--t2);transition:.2s;display:flex;align-items:center;justify-content:center;gap:7px}
  .sj-seg button .ic{width:17px;height:17px}
  .sj-seg button.on{background:var(--grad-brand,linear-gradient(135deg,var(--brand),var(--brand-deep)));color:#fff;
    box-shadow:0 10px 24px -12px var(--brand)}
  .sj-seg.soft button.on{background:var(--brand-soft);color:var(--brand-2);box-shadow:none}
  .sj-lbl{display:block;font-size:.86rem;color:var(--t2);font-weight:500;margin-bottom:7px;text-align:start}
  .sj-inp{position:relative;margin-bottom:15px}
  .sj-inp input{width:100%;padding:13px 15px;padding-inline-start:44px;background:var(--bg-2);
    border:1px solid var(--line-2);border-radius:13px;color:var(--t1);font:inherit;font-size:.95rem;transition:.2s}
  .sj-inp input::placeholder{color:var(--t3)}
  .sj-inp input:focus{outline:none;border-color:var(--brand);box-shadow:0 0 0 3px var(--brand-soft)}
  .sj-inp .ic{position:absolute;inset-block-start:50%;inset-inline-start:14px;transform:translateY(-50%);
    width:19px;height:19px;color:var(--t3);pointer-events:none}
  .sj-divider{display:flex;align-items:center;gap:12px;margin:18px 0;color:var(--t3);font-size:.8rem}
  .sj-divider::before,.sj-divider::after{content:'';flex:1;height:1px;background:var(--line)}
  .sj-terms{text-align:center;font-size:.78rem;color:var(--t3);margin-top:16px;line-height:1.7}
  .sj-terms a{color:var(--brand);text-decoration:none}
  .sj-otp{display:flex;gap:9px;direction:ltr;justify-content:center;margin:6px 0 4px}
  .sj-otp input{width:48px;height:56px;text-align:center;font-family:'Sora',sans-serif;font-size:1.3rem;font-weight:700;
    background:var(--bg-2);border:1px solid var(--line-2);border-radius:13px;color:var(--t1)}
  .sj-otp input:focus{outline:none;border-color:var(--brand);box-shadow:0 0 0 3px var(--brand-soft)}
  .sj-ok{text-align:center;padding:14px 6px 4px}
  .sj-ok .ok-ic{width:64px;height:64px;margin:0 auto 16px;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)}
  .sj-ok .ok-ic .ic{width:32px;height:32px;stroke-width:2.4}
  .sj-ok h3{font-size:1.18rem;margin-bottom:10px}
  .sj-ok p{color:var(--t2);font-size:.94rem;line-height:1.8;margin-bottom:20px}
  .sj-hint{font-size:.8rem;color:var(--t3);text-align:center;margin-top:12px}
  `;
  document.head.appendChild(el);
})();

let _open = null; // set by AuthRoot

function LoginPanel({ onClose }) {
  const [tab, setTab] = React.useState('login');     // login | signup
  const [method, setMethod] = React.useState('email'); // email | mobile
  const [step, setStep] = React.useState('form');    // form | otp | done
  const isLogin = tab === 'login';

  if (step === 'done') {
    return (
      <div className="sj-ok">
        <div className="ok-ic"><SJIcon name="check" /></div>
        <h3>{isLogin ? 'خوش آمدید 👋' : 'حساب شما ساخته شد'}</h3>
        <p>با موفقیت وارد حساب کاربری سنجاب شدید. اکنون می‌توانید سکه شارژ کنید، سفارش تبلیغ بدهید و از AIStudio استفاده کنید.</p>
        <SJButton block icon="arrow" onClick={onClose}>رفتن به داشبورد</SJButton>
      </div>
    );
  }

  if (step === 'otp') {
    return (
      <div>
        <p className="sj-lbl" style={{textAlign:'center',marginBottom:16}}>کد ۶ رقمی به {method==='email'?'ایمیل':'موبایل'} شما ارسال شد</p>
        <div className="sj-otp">
          {[0,1,2,3,4,5].map(i => (
            <input key={i} maxLength={1} inputMode="numeric"
              onChange={(e)=>{ const n=e.target.nextElementSibling||e.target.previousElementSibling; if(e.target.value&&e.target.nextElementSibling) e.target.nextElementSibling.focus(); }} />
          ))}
        </div>
        <div style={{marginTop:18}}>
          <SJButton block icon="arrow" onClick={()=>setStep('done')}>تأیید و ورود</SJButton>
        </div>
        <div className="sj-hint">کد را دریافت نکردید؟ <a href="#" onClick={(e)=>{e.preventDefault();}} style={{color:'var(--brand)'}}>ارسال مجدد (۰۰:۵۹)</a></div>
      </div>
    );
  }

  return (
    <div>
      <div className="sj-seg">
        <button className={isLogin?'on':''} onClick={()=>setTab('login')}>ورود</button>
        <button className={!isLogin?'on':''} onClick={()=>setTab('signup')}>ساخت حساب</button>
      </div>
      <div className="sj-seg soft">
        <button className={method==='email'?'on':''} onClick={()=>setMethod('email')}><SJIcon name="mail" /> ایمیل</button>
        <button className={method==='mobile'?'on':''} onClick={()=>setMethod('mobile')}><SJIcon name="phone" /> موبایل</button>
      </div>

      {!isLogin && (
        <>
          <label className="sj-lbl">نام و نام خانوادگی</label>
          <div className="sj-inp"><SJIcon name="handshake" /><input placeholder="مثلاً علی رضایی" /></div>
        </>
      )}

      <label className="sj-lbl">{method==='email'?'ایمیل':'شمارهٔ موبایل'}</label>
      <div className="sj-inp">
        <SJIcon name={method==='email'?'mail':'phone'} />
        <input dir={method==='email'?'ltr':'rtl'} placeholder={method==='email'?'you@example.com':'۰۹۱۲ ۰۰۰ ۰۰۰۰'} />
      </div>

      <label className="sj-lbl">رمز عبور</label>
      <div className="sj-inp">
        <SJIcon name="bulb" />
        <input type="password" placeholder={isLogin?'رمز عبور (اگر دارید)':'یک رمز عبور انتخاب کنید'} />
      </div>

      <SJButton block icon="arrow" onClick={()=>setStep('done')}>
        {isLogin ? 'ورود با رمز عبور' : 'ساخت حساب و ورود'}
      </SJButton>

      <div className="sj-divider">یا با کد یک‌بارمصرف</div>
      <SJButton block variant="ghost" iconLeading="bell" onClick={()=>setStep('otp')}>دریافت کد ورود</SJButton>

      <p className="sj-terms">با ادامه، <a href="#" onClick={(e)=>e.preventDefault()}>قوانین و حریم خصوصی</a> را می‌پذیرم.</p>
    </div>
  );
}

function ConsultPanel({ onClose }) {
  const [done, setDone] = React.useState(false);
  const topics = (window.SANJAB_DEFAULTS?.leadform?.services) || ['سئو','تبلیغات','یوتیوب','تولید محتوا','سایر'];
  if (done) {
    return (
      <div className="sj-ok">
        <div className="ok-ic"><SJIcon name="check" /></div>
        <h3>درخواست شما ثبت شد</h3>
        <p>سپاس از شما. کارشناسان سنجاب درخواست‌تان را بررسی می‌کنند و <b>به‌زودی</b> (کمتر از ۲۴ ساعت) با شما تماس می‌گیرند.</p>
        <SJButton block onClick={onClose}>بستن</SJButton>
      </div>
    );
  }
  return (
    <div>
      <p className="sj-lbl" style={{marginBottom:16,lineHeight:1.8}}>چند سؤال کوتاه؛ بعد از بررسی، مشاورهٔ رایگان برایتان تنظیم می‌کنیم.</p>
      <label className="sj-lbl">موضوع مشاوره</label>
      <div className="sj-inp" style={{marginBottom:15}}>
        <SJIcon name="target" />
        <select className="sj-consult-sel" style={{width:'100%',padding:'13px 15px',paddingInlineStart:44,background:'var(--bg-2)',border:'1px solid var(--line-2)',borderRadius:13,color:'var(--t1)',font:'inherit',fontSize:'.95rem',appearance:'none'}}>
          {topics.map((t,i)=><option key={i}>{t}</option>)}
        </select>
      </div>
      <label className="sj-lbl">نام شما</label>
      <div className="sj-inp"><SJIcon name="handshake" /><input placeholder="نام و نام خانوادگی" /></div>
      <label className="sj-lbl">ایمیل</label>
      <div className="sj-inp"><SJIcon name="mail" /><input dir="ltr" placeholder="you@example.com" /></div>
      <SJButton block icon="arrow" onClick={()=>setDone(true)}>ثبت درخواست مشاوره</SJButton>
      <p className="sj-terms">پاسخ‌گویی در ساعات کاری، شنبه تا چهارشنبه.</p>
    </div>
  );
}

function AuthRoot() {
  const [modal, setModal] = React.useState(null); // 'login' | 'consult' | null
  React.useEffect(() => { _open = setModal; return () => { _open = null; }; }, []);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') setModal(null); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  if (!modal) return null;
  const close = () => setModal(null);
  const title = modal === 'login' ? 'ورود به حساب' : 'مشاورهٔ رایگان';
  return (
    <div className="sj-modal-scrim" onMouseDown={(e)=>{ if(e.target===e.currentTarget) close(); }}>
      <div className="sj-modal" role="dialog" aria-modal="true">
        <div className="sj-modal-head">
          <div className="ttl"><span className="mk"><SJIcon name="acorn" /></span>{title}</div>
          <button className="sj-x" onClick={close} aria-label="بستن"><SJIcon name="menu" /></button>
        </div>
        <div className="sj-modal-body">
          {modal === 'login' ? <LoginPanel onClose={close} /> : <ConsultPanel onClose={close} />}
        </div>
      </div>
    </div>
  );
}

window.SJ_AUTH = {
  // استانداردسازی: ورود/ثبت‌نام → مودالِ واحدِ وبکستینگ (ایمیل+رمز). مشاوره همان فرمِ داخلی می‌ماند.
  openLogin:   () => (window.WCAuth && window.WCAuth.open) ? window.WCAuth.open() : (_open && _open('login')),
  openConsult: () => _open && _open('consult'),
};
Object.assign(window, { AuthRoot });
