/* ===========================================================
   راویار — App shell (نسخهٔ پروداکشن روی سایت‌سازِ وبکستینگ)
   تفاوت با نمونهٔ تعاملی: نوارِ سوییچرِ نمونه حذف شده، فقط صفحاتِ
   عمومی (خانه/داستان/مرور/اشتراک) سرو می‌شوند، و ورود/ثبت‌نام به
   ماژولِ احرازِ هویتِ مرکزیِ وبکستینگ (window.WCAuth) وصل است.
   پنلِ ادمین و استودیوی AI سطح‌های جداگانه‌اند (admin = پنلِ مستقل).
   =========================================================== */
const { useState, useEffect } = React;

/* ---- Toast (سکه/پیام) ---- */
function Toast({ msg }) {
  if (!msg) return null;
  return (
    <div className="gold-frame" style={{ position: 'fixed', bottom: 26, insetInlineStart: '50%', transform: 'translateX(50%)', zIndex: 200,
      background: 'rgba(13,24,60,.95)', borderRadius: 999, padding: '12px 22px', display: 'flex', alignItems: 'center', gap: 10,
      boxShadow: 'var(--shadow-pop)', animation: 'rise .35s ease both' }}>
      <CoinGlyph size={18} /><span style={{ fontSize: 14, fontWeight: 600 }}>{msg}</span>
    </div>
  );
}

/* ---- دکمهٔ ورود/حسابِ کاربر — متصل به wc-auth مرکزی ---- */
function AuthControl({ go }) {
  const [user, setUser] = useState(window.WCAuth ? window.WCAuth.user() : null);
  useEffect(() => { if (window.WCAuth) window.WCAuth.onChange(setUser); }, []);
  const open = () => { if (window.WCAuth) window.WCAuth.open(); };
  if (user) {
    const label = (user.name || user.fullName || user.mobile || user.email || 'کاربر') + '';
    return (
      <button onClick={open} title={label} aria-label="حساب کاربری"
        style={{ width: 38, height: 38, borderRadius: 999, background: 'linear-gradient(135deg,var(--turq-400),var(--lapis-500))',
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, color: '#04201d' }}>
        {label.trim().charAt(0) || 'ر'}
      </button>
    );
  }
  return (
    <button className="btn btn-gold" onClick={open} data-wc-auth style={{ padding: '9px 18px', fontSize: 14, fontWeight: 700 }}>
      <Icon name="users" size={15} /> {L('ورود / ثبت‌نام', 'Sign in')}
    </button>
  );
}

/* ---- هدرِ سایتِ عمومی ---- */
function SiteHeader({ go, screen, coins }) {
  const nav = [
    { id: 'home', fa: 'خانه', en: 'Home' },
    { id: 'browse', fa: 'مرور اسطوره‌ها', en: 'Browse myths' },
    { id: 'pricing', fa: 'اشتراک', en: 'Plans' },
    { id: 'home', fa: 'شاعران', en: 'Poets', key: 'poets' },
  ];
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 70, padding: '14px 0',
      background: 'linear-gradient(180deg, rgba(10,18,48,.92), rgba(10,18,48,.55) 70%, transparent)',
      backdropFilter: 'blur(10px)' }}>
      <div style={{ maxWidth: 'var(--maxw)', margin: '0 auto', padding: '0 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20 }}>
        <div className="row gap-4" style={{ alignItems: 'center' }}>
          <button onClick={() => go('home')} aria-label="راویار" style={{ display: 'flex' }}><Logo size={30} /></button>
          <nav className="row gap-3" style={{ fontSize: 15 }}>
            {nav.map((n, i) => (
              <button key={i} onClick={() => go(n.id)}
                style={{ color: screen === n.id && !n.key ? 'var(--gold-400)' : 'var(--cream-2)', fontWeight: 600, opacity: .92 }}>
                {OMID.TX(n)}
              </button>
            ))}
          </nav>
        </div>
        <div className="row gap-2" style={{ alignItems: 'center' }}>
          <button onClick={() => go('browse')} className="row gap-2"
            style={{ background: 'rgba(231,222,201,.06)', border: '1px solid var(--hairline)',
              borderRadius: 999, padding: '8px 15px', width: 280, color: 'var(--muted)', textAlign: 'start' }}>
            <Icon name="search" size={16} />
            <span style={{ fontSize: 13.5 }}>{L('جستجوی داستان، اسطوره، شاعر…', 'Search stories, poets, myths…')}</span>
          </button>
          <CoinPill value={coins} size="sm" onClick={() => go('pricing')} />
          <NotificationBell go={go} />
          <AuthControl go={go} />
        </div>
      </div>
    </header>
  );
}

/* ---- فوتر ---- */
function SiteFooter() {
  const cols = [
    { h: 'کاوش', hEn: 'Explore', items: ['اسطوره‌ها', 'حماسه‌ها', 'عاشقانه‌ها', 'شاعران', 'مناسبت‌ها'], itemsEn: ['Myths', 'Epics', 'Romances', 'Poets', 'Occasions'] },
    { h: 'پشتیبانی', hEn: 'Support', items: ['مرکز کمک', 'ارتباط با ما', 'سؤالات متداول', 'گزارش محتوا'], itemsEn: ['Help center', 'Contact us', 'FAQ', 'Report content'] },
    { h: 'قوانین', hEn: 'Legal', items: ['قوانین استفاده', 'حریم خصوصی', 'حق مؤلف', 'همکاری'], itemsEn: ['Terms of use', 'Privacy', 'Copyright', 'Partnership'] },
  ];
  return (
    <footer style={{ borderTop: '1px solid var(--hairline)', marginTop: 50, padding: '46px 0 40px', position: 'relative', zIndex: 2 }}>
      <div style={{ maxWidth: 'var(--maxw)', margin: '0 auto', padding: '0 22px', display: 'grid', gridTemplateColumns: '1.5fr 1fr 1fr 1fr', gap: 30 }}>
        <div>
          <Logo size={28} />
          <p className="muted" style={{ fontSize: 13.5, lineHeight: 2, marginTop: 14, maxWidth: 280 }}>
            {L('روایتِ اسطوره‌ها و داستان‌های کهن ایرانی با تصویرگری هوش مصنوعی؛ هنر، نگارگری و قصه در یک قاب.', 'Retelling ancient Persian myths and tales with AI illustration — art, illumination and story in one frame.')}
          </p>
          <div style={{ marginTop: 18 }}><SocialRow size={36} /></div>
        </div>
        {cols.map((c, i) => (
          <div key={i}>
            <div style={{ fontWeight: 700, marginBottom: 14, fontSize: 14.5 }}>{OMID.TX(c, 'h')}</div>
            <div className="col gap-2">
              {(OMID.getLang() === 'en' ? c.itemsEn : c.items).map((it, j) => <button key={j} className="muted" style={{ fontSize: 13.5, textAlign: 'start', width: 'fit-content' }}>{it}</button>)}
            </div>
          </div>
        ))}
      </div>
      <div style={{ maxWidth: 'var(--maxw)', margin: '26px auto 0', padding: '20px 22px 0', borderTop: '1px solid var(--hairline)',
        display: 'flex', justifyContent: 'space-between', color: 'var(--muted-2)', fontSize: 12.5 }}>
        <span>{L('© ۱۴۰۴ راویار — تمام حقوق محفوظ است.', '© 2025 Ravyar — All rights reserved.')}</span>
        <span>{L('ساخته‌شده با ❤ برای فرهنگ ایران', 'Made with ❤ for Persian culture')}</span>
      </div>
    </footer>
  );
}

/* ---- زبان: دکمهٔ شناورِ تغییر زبان (جایگزینِ سوییچرِ نمونه) ---- */
function LangToggle({ lang, setLang }) {
  return (
    <button className="chip" onClick={() => setLang(lang === 'fa' ? 'en' : 'fa')}
      style={{ position: 'fixed', top: 16, insetInlineStart: 16, zIndex: 95, padding: '7px 12px',
        background: 'rgba(7,11,28,.86)', backdropFilter: 'blur(14px)', border: '1px solid rgba(212,169,76,.18)' }}>
      <Icon name="globe" size={14} /> {lang === 'fa' ? 'EN' : 'فا'}
    </button>
  );
}

/* ---- App ---- */
function App() {
  const [screen, setScreen] = useState('home');
  const [lang, setLangState] = useState('fa');
  const setLang = (l) => { OMID.setLang(l); setLangState(l); };
  const [story, setStory] = useState(OMID.byId('siavash'));
  const [coins, setCoins] = useState(OMID.WALLET.balance);
  const [toast, setToast] = useState(null);
  const tRef = React.useRef(null);
  const showToast = (msg) => { setToast(msg); clearTimeout(tRef.current); tRef.current = setTimeout(() => setToast(null), 2600); };

  useEffect(() => { window.scrollTo(0, 0); }, [screen]);

  const go = (s) => setScreen(s);
  const openStory = (st) => { setStory(st); setScreen('story'); };
  const earn = (n, why) => { setCoins(c => c + n); showToast(L(`${OMID.numFa(n)} سکه برای ${why} افزوده شد`, `${n} coins added for ${why}`)); };

  return (
    <div className="app-frame">
      <LangToggle lang={lang} setLang={setLang} />
      <div className="canvas-bg" />
      <div style={{ position: 'relative', zIndex: 2 }}>
        <SiteHeader go={go} screen={screen} coins={coins} />
        <main key={screen}>
          {screen === 'home'    && <HomeScreen openStory={openStory} go={go} />}
          {screen === 'story'   && <StoryScreen story={story} openStory={openStory} go={go} coins={coins} earn={earn} />}
          {screen === 'browse'  && <BrowseScreen openStory={openStory} />}
          {screen === 'pricing' && <PricingScreen coins={coins} setCoins={setCoins} toast={showToast} />}
        </main>
        <SiteFooter />
      </div>
      {/* FABِ پشتیبانی حالا ماژولِ مرکزیِ وبکستینگ است (wc-support.js) — بومی حذف شد تا تکراری نباشد */}
      <Toast msg={toast} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
