/* wegopaars site — tours: seasonal-tour grid with filter + registration modal. */
(function () {
  const DS = window.WegopaarsDesignSystem_3b7565;
  const { Card, Badge, Button, FilterChip, ProgressBar, Avatar, SectionHeading, Input } = DS;
  const WGP = (window.WGP = window.WGP || {});
  const { fmt, ico } = WGP;

  const SEASON_COLOR = { spring:'#3fae6a', summer:'#e8a33d', autumn:'#c2603e', winter:'#2aa7c4', event:'#9b6cc2' };

  WGP.ToursSection = function ToursSection({ lang, tours, filter, onFilter, onRegister }) {
    const fa = lang === 'fa';
    const T = window.WGP_DATA.T[lang];
    const FILTERS = ['all','spring','summer','autumn','winter','event','free'];
    const shown = tours.filter(t => filter === 'all' ? true : filter === 'free' ? t.price === 0 : t.season === filter);
    return (
      <section id="tours" style={{ position:'relative', zIndex:1, maxWidth:'var(--maxw)', margin:'0 auto', padding:'50px 22px' }}>
        <SectionHeading tag={fa ? 'تورهای فصلی و مناسبتی' : 'Seasonal & special tours'} title={fa ? 'تور بعدی‌ات را رزرو کن' : 'Book your next tour'} subtitle={fa ? 'تورهای پولی با پرداخت بخشی از هزینه (بیعانه) و تورهای رایگان با ثبت‌نام ساده.' : 'Paid tours with a partial deposit, and free tours with simple registration.'} />
        <div style={{ display:'flex', gap:8, justifyContent:'center', flexWrap:'wrap', margin:'22px 0 26px' }}>
          {FILTERS.map(id => <FilterChip key={id} active={id === filter} onClick={() => onFilter(id)}>{T['flt_' + id]}</FilterChip>)}
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:18 }}>
          {shown.map(t => {
            const isFree = t.price === 0;
            const color = isFree ? '#3fae6a' : SEASON_COLOR[t.season];
            const exec = fa ? t.execFa : t.execEn;
            const pct = Math.round(t.filled / t.capacity * 100);
            return (
              <Card key={t.id} pad={0} style={{ overflow:'hidden', display:'flex', flexDirection:'column' }}>
                <div style={{ position:'relative' }}>
                  <image-slot id={'wg-tour-' + t.id} shape="rect" fit="cover" placeholder={fa ? t.titleFa : t.titleEn} style={{ display:'block', width:'100%', height:150 }}></image-slot>
                  <span style={{ position:'absolute', top:11, insetInlineStart:11 }}><Badge tone={color} variant="solid">{isFree ? T.flt_free : T['se_' + t.season]}</Badge></span>
                  {isFree && <span style={{ position:'absolute', top:11, insetInlineEnd:11 }}><Badge tone="green" variant="solid">{fa ? 'رایگان' : 'Free'}</Badge></span>}
                </div>
                <div style={{ padding:'15px 16px', display:'flex', flexDirection:'column', flex:1 }}>
                  <div style={{ fontWeight:800, fontSize:16, lineHeight:1.5 }}>{fa ? t.titleFa : t.titleEn}</div>
                  <div style={{ display:'flex', alignItems:'center', gap:12, marginTop:9, fontSize:12, color:'var(--t3)' }}>
                    <span style={{ display:'inline-flex', alignItems:'center', gap:5 }}>{ico(['M12 21s-7-5.2-7-11a7 7 0 0 1 14 0c0 5.8-7 11-7 11z','M12 10a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z'], 1.8, 14)}{fa ? t.cityFa : t.cityEn}</span>
                    <span style={{ display:'inline-flex', alignItems:'center', gap:5 }}>{ico(['M3 4h18v18H3z','M3 10h18M8 2v4M16 2v4'], 1.8, 14)}{fa ? t.dateFa : t.dateEn}</span>
                    <span>{fa ? t.durFa : t.durEn}</span>
                  </div>
                  <div style={{ marginTop:13 }}>
                    <div style={{ display:'flex', justifyContent:'space-between', fontSize:'11.5px', color:'var(--t3)', marginBottom:5 }}><span>{fa ? 'ظرفیت' : 'Seats'}</span><span>{fmt(t.filled, lang)} / {fmt(t.capacity, lang)}</span></div>
                    <ProgressBar value={pct} color={color} />
                  </div>
                  <div style={{ display:'flex', alignItems:'center', gap:7, marginTop:13, fontSize:12, color:'var(--t2)' }}>
                    <Avatar initial={exec ? exec.charAt(0) : ''} size={22} />{exec}
                    <Badge tone="green" style={{ marginInlineStart:'auto' }} icon={ico(['M5 13l4 4L19 7'], 2.4, 11)}>{fa ? 'تأییدشده' : 'Verified'}</Badge>
                  </div>
                  <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop:15, paddingTop:14, borderTop:'1px solid var(--line)' }}>
                    <div>
                      <div style={{ fontSize:'10.5px', color:'var(--t3)' }}>{isFree ? (fa ? 'ثبت‌نام آزاد' : 'Open registration') : (fa ? 'هر نفر' : 'per person')}</div>
                      <div style={{ fontWeight:900, fontSize:16, color:'var(--t1)' }}>{isFree ? (fa ? 'رایگان' : 'Free') : fmt(t.price, lang) + ' ' + T.toman}</div>
                    </div>
                    <Button variant="brand" size="sm" onClick={() => onRegister(t.id)}>{fa ? 'ثبت‌نام' : 'Register'}</Button>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      </section>
    );
  };

  /* RegModal — سفرِ رزروِ تور، منطبق بر مدلِ خودِ سایت (Tour/TourBooking).
     مرحله‌ها: فرم (پیش‌پرشده از visitor-auth اگر واردشده) → ثبتِ رزرو روی
     اندپوینتِ واقعیِ POST /sites/:id/public/tours/:tourId/book → صفحهٔ تکمیل.
     نکته: اندپوینتِ پرداختِ آنلاینِ بیعانه هنوز وجود ندارد (backendGap) — برای
     تورِ پولی، رزرو به‌صورتِ «درخواستِ رزرو» ثبت و پیامِ هماهنگیِ بیعانه نمایش
     داده می‌شود. اگر tour.apiId نداشته باشد (کاتالوگِ استاتیکِ دمو) به رفتارِ
     محلیِ قبلی برمی‌گردد تا هرگز خطا ندهد. */
  WGP.RegModal = function RegModal({ lang, tour, visitor, onClose, onBook, onBooked }) {
    const fa = lang === 'fa';
    const T = window.WGP_DATA.T[lang];
    const [name, setName] = React.useState('');
    const [phone, setPhone] = React.useState('');
    const [people, setPeople] = React.useState(1);
    const [note, setNote] = React.useState('');
    const [busy, setBusy] = React.useState(false);
    const [err, setErr] = React.useState('');
    const [done, setDone] = React.useState(null); // {message, deposit, tracking}

    // پیش‌پرکردن از حسابِ واردشده هر بار که مودال برای یک تورِ جدید باز می‌شود
    React.useEffect(() => {
      if (!tour) return;
      setName((visitor && visitor.name) || '');
      setPhone((visitor && visitor.phone) || '');
      setPeople(1); setNote(''); setErr(''); setDone(null); setBusy(false);
    }, [tour && tour.id]);

    if (!tour) return null;
    const isFree = tour.price === 0;
    const deposit = Math.round((tour.price || 0) * (tour.depositPct || 0) / 100);
    const seats = Math.max(0, (tour.capacity || 0) - (tour.filled || 0));

    const submit = () => {
      setErr('');
      if (!name.trim()) { setErr(fa ? 'نام و نام خانوادگی را وارد کنید.' : 'Please enter your full name.'); return; }
      const ppl = Math.max(1, Number(people) || 1);
      setBusy(true);
      Promise.resolve(onBook(tour, { name: name.trim(), phone: phone.trim(), people: ppl, note: note.trim() }))
        .then((res) => {
          setBusy(false);
          if (onBooked) onBooked(tour, ppl);
          setDone({ message: (res && res.message) || (fa ? 'رزرو شما ثبت شد' : 'Your booking is registered'), deposit: !isFree ? deposit : 0 });
        })
        .catch((e) => { setBusy(false); setErr((e && e.message) || (fa ? 'خطا در ثبتِ رزرو؛ دوباره تلاش کنید.' : 'Booking failed; please try again.')); });
    };

    const loggedIn = !!visitor;

    return (
      <div onClick={onClose} style={{ position:'fixed', inset:0, zIndex:95, background:'rgba(4,12,14,.6)', backdropFilter:'blur(4px)', display:'grid', placeItems:'center', padding:20 }}>
        <div onClick={(e) => e.stopPropagation()} style={{ width:'min(460px,96vw)', background:'var(--bg)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', boxShadow:'var(--shadow-lg)', overflow:'hidden', animation:'pop .35s var(--spring)' }}>
          <div style={{ padding:'20px 22px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:12 }}>
            <div>
              <div style={{ fontSize:'11.5px', fontWeight:800, color:'var(--acc)' }}>{done ? (fa ? 'رزرو ثبت شد' : 'Booking registered') : (fa ? 'ثبت‌نام در تور' : 'Tour registration')}</div>
              <h3 style={{ fontSize:18, fontWeight:900, margin:'5px 0 0' }}>{fa ? tour.titleFa : tour.titleEn}</h3>
              <div style={{ fontSize:'12.5px', color:'var(--t3)', marginTop:4 }}>{fa ? tour.cityFa : tour.cityEn} · {fa ? tour.dateFa : tour.dateEn} · {fa ? tour.durFa : tour.durEn}</div>
            </div>
            <button onClick={onClose} style={{ width:34, height:34, borderRadius:10, background:'var(--surface)', border:'1px solid var(--line)', color:'var(--t2)', cursor:'pointer', display:'grid', placeItems:'center', flex:'none' }}>{ico(['M18 6 6 18M6 6l12 12'], 2, 16)}</button>
          </div>

          {done
            ? <div style={{ padding:'26px 22px', textAlign:'center' }}>
                <div style={{ width:58, height:58, borderRadius:'50%', margin:'0 auto 14px', background:'color-mix(in srgb,var(--green) 16%,transparent)', display:'grid', placeItems:'center', color:'var(--green)' }}>{ico(['M5 13l4 4L19 7'], 2.6, 30)}</div>
                <h4 style={{ fontSize:17, fontWeight:900, margin:'0 0 6px' }}>{fa ? 'رزرو شما ثبت شد 🎉' : 'Your booking is registered 🎉'}</h4>
                <p style={{ fontSize:13, color:'var(--t2)', lineHeight:1.9, margin:'0 0 14px' }}>{done.message}</p>
                {done.deposit > 0 &&
                  <div style={{ padding:'12px 14px', borderRadius:'var(--r-sm)', background:'color-mix(in srgb,var(--saffron) 12%,transparent)', border:'1px solid color-mix(in srgb,var(--saffron) 30%,transparent)', fontSize:'12.5px', color:'var(--t1)', lineHeight:1.8, textAlign:'start', marginBottom:14 }}>
                    {fa ? `بیعانهٔ ${fmt(done.deposit, lang)} ${T.toman} برای این تور لازم است. مجریِ تور برای هماهنگیِ پرداختِ بیعانه با شما تماس می‌گیرد.` : `A deposit of ${fmt(done.deposit, lang)} ${T.toman} is required. The operator will contact you to arrange the deposit payment.`}
                  </div>}
                {loggedIn
                  ? <a href="/custom/wegopars/profile.html#orders" style={{ display:'inline-block', textDecoration:'none' }}><Button variant="surface" fullWidth>{fa ? 'مشاهدهٔ حسابِ من' : 'Go to my account'}</Button></a>
                  : <div style={{ fontSize:'12px', color:'var(--t3)', lineHeight:1.8 }}>{fa ? 'برای پیگیریِ رزرو می‌توانید یک حساب بسازید.' : 'Create an account to track your booking.'}</div>}
                <Button variant="brand" fullWidth style={{ marginTop:12 }} onClick={onClose}>{fa ? 'بستن' : 'Done'}</Button>
              </div>
            : <div style={{ padding:'20px 22px' }}>
                {!loggedIn &&
                  <div style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 13px', borderRadius:'var(--r-sm)', background:'var(--surface)', border:'1px solid var(--line)', marginBottom:14, fontSize:'12.5px', color:'var(--t2)' }}>
                    <span style={{ color:'var(--acc)', flex:'none' }}>{ico(['M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2','M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8'], 1.8, 18)}</span>
                    <span style={{ flex:1 }}>{fa ? 'برای پیگیریِ رزرو، وارد شوید (اختیاری).' : 'Log in to track your booking (optional).'}</span>
                    <button onClick={() => { if (window.WCAuth && window.WCAuth.open) window.WCAuth.open(); }} style={{ border:'none', background:'transparent', color:'var(--acc)', fontWeight:800, cursor:'pointer', fontFamily:'inherit', fontSize:'12.5px', flex:'none' }}>{fa ? 'ورود' : 'Log in'}</button>
                  </div>}
                <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
                  <Input label={fa ? 'نام و نام خانوادگی' : 'Full name'} value={name} onChange={(e) => setName(e.target.value)} />
                  <Input label={fa ? 'شمارهٔ تماس' : 'Phone number'} type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} />
                  <div>
                    <div style={{ fontSize:'12px', fontWeight:600, color:'var(--t2)', margin:'0 2px 6px' }}>{fa ? 'تعداد نفرات' : 'Number of people'}{seats ? ` · ${fa ? 'ظرفیتِ باقی‌مانده' : 'seats left'}: ${fmt(seats, lang)}` : ''}</div>
                    <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                      <button onClick={() => setPeople(Math.max(1, (Number(people) || 1) - 1))} style={{ width:40, height:40, borderRadius:10, background:'var(--surface)', border:'1px solid var(--line)', color:'var(--t1)', cursor:'pointer', fontSize:18, fontWeight:800 }}>−</button>
                      <div style={{ minWidth:44, textAlign:'center', fontWeight:900, fontSize:16 }}>{fmt(Number(people) || 1, lang)}</div>
                      <button onClick={() => setPeople((seats ? Math.min(seats, (Number(people) || 1) + 1) : (Number(people) || 1) + 1))} style={{ width:40, height:40, borderRadius:10, background:'var(--surface)', border:'1px solid var(--line)', color:'var(--t1)', cursor:'pointer', fontSize:18, fontWeight:800 }}>+</button>
                    </div>
                  </div>
                </div>
                {isFree
                  ? <div style={{ marginTop:16, padding:14, borderRadius:'var(--r-sm)', background:'color-mix(in srgb,var(--green) 12%,transparent)', border:'1px solid color-mix(in srgb,var(--green) 30%,transparent)', display:'flex', alignItems:'center', gap:10 }}>
                      <span style={{ color:'var(--green)' }}>{ico(['M5 13l4 4L19 7'], 2, 20)}</span>
                      <div style={{ fontSize:13, color:'var(--t1)', fontWeight:700 }}>{fa ? 'این تور رایگان است — فقط ثبت‌نام کنید.' : 'This tour is free — just register.'}</div>
                    </div>
                  : <div style={{ marginTop:16, padding:15, borderRadius:'var(--r-sm)', background:'var(--card)', border:'1px solid var(--line)' }}>
                      <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, color:'var(--t2)', marginBottom:8 }}><span>{fa ? 'هزینهٔ کل تور (هر نفر)' : 'Total tour price (each)'}</span><span style={{ fontWeight:700, color:'var(--t1)' }}>{fmt(tour.price, lang)} {T.toman}</span></div>
                      <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, color:'var(--t2)', marginBottom:10 }}><span>{fa ? 'بیعانه' : 'Deposit'} ({fa ? '٪' + fmt(tour.depositPct, lang) : fmt(tour.depositPct, lang) + '%'})</span><span style={{ fontWeight:900, color:'var(--acc)', fontSize:16 }}>{fmt(deposit, lang)} {T.toman}</span></div>
                      <div style={{ fontSize:'11.5px', color:'var(--t3)', lineHeight:1.7, paddingTop:10, borderTop:'1px solid var(--line)' }}>{fa ? 'رزروِ شما ثبت می‌شود و مجریِ تور برای هماهنگیِ پرداختِ بیعانه با شما تماس می‌گیرد.' : 'Your reservation is registered; the operator will contact you to arrange the deposit.'}</div>
                    </div>}
                {err && <div style={{ marginTop:12, color:'#ef4444', fontSize:'12.5px', textAlign:'center' }}>{err}</div>}
                <Button variant="brand" fullWidth style={{ marginTop:18, opacity: busy ? .7 : 1 }} onClick={busy ? undefined : submit}>{busy ? (fa ? 'در حال ثبت…' : 'Submitting…') : (isFree ? (fa ? 'ثبت‌نام رایگان' : 'Register for free') : (fa ? 'ثبتِ رزرو و هماهنگیِ بیعانه' : 'Reserve & arrange deposit'))}</Button>
              </div>}
        </div>
      </div>
    );
  };
})();
