/* wegopaars site — root app: holds state, composes all sections. */
(function () {
  const DS = window.WegopaarsDesignSystem_3b7565;
  const { Button, Badge, Card, SectionHeading, Toast } = DS;
  const WGP = window.WGP;
  const { ico } = WGP;

  function ExecutorSection({ lang }) {
    const fa = lang === 'fa';
    const pRules = fa ? ['پرداخت بیعانه برای تورهای پولی الزامی و تضمین رزرو است.','تا ۷۲ ساعت پیش از تور، بیعانه قابل بازگشت است.','رعایت برنامهٔ اعلام‌شدهٔ مجری ضروری است.'] : ['A deposit is required for paid tours and secures your booking.','The deposit is refundable up to 72 hours before the tour.','Following the operator’s schedule is required.'];
    const xRules = fa ? ['داشتن مجوز قانونی گردشگری و کارت راهنما الزامی است.','بیمهٔ مسئولیت مسافر برای هر تور باید فعال باشد.','تور تا تأیید مدارک توسط ادمین منتشر نمی‌شود.'] : ['A valid tourism permit and guide card are mandatory.','Passenger liability insurance must be active.','A tour is not published until documents are approved.'];
    const ruleCard = (tone, icon, title, rules) => (
      <Card pad="16px 18px">
        <div style={{ display:'flex', alignItems:'center', gap:9, fontWeight:800, fontSize:'14.5px', marginBottom:10 }}>
          <span style={{ width:30, height:30, borderRadius:9, background:`color-mix(in srgb,${tone} 15%,transparent)`, display:'grid', placeItems:'center', color:tone }}>{icon}</span>{title}
        </div>
        <ul style={{ margin:0, paddingInlineStart:18, color:'var(--t2)', fontSize:'13.5px', lineHeight:2 }}>{rules.map((r,i)=><li key={i}>{r}</li>)}</ul>
      </Card>
    );
    return (
      <section id="executor" style={{ position:'relative', zIndex:1, background:'var(--bg-2)', borderBlock:'1px solid var(--line)' }}>
        <div style={{ maxWidth:'var(--maxw)', margin:'0 auto', padding:'54px 22px', display:'grid', gridTemplateColumns:'1fr 1fr', gap:30, alignItems:'start' }}>
          <div>
            <SectionHeading align="start" tagColor="var(--saffron)" tag={fa ? 'مشارکت در تور' : 'Join a tour'} title={fa ? 'مجری تور شوید' : 'Become a tour operator'} subtitle={fa ? 'اگر مجوز و تجربهٔ اجرای تور دارید، می‌توانید تور خودتان را در ایران‌گرد منتشر کنید.' : 'If you hold a permit and have experience, you can publish your own tour on wegopaars.'} />
            <div style={{ display:'flex', flexDirection:'column', gap:14, marginTop:20 }}>
              {ruleCard('var(--acc)', ico(['M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2','M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8'], 1.9, 16), fa ? 'قوانین شرکت‌کننده' : 'Participant rules', pRules)}
              {ruleCard('var(--saffron)', ico(['M9 12l2 2 4-4','M21 12c0 5-3.5 7.5-8.5 9C7.5 19.5 4 17 4 12V6l8-3 8 3v6z'], 1.9, 16), fa ? 'قوانین مجری' : 'Operator rules', xRules)}
            </div>
          </div>
          <Card gradient pad="26px" style={{ position:'sticky', top:90, borderRadius:'var(--r-lg)', boxShadow:'var(--shadow-lg)' }}>
            <div style={{ width:54, height:54, borderRadius:15, background:'var(--grad-brand)', display:'grid', placeItems:'center', marginBottom:16, color:'#fff' }}>{ico(['M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2','M8 2h8v4H8z','M9 12l2 2 4-4'], 1.8, 28)}</div>
            <h3 style={{ fontSize:20, fontWeight:900, margin:'0 0 8px' }}>{fa ? 'تور خودت را اجرا کن' : 'Run your own tour'}</h3>
            <p style={{ color:'var(--t2)', fontSize:'13.5px', lineHeight:1.85, margin:'0 0 18px' }}>{fa ? 'پروفایلت را به مجری ارتقا بده، مدارک را بارگذاری کن و پس از تأیید ادمین تورت را منتشر کن.' : 'Upgrade to operator, upload documents, and publish after admin approval.'}</p>
            <div style={{ display:'flex', alignItems:'flex-start', gap:11, padding:'13px 15px', borderRadius:'var(--r-sm)', background:'color-mix(in srgb,var(--saffron) 13%,transparent)', border:'1px solid color-mix(in srgb,var(--saffron) 32%,transparent)', marginBottom:18 }}>
              <span style={{ color:'var(--saffron)', flex:'none' }}>{ico(['M12 9v4M12 17h.01','M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z'], 1.9, 20)}</span>
              <div style={{ fontSize:'12.5px', color:'var(--t1)', lineHeight:1.7 }}>{fa ? 'تا تأیید مدارک و مجوزها توسط ادمین، تورِ شما منتشر و فعال نمی‌شود.' : 'Until your documents are approved by an admin, your tour stays unpublished.'}</div>
            </div>
            <Button variant="brand" fullWidth>{fa ? 'ثبت‌نام به‌عنوان مجری' : 'Apply as an operator'}</Button>
          </Card>
        </div>
      </section>
    );
  }

  function Site() {
    const D = window.WGP_DATA;
    const [lang, setLang] = React.useState('fa');
    // تمِ محلیِ React با ماندگاری در localStorage (هم‌کلیدِ wc_theme با no-flash و صفحاتِ login/profile)
    const [theme, setTheme] = React.useState(function () { try { return localStorage.getItem('wc_theme') || 'dark'; } catch (e) { return 'dark'; } });
    const [cityId, setCityId] = React.useState(null);
    const [filter, setFilter] = React.useState('all');
    const [regId, setRegId] = React.useState(null);
    const [toast, setToast] = React.useState(null);
    const [visitor, setVisitor] = React.useState(null);
    const [liveTours, setLiveTours] = React.useState(null); // تورهای واقعیِ منتشرشده از پنل (اگر باشند)
    const tRef = React.useRef();
    const fa = lang === 'fa';
    const dir = fa ? 'rtl' : 'ltr';
    const brand = D.T[lang].brand;
    const content = (D.content || {})[lang] || {};

    React.useEffect(() => {
      document.documentElement.setAttribute('dir', dir);
      document.documentElement.setAttribute('data-theme', theme);
      try { localStorage.setItem('wc_theme', theme); } catch (e) {}
    }, [dir, theme]);

    // وضعیتِ ورودِ بازدیدکننده از ماژولِ مرکزیِ wc-auth (برای نمایشِ «حسابِ من» در ناوبری)
    React.useEffect(() => {
      if (window.WCAuth && window.WCAuth.onChange) window.WCAuth.onChange(setVisitor);
    }, []);

    // تورهای واقعیِ منتشرشده را از اندپوینتِ عمومیِ tourism بگیر و به شکلِ کارت map کن.
    // اگر چیزی نبود یا خطا داد، کاتالوگِ استاتیکِ طراحی (D.TOURS) دست‌نخورده می‌ماند
    // تا سایت هرگز سفید/خالی نشود. فقط بخشِ «تورها» زنده می‌شود؛ نقشه/مقصدها/صنایع همان طراحی.
    React.useEffect(() => {
      const api = (window.WCAuth && window.WCAuth.apiBase && window.WCAuth.apiBase()) || '/api/v1';
      let tries = 0;
      const attempt = () => {
        const sid = window.WCAuth && window.WCAuth.siteId && window.WCAuth.siteId();
        if (!sid) { if (tries++ < 12) setTimeout(attempt, 500); return; }
        fetch(api + '/sites/' + sid + '/public/tours', { cache: 'no-store' })
          .then((r) => (r.ok ? r.json() : []))
          .then((list) => {
            if (!Array.isArray(list) || !list.length) return;
            setLiveTours(list.map((t) => {
              const price = parseInt(String(t.price || '0').replace(/[^\d]/g, ''), 10) || 0;
              const filled = (t._count && t._count.bookings) || 0;
              const dur = t.durationDays ? Number(t.durationDays) : 0;
              return {
                id: t.id, apiId: t.id,
                titleFa: t.title, titleEn: t.title,
                cityFa: t.destination || '', cityEn: t.destination || '',
                dateFa: t.startDate || '', dateEn: t.startDate || '',
                durFa: dur ? dur + ' روز' : '', durEn: dur ? dur + ' days' : '',
                season: price === 0 ? 'spring' : 'event',
                price: price, depositPct: 30,
                capacity: t.capacity || 0, filled: filled,
                execFa: '', execEn: '',
              };
            }));
          })
          .catch(() => {});
      };
      attempt();
    }, []);
    const goAccount = () => { window.location.href = visitor ? '/custom/wegopars/profile.html' : '/custom/wegopars/login.html'; };

    const flash = (msg) => { setToast(msg); clearTimeout(tRef.current); tRef.current = setTimeout(() => setToast(null), 2800); };

    const crafts = [];
    D.CITIES.forEach(c => { const t = c[lang]; c.handicrafts.forEach(h => { const hl = h[lang]; crafts.push({ name:hl.name, souvenir:hl.souvenir, basalam:h.basalam, cityName:t.name, initial:hl.name.charAt(0), tint:c.color }); }); });
    crafts.sort((a, b) => (b.basalam ? 1 : 0) - (a.basalam ? 1 : 0));

    const city = D.CITIES.find(c => c.id === cityId) || null;
    // کاتالوگِ نمایش: تورهای زنده اگر باشند، وگرنه طراحیِ استاتیک
    const toursShown = (liveTours && liveTours.length) ? liveTours : D.TOURS;
    const regTour = toursShown.find(t => t.id === regId) || null;

    // ثبتِ واقعیِ رزرو روی اندپوینتِ عمومیِ tourism (اگر تور apiId داشته باشد).
    // اگر تورِ استاتیکِ دمو بود (بدونِ apiId) به رفتارِ محلی برمی‌گردد تا خطا ندهد.
    const bookTour = (t, fields) => {
      const api = (window.WCAuth && window.WCAuth.apiBase && window.WCAuth.apiBase()) || '/api/v1';
      const sid = window.WCAuth && window.WCAuth.siteId && window.WCAuth.siteId();
      if (!t.apiId || !sid) {
        // دموِ استاتیک — بدونِ بک‌اند
        return Promise.resolve({ message: fa ? 'درخواستِ شما ثبت شد (نمایشی).' : 'Your request was recorded (demo).' });
      }
      const token = window.WCAuth && window.WCAuth.token && window.WCAuth.token();
      const headers = { 'Content-Type': 'application/json' };
      if (token) headers.Authorization = 'Bearer ' + token;
      return fetch(api + '/sites/' + sid + '/public/tours/' + t.apiId + '/book', {
        method: 'POST', headers: headers,
        body: JSON.stringify({ name: fields.name, phone: fields.phone, people: fields.people, note: fields.note }),
      })
        .then((r) => r.json().then((j) => ({ ok: r.ok, j: j })))
        .then((res) => { if (!res.ok) throw new Error((res.j && res.j.message) || (fa ? 'ثبتِ رزرو ناموفق بود' : 'Booking failed')); return res.j; });
    };

    // پس از ثبتِ موفق: ظرفیتِ محلی را به‌روز و پیامِ کوتاه نشان بده
    const onBooked = (t, ppl) => {
      const ref = toursShown.find(x => x.id === t.id);
      if (ref && (ref.filled + ppl) <= ref.capacity) ref.filled += ppl;
      flash(fa ? 'رزروِ شما با موفقیت ثبت شد.' : 'Your booking was registered.');
    };

    return (
      <div dir={dir} data-theme={theme} style={{ minHeight:'100vh', background:'var(--bg)', color:'var(--t1)', position:'relative', overflowX:'hidden' }}>
        <div style={{ position:'fixed', inset:0, pointerEvents:'none', zIndex:0, background:'radial-gradient(60% 50% at 80% 0%,rgba(31,157,87,.12),transparent 60%),radial-gradient(50% 40% at 10% 20%,rgba(232,163,61,.08),transparent 60%)' }} />
        <WGP.Nav lang={lang} theme={theme} brand={brand} visitor={visitor} onAccount={goAccount} onLang={() => setLang(fa ? 'en' : 'fa')} onTheme={() => setTheme(theme === 'dark' ? 'light' : 'dark')} onAdmin={() => { window.location.href = '../admin/index.html'; }} />
        <WGP.Hero lang={lang} content={content} />
        <WGP.MapSection lang={lang} cities={D.CITIES} onOpen={setCityId} />
        <WGP.DestSection lang={lang} cities={D.CITIES} onOpen={setCityId} />
        <WGP.Crafts lang={lang} crafts={crafts.slice(0, 6)} />
        <WGP.ToursSection lang={lang} tours={toursShown} filter={filter} onFilter={setFilter} onRegister={setRegId} />
        <ExecutorSection lang={lang} />
        <WGP.Footer lang={lang} brand={brand} content={content} />
        <WGP.CityDrawer lang={lang} city={city} onClose={() => setCityId(null)} />
        <WGP.RegModal lang={lang} tour={regTour} visitor={visitor} onClose={() => setRegId(null)} onBook={bookTour} onBooked={onBooked} />
        {toast && <Toast message={toast} />}
      </div>
    );
  }

  window.WGP.Site = Site;
})();
