// aerOS Guest v3 — Hotel services (spa booking, transfer, wifi, events, content) — v2 themed.
const { useState: _s3S, useEffect: _s3E } = React;

// Guest content service key -> backend static_page.page_key aliases. Lets the
// real CMS page back a fixed guest tile (e.g. the "Şehir Turu" tile -> turist).
const PAGE_KEY_ALIAS = { tour: ['turist', 'tour', 'city_tour', 'sehir_turu'], news: ['newspaper', 'news', 'gazete'], tv: ['tv_guide', 'tv'], meeting: ['meeting', 'toplanti'], social: ['social', 'social_media'], gallery: ['gallery', 'galeri'] };
function findStaticPage(service) {
  const pages = (window.G2DATA && window.G2DATA.PAGES) || [];
  const keys = PAGE_KEY_ALIAS[service] || [service];
  return pages.find((p) => keys.includes((p.key || '').toLowerCase())) || null;
}

function G3SvcHeader({ C, t, tw, title, color, icon, onBack }) {
  return (
    <div style={{ background: `linear-gradient(155deg, ${color}, color-mix(in oklab, ${color} 60%, #000))`, color: '#fff', padding: '50px 18px 22px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onBack} aria-label={t.back} style={{ width: 40, height: 40, borderRadius: 12, border: 'none', background: 'rgba(255,255,255,0.2)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0, backdropFilter: 'blur(6px)' }}>{Icon.chevLeft({ size: 21 })}</button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {icon && <span style={{ display: 'flex', opacity: 0.92 }}>{icon({ size: 22 })}</span>}
          <h1 style={{ fontFamily: G2THEME.headFont(tw), fontSize: 23, fontWeight: 600 }}>{title}</h1>
        </div>
      </div>
    </div>
  );
}

function G3Field({ label, children, C }) { return <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}><span style={{ fontSize: 12.5, fontWeight: 700, color: C.ink2 }}>{label}</span>{children}</div>; }
function G3Input({ value, onChange, placeholder, icon, type = 'text', C }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: C.bg2, borderRadius: 12, padding: '0 13px', height: 46, border: `1.5px solid ${C.line2}` }}>
      {icon && <span style={{ color: C.muted, display: 'flex' }}>{icon({ size: 17 })}</span>}
      <input type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder} style={{ flex: 1, border: 'none', background: 'transparent', outline: 'none', fontSize: 14.5, fontFamily: G2THEME.BODY_FONT, color: C.ink }} />
    </div>
  );
}

function G3Services({ C, t, lang, tw, service, onBack, toast }) {
  const D = window.G2DATA;
  const m = D.SERVICE_META[service] || { icon: 'image', color: C.accent };
  const color = m.color;
  return (
    <div className="g2-noscroll" style={{ height: '100%', overflowY: 'auto', background: C.bg, fontFamily: G2THEME.BODY_FONT }}>
      <G3SvcHeader C={C} t={t} tw={tw} title={t[service] || service} color={color} icon={Icon[m.icon]} onBack={onBack} />
      <div style={{ padding: '18px 16px 30px' }}>
        {service === 'spa' && <SpaMod C={C} t={t} lang={lang} tw={tw} toast={toast} />}
        {service === 'transfer' && <TransferMod C={C} t={t} lang={lang} tw={tw} toast={toast} />}
        {service === 'wifi' && <WifiMod C={C} t={t} toast={toast} />}
        {service === 'events' && <EventsMod C={C} t={t} lang={lang} tw={tw} />}
        {['tour', 'gallery', 'news', 'tv', 'meeting', 'social'].includes(service) && <ContentMod C={C} t={t} lang={lang} tw={tw} service={service} color={color} icon={Icon[m.icon]} />}
      </div>
    </div>
  );
}

function SpaMod({ C, t, lang, tw, toast }) {
  const D = window.G2DATA;
  const [book, setBook] = _s3S(null);
  const [tier, setTier] = _s3S(0);
  const [f, setF] = _s3S({ surname: '', date: '', time: '' });
  return (
    <>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {D.SPA_SERVICES.map(s => (
          <div key={s.id} style={{ display: 'flex', gap: 13, padding: 12, background: C.bg2, borderRadius: 16, boxShadow: C.cardShadow }}>
            <div style={{ width: 70, flexShrink: 0 }}><G2Photo id={'spa-' + s.id} color={s.color} ratio={0.95} radius={12} C={C} t={t} photoMode={tw.photoMode} icon={Icon.spa} src={s.image} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 15.5, color: C.ink }}>{lang === 'en' ? s.en : s.name}</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>{s.tiers.map((tr, i) => <span key={i} className="tnum" style={{ fontSize: 11.5, fontWeight: 600, color: C.ink2, background: C.dark ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)', borderRadius: 7, padding: '4px 9px' }}>{tr.d} · {G2THEME.money(tr.p, tw.currency)}</span>)}</div>
              <div style={{ marginTop: 11 }}><G2Btn size="sm" variant="soft" C={C} onClick={() => { setBook(s); setTier(0); }}>{t.book}</G2Btn></div>
            </div>
          </div>
        ))}
      </div>
      <G2Sheet open={!!book} onClose={() => setBook(null)} C={C} animate={tw.animate}>
        {book && <div style={{ padding: '8px 20px calc(24px + env(safe-area-inset-bottom))' }}>
          <h2 style={{ fontFamily: G2THEME.headFont(tw), fontSize: 22, fontWeight: 600, color: C.ink, marginTop: 8 }}>{lang === 'en' ? book.en : book.name}</h2>
          <div style={{ marginTop: 16 }}>
            <span style={{ fontSize: 12.5, fontWeight: 700, color: C.ink2 }}>{t.selectTier}</span>
            <div style={{ display: 'flex', gap: 8, marginTop: 9 }}>{book.tiers.map((tr, i) => <button key={tr.d || i} onClick={() => setTier(i)} style={{ flex: 1, padding: 12, borderRadius: 12, border: `1.5px solid ${tier === i ? C.accent : C.line2}`, background: tier === i ? C.accentSoft : 'transparent', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT }}><div style={{ fontWeight: 700, fontSize: 13, color: C.ink }}>{tr.d}</div><div className="tnum" style={{ fontSize: 13, color: C.onAccentSoft, fontWeight: 700, marginTop: 2 }}>{G2THEME.money(tr.p, tw.currency)}</div></button>)}</div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 13, marginTop: 16 }}>
            <G3Field label={t.surname} C={C}><G3Input value={f.surname} onChange={v => setF({ ...f, surname: v })} icon={Icon.user} C={C} /></G3Field>
            <div style={{ display: 'flex', gap: 12 }}><div style={{ flex: 1 }}><G3Field label={t.date} C={C}><G3Input value={f.date} onChange={v => setF({ ...f, date: v })} type="date" icon={Icon.calendar} C={C} /></G3Field></div><div style={{ flex: 1 }}><G3Field label={t.time} C={C}><G3Input value={f.time} onChange={v => setF({ ...f, time: v })} type="time" icon={Icon.clock} C={C} /></G3Field></div></div>
          </div>
          <div style={{ marginTop: 20 }}><G2Btn full size="lg" C={C} onClick={async () => {
            const tr = book.tiers[tier] || {};
            const when = f.date ? (f.date + 'T' + (f.time || '12:00') + ':00') : new Date().toISOString().slice(0, 19);
            try { await window.guestApi.bookSpa(book.id, parseInt(tr.d, 10) || null, tr.p || null, { surname: f.surname, when, note: null }); toast(t.reserved); setBook(null); }
            catch (e) { toast(lang === 'en' ? 'Could not send request' : 'Talep gönderilemedi'); }
          }}>{t.book} · {G2THEME.money(book.tiers[tier].p, tw.currency)}</G2Btn></div>
        </div>}
      </G2Sheet>
    </>
  );
}

function TransferMod({ C, t, lang, tw, toast }) {
  const D = window.G2DATA;
  const [route, setRoute] = _s3S((D.ROUTES[0] || {}).id);
  const [veh, setVeh] = _s3S((D.VEHICLES[0] || {}).id);
  const [round, setRound] = _s3S(false);
  const [f, setF] = _s3S({ surname: '', flight: '', date: '', pax: '2' });
  if (!D.ROUTES.length || !D.VEHICLES.length) {
    return <div style={{ padding: '40px 20px', textAlign: 'center', color: C.muted, fontSize: 14 }}>{lang === 'en' ? 'No transfer options available.' : 'Transfer seçeneği bulunmuyor.'}</div>;
  }
  const r = D.ROUTES.find(x => x.id === route) || D.ROUTES[0], v = D.VEHICLES.find(x => x.id === veh) || D.VEHICLES[0];
  const price = Math.round(r.price * v.mult * (round ? 1.9 : 1));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <G3Field label={t.route} C={C}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{D.ROUTES.map(x => <button key={x.id} onClick={() => setRoute(x.id)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderRadius: 12, border: `1.5px solid ${route === x.id ? C.accent : C.line2}`, background: route === x.id ? C.accentSoft : 'transparent', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT }}><span style={{ color: route === x.id ? C.accent : C.muted, display: 'flex' }}>{Icon.plane({ size: 17 })}</span><span style={{ flex: 1, textAlign: 'left', fontSize: 14, fontWeight: 600, color: C.ink }}>{lang === 'en' ? x.en : x.label}</span><span className="tnum" style={{ fontSize: 13, color: C.ink2, fontWeight: 700 }}>{G2THEME.money(x.price, tw.currency)}</span></button>)}</div>
      </G3Field>
      <G3Field label={t.vehicle} C={C}>
        <div style={{ display: 'flex', gap: 8 }}>{D.VEHICLES.map(x => <button key={x.id} onClick={() => setVeh(x.id)} style={{ flex: 1, padding: '11px 6px', borderRadius: 12, border: `1.5px solid ${veh === x.id ? C.accent : C.line2}`, background: veh === x.id ? C.accentSoft : 'transparent', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 }}><span style={{ color: veh === x.id ? C.accent : C.muted, display: 'flex' }}>{Icon.car({ size: 18 })}</span><span style={{ fontSize: 11, fontWeight: 700, color: C.ink, textAlign: 'center', lineHeight: 1.15 }}>{x.label}</span><span style={{ fontSize: 10, color: C.muted }}>{x.cap} {t.people}</span></button>)}</div>
      </G3Field>
      <button onClick={() => setRound(r => !r)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderRadius: 12, border: `1.5px solid ${round ? C.accent : C.line2}`, background: round ? C.accentSoft : 'transparent', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT }}><span style={{ width: 20, height: 20, borderRadius: 6, border: `1.5px solid ${round ? C.accent : C.line2}`, background: round ? C.accent : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{round && Icon.check({ size: 13, style: { color: '#fff' } })}</span><span style={{ fontSize: 14, fontWeight: 600, color: C.ink }}>{t.roundTrip}</span></button>
      <div style={{ display: 'flex', gap: 12 }}><div style={{ flex: 1 }}><G3Field label={t.surname} C={C}><G3Input value={f.surname} onChange={v => setF({ ...f, surname: v })} icon={Icon.user} C={C} /></G3Field></div><div style={{ width: 92 }}><G3Field label={t.passengers} C={C}><G3Input value={f.pax} onChange={v => setF({ ...f, pax: v })} type="number" C={C} /></G3Field></div></div>
      <div style={{ display: 'flex', gap: 12 }}><div style={{ flex: 1 }}><G3Field label={t.flightNo} C={C}><G3Input value={f.flight} onChange={v => setF({ ...f, flight: v })} placeholder="TK1980" icon={Icon.plane} C={C} /></G3Field></div><div style={{ flex: 1 }}><G3Field label={t.date} C={C}><G3Input value={f.date} onChange={v => setF({ ...f, date: v })} placeholder="08.06" icon={Icon.calendar} C={C} /></G3Field></div></div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: C.bg2, borderRadius: 14, padding: '14px 16px', border: `1px solid ${C.line}` }}>
        <span style={{ fontSize: 13.5, color: C.ink2, fontWeight: 600 }}>{t.total}</span>
        <span className="tnum" style={{ fontSize: 21, fontWeight: 800, color: C.accent }}>{G2THEME.money(price, tw.currency)}</span>
      </div>
      <G2Btn full size="lg" C={C} icon={Icon.checkCircle} onClick={async () => {
        try {
          await window.guestApi.requestTransfer({
            surname: f.surname, route: (lang === 'en' ? r.en : r.label), car: v.label, price,
            flight: f.flight, round, remarks: `${f.pax} ${t.people} · ${f.date || ''}`.trim(),
          });
          toast(t.reserved);
        } catch (e) { toast(lang === 'en' ? 'Could not send request' : 'Talep gönderilemedi'); }
      }}>{t.request}</G2Btn>
    </div>
  );
}

function WifiMod({ C, t, toast }) {
  const D = window.G2DATA;
  const copy = (v) => { try { navigator.clipboard.writeText(v); } catch {} toast(t.copied); };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0' }}>
        <div style={{ padding: 14, background: '#fff', borderRadius: 18, boxShadow: C.cardShadow }}>{window.QRCode ? <QRCode value={`WIFI:S:${D.BRAND.wifiSsid};T:WPA;P:${D.BRAND.wifiPass};;`} size={150} /> : <div style={{ width: 150, height: 150, background: '#eee', borderRadius: 8 }} />}</div>
      </div>
      <div style={{ background: C.bg2, borderRadius: 16, overflow: 'hidden', border: `1px solid ${C.line}` }}>
        {[[t.wifiName, D.BRAND.wifiSsid], [t.wifiPass, D.BRAND.wifiPass]].map(([k, v], i) => (
          <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderBottom: i === 0 ? `1px solid ${C.line}` : 'none' }}>
            <div style={{ flex: 1 }}><div style={{ fontSize: 11.5, color: C.muted, fontWeight: 600 }}>{k}</div><div className="tnum" style={{ fontSize: 16, fontWeight: 700, color: C.ink, marginTop: 2 }}>{v}</div></div>
            <button onClick={() => copy(v)} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 13px', borderRadius: 10, border: 'none', background: C.accentSoft, color: C.onAccentSoft, fontSize: 12.5, fontWeight: 700, cursor: 'pointer', fontFamily: G2THEME.BODY_FONT }}>{Icon.copy({ size: 14 })}{t.copy}</button>
          </div>
        ))}
      </div>
      <G2Btn full size="lg" variant="dark" C={C} icon={Icon.wifi} onClick={() => toast(t.connect)}>{t.connect}</G2Btn>
    </div>
  );
}

function EventsMod({ C, t, lang, tw }) {
  const D = window.G2DATA;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {D.EVENTS.map(e => (
        <div key={e.id} style={{ background: C.bg2, borderRadius: 18, overflow: 'hidden', boxShadow: C.cardShadow }}>
          <G2Photo id={'ev-' + e.id} color={e.color} ratio={2.3} radius={0} C={C} t={t} photoMode={tw.photoMode} icon={Icon.ticket} />
          <div style={{ padding: 16 }}>
            <div style={{ fontFamily: G2THEME.headFont(tw), fontSize: 19, fontWeight: 600, color: C.ink }}>{lang === 'en' ? e.en : e.title}</div>
            <div style={{ fontSize: 13, color: C.muted, marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>{Icon.calendar({ size: 14 })}{e.date}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// Real CMS-backed content page: loads the tenant's static page (sections / rich
// body / images) for this guest tile. No hard-coded demo content — when the
// tenant hasn't authored a page, a neutral empty state shows instead.
function ContentMod({ C, t, lang, tw, service, color, icon }) {
  const en = lang === 'en';
  const [page, setPage] = _s3S(null);
  const [loading, setLoading] = _s3S(true);
  _s3E(() => {
    let on = true;
    (async () => {
      try {
        const meta = findStaticPage(service);
        if (!meta) { if (on) { setPage(null); setLoading(false); } return; }
        const full = window.guestApi && window.guestApi.staticPage ? await window.guestApi.staticPage(meta.id) : null;
        if (on) { setPage(full || null); setLoading(false); }
      } catch (e) { if (on) { setPage(null); setLoading(false); } }
    })();
    return () => { on = false; };
  }, [service]);

  if (loading) return <div role="status" style={{ padding: '40px 10px', textAlign: 'center', color: C.muted, fontSize: 13 }}>…</div>;

  const sections = (page && Array.isArray(page.sections)) ? page.sections : [];
  const body = page ? (en ? (page.content_en || page.content_tr) : (page.content_tr || page.content_en)) : '';

  if (!page || (!sections.length && !body)) {
    return (
      <div style={{ padding: '46px 20px', textAlign: 'center', color: C.muted, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
        <span style={{ width: 56, height: 56, borderRadius: 16, background: `color-mix(in oklab, ${color} 14%, ${C.bg2})`, color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{icon({ size: 26 })}</span>
        <div style={{ fontSize: 14, fontWeight: 600, color: C.ink2 }}>{en ? 'Content coming soon.' : 'İçerik yakında eklenecek.'}</div>
      </div>
    );
  }

  // Gallery: render the page's section images as a grid.
  if (service === 'gallery') {
    const imgs = sections.map((s) => s.image).filter(Boolean);
    if (!imgs.length) return <div style={{ padding: '46px 20px', textAlign: 'center', color: C.muted, fontSize: 14 }}>{en ? 'No photos yet.' : 'Henüz fotoğraf yok.'}</div>;
    return <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>{imgs.map((src, i) => <G2Photo key={i} id={'gal-' + i} color={color} ratio={1} radius={14} C={C} t={t} photoMode={tw.photoMode} src={src} icon={Icon.image} />)}</div>;
  }

  // Body HTML comes from the tenant's own staff CMS (Quill editor) — first-party,
  // not guest input. Rendered as-is; if untrusted authors are ever added, sanitize here.
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {sections.map((s, i) => {
        const title = en ? (s.title_en || s.title_tr) : (s.title_tr || s.title_en);
        const sBody = en ? (s.body_en || s.body_tr) : (s.body_tr || s.body_en);
        return (
          <div key={s.id || i} style={{ background: C.bg2, borderRadius: 16, overflow: 'hidden', boxShadow: C.cardShadow }}>
            {s.image && <G2Photo id={'sec-' + (s.id || i)} color={color} ratio={2} radius={0} C={C} t={t} photoMode={tw.photoMode} src={s.image} icon={icon} />}
            <div style={{ padding: 16 }}>
              {title && <div style={{ fontFamily: G2THEME.headFont(tw), fontSize: 18, fontWeight: 600, color: C.ink }}>{title}</div>}
              {sBody && <div style={{ fontSize: 13.5, color: C.ink2, lineHeight: 1.55, marginTop: title ? 8 : 0 }} dangerouslySetInnerHTML={{ __html: sBody }} />}
            </div>
          </div>
        );
      })}
      {!sections.length && body && (
        <div style={{ background: C.bg2, borderRadius: 16, padding: 16, boxShadow: C.cardShadow, fontSize: 13.5, color: C.ink2, lineHeight: 1.55 }} dangerouslySetInnerHTML={{ __html: body }} />
      )}
    </div>
  );
}

window.G3Services = G3Services;
