// aerOS Guest v3 — app shell: bottom nav + routing + guest settings (localStorage) + overlays.
// Merges v1 hotel app (home/outlets/services/concierge/bottom-nav) with the v2 themed menu.
const { useState: _a3S, useEffect: _a3E } = React;

const G3_DEFAULTS = {
  theme: 'dark', accent: '#E0742F', headingFont: 'space', layout: 'gallery', catNav: 'pills',
  heroStyle: 'minimal', corners: 'soft', mode: 'table', photoMode: 'placeholder', currency: '₺',
  showCal: true, showDiet: true, showBadge: true, showPrice: true, featured: true, animate: true,
};

function useGuestSettings() {
  const [s, setS_] = _a3S(() => { try { return { ...G3_DEFAULTS, ...JSON.parse(localStorage.getItem('g3-settings') || '{}') }; } catch { return { ...G3_DEFAULTS }; } });
  const setS = (k, v) => setS_(prev => { const n = { ...prev, [k]: v }; try { localStorage.setItem('g3-settings', JSON.stringify(n)); } catch {} return n; });
  return [s, setS];
}

function G3BottomNav({ C, t, active, onNav, cartCount }) {
  const items = [
    { id: 'home', label: t.home, icon: 'home' },
    { id: 'cart', label: t.cart, icon: 'bag', badge: cartCount },
    { id: 'concierge', label: t.messages, icon: 'chat' },
    { id: 'services', label: t.servicesShort, icon: 'spa' },
  ];
  return (
    <div style={{ flexShrink: 0, display: 'flex', background: C.bg2, borderTop: `1px solid ${C.line}`, padding: '8px 12px calc(8px + env(safe-area-inset-bottom))' }}>
      {items.map(it => { const on = active === it.id; return (
        <button key={it.id} onClick={() => onNav(it.id)} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, border: 'none', background: 'none', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT, position: 'relative', padding: '4px 0' }}>
          <span style={{ position: 'relative', color: on ? C.accent : C.muted, display: 'flex' }}>
            {Icon[it.icon]({ size: 23 })}
            {it.badge > 0 && <span className="tnum" style={{ position: 'absolute', top: -5, right: -8, minWidth: 16, height: 16, padding: '0 4px', borderRadius: 8, background: '#dc2626', color: '#fff', fontSize: 10, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{it.badge}</span>}
          </span>
          <span style={{ fontSize: 10.5, fontWeight: on ? 700 : 600, color: on ? C.accent : C.muted }}>{it.label}</span>
        </button>
      ); })}
    </div>
  );
}

// First-visit "add to home screen" prompt. Android/Chrome installs in one tap
// (native prompt, branded by the manifest). iOS Safari forbids programmatic
// install, so we guide the guest to Share -> Add to Home Screen.
function G3InstallPrompt({ C, t, lang, logo, brandName, onClose }) {
  const en = lang === 'en';
  const isIOS = typeof navigator !== 'undefined' && /iphone|ipad|ipod/i.test(navigator.userAgent || '');
  const canPrompt = !!window.__a2hsPrompt;
  const install = async () => {
    const p = window.__a2hsPrompt;
    if (p) { try { p.prompt(); await p.userChoice; window.__a2hsPrompt = null; } catch (e) {} }
    onClose();
  };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 60, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', background: 'rgba(0,0,0,0.45)', animation: 'g2fade .2s ease' }}>
      <style>{'@keyframes g2fade{from{opacity:0}to{opacity:1}}@keyframes g2bounce{0%,100%{transform:translateY(0)}50%{transform:translateY(5px)}}@keyframes g2rise{from{transform:translateY(100%)}to{transform:translateY(0)}}'}</style>
      <div onClick={e => e.stopPropagation()} style={{ background: C.bg2, borderTopLeftRadius: 24, borderTopRightRadius: 24, padding: '22px 20px calc(20px + env(safe-area-inset-bottom))', boxShadow: '0 -10px 40px rgba(0,0,0,0.4)', animation: 'g2rise .3s cubic-bezier(.22,1,.36,1)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
          <div style={{ width: 58, height: 58, borderRadius: 16, overflow: 'hidden', background: logo ? '#fff' : `linear-gradient(135deg, ${C.accent}, ${C.accentDark})`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 800, fontSize: 26, flexShrink: 0, border: `1px solid ${C.line}` }}>
            {logo ? <img src={logo} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain' }} /> : (brandName || 'a').charAt(0)}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: G2THEME.headFont({ headingFont: 'space' }), fontSize: 18, fontWeight: 700, color: C.ink }}>{en ? 'Add to your Home Screen' : 'Ana ekranınıza ekleyin'}</div>
            <div style={{ fontSize: 13, color: C.muted, marginTop: 2 }}>{en ? `Open ${brandName || 'the app'} in one tap, full-screen.` : `${brandName || 'Uygulamayı'} tek dokunuşla, tam ekran açın.`}</div>
          </div>
          <button onClick={onClose} aria-label={t.close} style={{ width: 32, height: 32, borderRadius: '50%', border: 'none', background: C.dark ? 'rgba(255,255,255,0.07)' : 'rgba(0,0,0,0.05)', color: C.ink2, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>{Icon.x({ size: 17 })}</button>
        </div>
        {canPrompt ? (
          <G2Btn full size="lg" C={C} icon={Icon.download} onClick={install}>{en ? 'Add' : 'Ekle'}</G2Btn>
        ) : isIOS ? (
          <div>
            <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '13px 15px', borderRadius: 14, background: C.dark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.03)', border: `1px solid ${C.line}`, fontSize: 14, color: C.ink2, lineHeight: 1.5 }}>
              <span style={{ color: C.accent, flexShrink: 0, display: 'flex' }}>{Icon.upload({ size: 20 })}</span>
              <div>{en ? <>Tap the <b>Share</b> button below, then <b>Add to Home Screen</b>.</> : <>Aşağıdaki <b>Paylaş</b> butonuna dokun, sonra <b>Ana Ekrana Ekle</b>'yi seç.</>}</div>
            </div>
            <div style={{ textAlign: 'center', marginTop: 4, color: C.accent, fontSize: 24, animation: 'g2bounce 1.4s infinite' }}>↓</div>
          </div>
        ) : (
          <div style={{ fontSize: 13.5, color: C.ink2, textAlign: 'center', padding: '10px 0' }}>{en ? 'Use your browser menu → Install / Add to Home Screen.' : 'Tarayıcı menüsü → Yükle / Ana ekrana ekle.'}</div>
        )}
        <button onClick={onClose} style={{ width: '100%', marginTop: 12, padding: 10, border: 'none', background: 'transparent', color: C.muted, fontSize: 13.5, fontWeight: 600, cursor: 'pointer', fontFamily: G2THEME.BODY_FONT }}>{en ? 'Maybe later' : 'Daha sonra'}</button>
      </div>
    </div>
  );
}

function GuestV3() {
  const [tw, setS] = useGuestSettings();
  // Tenant brand color (primary_color from branding) drives the whole guest
  // theme accent; falls back to the tweak default only when no brand color.
  const _brandAccent = (window.G2DATA.BRAND && window.G2DATA.BRAND.color) || null;
  const C = G2THEME.buildTheme(_brandAccent ? { ...tw, accent: _brandAccent } : tw);
  const [lang, setLang] = _a3S(() => { try { return localStorage.getItem('g3-lang') || 'tr'; } catch { return 'tr'; } });
  _a3E(() => { try { localStorage.setItem('g3-lang', lang); } catch {} }, [lang]);
  const t = lang === 'en' ? window.G2DATA.EN : window.G2DATA.TR;
  const D = window.G2DATA;

  const [screen, setScreen] = _a3S('home');
  const [outlet, setOutlet] = _a3S(null);
  const [service, setService] = _a3S(null);
  const [cart, setCart] = _a3S([]);
  const [order, setOrder] = _a3S(null);
  // Active orders persist across navigation + reload so the guest can always
  // get back to a placed order's tracking from any screen.
  const [orders, setOrders] = _a3S(() => { try { return JSON.parse(localStorage.getItem('g3-orders') || '[]'); } catch (e) { return []; } });
  _a3E(() => { try { localStorage.setItem('g3-orders', JSON.stringify(orders)); } catch (e) {} }, [orders]);
  const openTracking = (rec) => { setOrder({ id: rec.id, surname: rec.surname }); setScreen('tracking'); };
  const [selProduct, setSelProduct] = _a3S(null);
  const [showWaiter, setShowWaiter] = _a3S(false);
  const [showSettings, setShowSettings] = _a3S(false);
  const [toastMsg, setToastMsg] = _a3S('');
  const toast = (m) => { setToastMsg(m); setTimeout(() => setToastMsg(''), 2000); };

  // Capture the Android/Chrome install prompt so Settings can trigger it.
  _a3E(() => {
    const h = (e) => { e.preventDefault(); window.__a2hsPrompt = e; };
    window.addEventListener('beforeinstallprompt', h);
    return () => window.removeEventListener('beforeinstallprompt', h);
  }, []);

  // Production: hydrate real tenant data + pin ordering mode from the QR URL.
  const [ready, setReady] = _a3S(false);
  const [showA2HS, setShowA2HS] = _a3S(false);
  _a3E(() => {
    (window.G2HYDRATE ? window.G2HYDRATE() : Promise.resolve())
      .then(() => { const cm = window.G2CTX && window.G2CTX.mode; if (cm) setS('mode', cm === 'restaurant' ? 'table' : 'room'); })
      .finally(() => setReady(true));
  }, []);
  // First visit: offer "add to home screen" (skip if dismissed or already installed).
  _a3E(() => {
    if (!ready) return;
    let standalone = false;
    try { standalone = (navigator.standalone) || (matchMedia && matchMedia('(display-mode: standalone)').matches); } catch (e) {}
    let dismissed = false;
    try { dismissed = !!localStorage.getItem('aeros-a2hs-dismissed'); } catch (e) {}
    if (standalone || dismissed) return;
    const id = setTimeout(() => setShowA2HS(true), 1400);
    return () => clearTimeout(id);
  }, [ready]);
  const dismissA2HS = () => { setShowA2HS(false); try { localStorage.setItem('aeros-a2hs-dismissed', '1'); } catch (e) {} };

  // Open the product detail sheet, loading its portions/modifiers on demand.
  const openProduct = async (p) => {
    setSelProduct(p);
    try { const opts = window.guestApi ? await window.guestApi.productOptions(p.id) : null; if (opts) setSelProduct(cur => cur && cur.id === p.id ? { ...cur, portions: opts.portions || [], mods: opts.mods || [], allergens: opts.allergens || [] } : cur); } catch (e) {}
  };

  // Build the backend order from the v2 cart + QR context, then show tracking.
  const placeOrder = async (o) => {
    const ctx = window.G2CTX || {};
    const items = (o.items || []).map(it => ({ menu_det_id: Number(it.pid), quantity: it.qty, note: it.note || '' })).filter(it => Number.isFinite(it.menu_det_id));
    const loc = ctx.mode === 'room' ? ctx.room : ctx.table;
    const payload = { surname: String(loc || 'Misafir'), note: o.note || '', price_type: ctx.mode === 'room' ? 0 : 1, outlet_id: (outlet && typeof outlet.id === 'number') ? outlet.id : (ctx.outlet || null), items };
    if (ctx.mode === 'room') payload.room_number = parseInt(ctx.room, 10) || null; else payload.table_number = ctx.table || null;
    let id = null;
    try { const res = window.guestApi ? await window.guestApi.createOrder(payload) : null; id = res && res.id; } catch (e) {}
    if (id) { const rec = { id, surname: payload.surname, ts: Date.now(), label: (outlet && outlet.name) || (D.BRAND && D.BRAND.name) || '' }; setOrders(os => [rec, ...os.filter(x => x.id !== id)].slice(0, 8)); }
    setOrder({ ...o, id, surname: payload.surname }); setCart([]); setScreen('tracking');
  };

  const cartCount = cart.reduce((s, it) => s + it.qty, 0);
  const cartTotal = cart.reduce((s, it) => s + it.unit * it.qty, 0);
  const addItem = (item) => { setCart(c => [...c, item]); toast(t.addToCart); };
  const quickAdd = (p) => { const nm = lang === 'en' ? p.en : p.name; setCart(c => [...c, { id: p.id + '-' + Date.now(), pid: p.id, name: nm, qty: 1, unit: p.price, color: p.color, modLabels: [] }]); toast(t.addToCart); };

  const openOutlet = (o) => { setOutlet(o); setScreen('menu'); };
  const openService = (id) => { if (id === 'concierge') { setScreen('concierge'); return; } setService(id); setScreen('service'); };
  const navTab = (id) => setScreen(id);

  const showNav = ['home', 'cart', 'concierge', 'services'].includes(screen);
  const ctx = window.G2CTX || {};
  const modeLabel = tw.mode === 'room' ? t.roomLabel + ' ' + (ctx.room || '') : tw.mode === 'view' ? t.viewOnly : t.tableLabel + ' ' + (ctx.table || '');

  if (!ready) return (
    <div style={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: C.bg }}>
      <div style={{ width: 30, height: 30, border: `3px solid ${C.line}`, borderTopColor: C.accent, borderRadius: '50%', animation: 'g2spin 0.7s linear infinite' }} />
      <style>{'@keyframes g2spin{to{transform:rotate(360deg)}}'}</style>
    </div>
  );

  // Production: the guest device IS the phone — render fullscreen (no desktop frame).
  return (
    <div style={{ position: 'relative', height: '100vh', display: 'flex', flexDirection: 'column', background: C.bg, fontFamily: G2THEME.BODY_FONT }}>
      <div style={{ flex: 1, minHeight: 0, position: 'relative', overflow: 'hidden' }}>
        {screen === 'home' && <G3Home C={C} t={t} lang={lang} tw={tw} onOutlet={openOutlet} onService={openService} onLang={setLang} onSettings={() => setShowSettings(true)} />}
        {screen === 'menu' && outlet && (
          <G2Menu C={C} t={t} lang={lang} tw={tw} brand={outlet.name} brandSub={`${t['ot_' + outlet.type]} · ${D.BRAND.sub}`}
            onSelect={openProduct} onQuickAdd={quickAdd} onCart={() => setScreen('cart')} onWaiter={() => setShowWaiter(true)}
            cartCount={cartCount} cartTotal={cartTotal} onLang={setLang} onCurrency={(v) => setS('currency', v)}
            onBack={() => setScreen('home')} />
        )}
        {screen === 'cart' && <G2Cart C={C} t={t} lang={lang} tw={tw} cart={cart} setCart={setCart} onBack={() => setScreen(outlet ? 'menu' : 'home')} onPlaced={placeOrder} toast={toast} onItem={(pid) => { const p = D.PRODUCTS.find(x => x.id === pid); if (p) openProduct(p); }} />}
        {screen === 'tracking' && order && <G2Tracking C={C} t={t} lang={lang} tw={tw} order={order} onNew={() => { setOrders(os => os.filter(x => x.id !== (order && order.id))); setCart([]); setOrder(null); setScreen('home'); }} />}
        {screen === 'concierge' && <G3Concierge C={C} t={t} lang={lang} tw={tw} />}
        {screen === 'services' && <G3ServiceList C={C} t={t} lang={lang} tw={tw} onService={openService} />}
        {screen === 'service' && service && <G3Services C={C} t={t} lang={lang} tw={tw} service={service} onBack={() => setScreen('services')} toast={toast} />}
      </div>

      {/* Active-order pill — reachable from any screen so a placed order is never lost. */}
      {orders.length > 0 && !['tracking', 'cart'].includes(screen) && (
        <button onClick={() => openTracking(orders[0])} style={{ position: 'absolute', left: 16, right: 16, bottom: showNav ? 'calc(74px + env(safe-area-inset-bottom))' : 'calc(16px + env(safe-area-inset-bottom))', zIndex: 40, display: 'flex', alignItems: 'center', gap: 11, padding: '12px 16px', borderRadius: 16, border: 'none', background: `linear-gradient(180deg, ${C.accent}, ${C.accentDark})`, color: C.accentInk, boxShadow: '0 12px 30px -8px rgba(0,0,0,0.5)', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT }}>
          <span style={{ width: 30, height: 30, borderRadius: 9, background: 'rgba(255,255,255,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{Icon.clock({ size: 17 })}</span>
          <span style={{ flex: 1, textAlign: 'left', fontSize: 14, fontWeight: 700 }}>{lang === 'en' ? 'Your orders' : 'Siparişlerim'}{orders.length > 1 ? ' · ' + orders.length : ''}</span>
          <span style={{ fontSize: 12.5, fontWeight: 600, opacity: 0.92 }}>{lang === 'en' ? 'Track →' : 'Takip et →'}</span>
        </button>
      )}

      {showNav && <G3BottomNav C={C} t={t} active={screen} onNav={navTab} cartCount={cartCount} />}

      {/* overlays */}
      <G2ProductSheet product={selProduct} C={C} t={t} lang={lang} tw={tw} animate={tw.animate} onClose={() => setSelProduct(null)} onAdd={(item) => { addItem(item); setSelProduct(null); }} />
      <G2WaiterSheet open={showWaiter} onClose={() => setShowWaiter(false)} C={C} t={t} lang={lang} tw={tw} animate={tw.animate} toast={toast} tableLabel={modeLabel} />
      <G3SettingsSheet open={showSettings} onClose={() => setShowSettings(false)} C={C} t={t} tw={tw} setS={setS} animate={tw.animate} lang={lang} />
      {showA2HS && <G3InstallPrompt C={C} t={t} lang={lang} logo={D.BRAND.logo} brandName={D.BRAND.name} onClose={dismissA2HS} />}
      <G2Toast msg={toastMsg} C={C} />
    </div>
  );
}

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