// aerOS Guest v3 — in-menu guest-facing Settings sheet. Lets guests change theme, currency, layout, catNav + content toggles.
function G3Seg({ value, onChange, options, C, cols }) {
  return (
    <div style={{ display: cols ? 'grid' : 'flex', gridTemplateColumns: cols ? `repeat(${cols},1fr)` : undefined, gap: 7, padding: 4, borderRadius: 13, background: C.dark ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.04)' }}>
      {options.map(([v, l]) => { const on = value === v; return (
        <button key={v} onClick={() => onChange(v)} style={{ flex: cols ? undefined : 1, padding: '10px 8px', borderRadius: 10, border: 'none', background: on ? `linear-gradient(180deg, ${C.accent}, ${C.accentDark})` : 'transparent', color: on ? C.accentInk : C.ink2, fontSize: 13.5, fontWeight: 700, cursor: 'pointer', fontFamily: G2THEME.BODY_FONT, transition: 'all 150ms', boxShadow: on ? `0 4px 12px -5px ${C.accent}` : 'none' }}>{l}</button>
      ); })}
    </div>
  );
}

function G3Toggle({ label, value, onChange, C }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '11px 2px' }}>
      <span style={{ fontSize: 14.5, fontWeight: 600, color: C.ink }}>{label}</span>
      <button onClick={() => onChange(!value)} role="switch" aria-checked={value} style={{ position: 'relative', width: 46, height: 28, borderRadius: 999, border: 'none', background: value ? C.accent : (C.dark ? 'rgba(255,255,255,0.16)' : 'rgba(0,0,0,0.18)'), cursor: 'pointer', transition: 'background 180ms', flexShrink: 0 }}>
        <span style={{ position: 'absolute', top: 3, left: value ? 21 : 3, width: 22, height: 22, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,0.3)', transition: 'left 180ms cubic-bezier(.34,1.56,.64,1)' }} />
      </button>
    </div>
  );
}

function G3SettingsSheet({ open, onClose, C, t, tw, setS, animate, lang }) {
  const label = { display: 'flex', alignItems: 'center', gap: 7, fontSize: 12, fontWeight: 700, color: C.muted, textTransform: 'uppercase', letterSpacing: '0.05em', margin: '20px 0 11px' };
  const en = lang === 'en';
  const [iosHelp, setIosHelp] = React.useState(false);
  const [pushMsg, setPushMsg] = React.useState(null);
  const enablePush = async () => {
    if (!window.G2PUSH || !window.G2PUSH.supported) { setPushMsg(en ? 'Notifications not supported on this device.' : 'Bu cihazda bildirim desteklenmiyor.'); return; }
    const r = await window.G2PUSH.enable();
    if (r.ok) setPushMsg(en ? 'Notifications enabled.' : 'Bildirimler açıldı.');
    else if (r.reason === 'insecure') setPushMsg(en ? 'Needs HTTPS or an installed app.' : 'HTTPS ya da kurulu uygulama gerekir.');
    else if (r.reason === 'denied') setPushMsg(en ? 'Permission denied.' : 'İzin verilmedi.');
    else setPushMsg(en ? 'Could not enable notifications.' : 'Bildirimler açılamadı.');
  };
  const isStandalone = (typeof navigator !== 'undefined' && navigator.standalone) || (typeof matchMedia !== 'undefined' && matchMedia('(display-mode: standalone)').matches);
  const isIOS = typeof navigator !== 'undefined' && /iphone|ipad|ipod/i.test(navigator.userAgent || '');
  const addToHome = async () => {
    if (isStandalone) { setIosHelp(false); return; }
    const p = window.__a2hsPrompt;
    if (p) { try { p.prompt(); await p.userChoice; window.__a2hsPrompt = null; } catch (e) {} return; }
    setIosHelp(v => !v);   // iOS Safari can't trigger programmatically — show how-to
  };
  return (
    <G2Sheet open={open} onClose={onClose} C={C} full animate={animate}>
      <div style={{ padding: '8px 20px 0', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
        <span style={{ width: 42, height: 42, borderRadius: 13, background: `linear-gradient(135deg, ${C.accent}, ${C.accentDark})`, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{Icon.settings({ size: 22 })}</span>
        <div style={{ flex: 1 }}>
          <h2 style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 23, color: C.ink, lineHeight: 1.05 }}>{t.settings}</h2>
          <div style={{ fontSize: 12.5, color: C.muted, marginTop: 1 }}>{t.setDesc}</div>
        </div>
        <button onClick={onClose} aria-label={t.close} style={{ width: 34, height: 34, 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: 18 })}</button>
      </div>

      <div className="g2-noscroll" style={{ flex: 1, overflowY: 'auto', padding: '4px 20px 8px' }}>
        <div style={label}>{Icon.sun({ size: 14 })}{t.setTheme}</div>
        <G3Seg value={tw.theme} onChange={v => setS('theme', v)} C={C} options={[['dark', lang === 'en' ? 'Dark' : 'Koyu'], ['light', lang === 'en' ? 'Light' : 'Açık']]} />

        <div style={label}>{Icon.dollar({ size: 14 })}{t.setCurrency}</div>
        <G3Seg value={tw.currency} onChange={v => setS('currency', v)} C={C} options={[['₺', '₺ TL'], ['$', '$ USD'], ['€', '€ EUR']]} />

        <div style={label}>{Icon.grid({ size: 14 })}{t.setLayout}</div>
        <G3Seg value={tw.layout} onChange={v => setS('layout', v)} C={C} cols={2} options={[['gallery', t.layGallery], ['list', t.layList], ['magazine', t.layMagazine], ['text', t.layText]]} />

        <div style={label}>{Icon.menu({ size: 14 })}{t.setCatNav}</div>
        <G3Seg value={tw.catNav} onChange={v => setS('catNav', v)} C={C} options={[['pills', t.navPills], ['tabs', t.navTabs]]} />

        <div style={label}>{Icon.layers({ size: 14 })}{t.setContent}</div>
        <div style={{ background: C.dark ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.02)', borderRadius: 16, padding: '4px 14px', border: `1px solid ${C.line}` }}>
          {[['featured', t.optFeatured], ['showBadge', t.optBadge], ['showDiet', t.optDiet], ['showCal', t.optCal], ['showPrice', t.optPrice], ['animate', t.optAnim]].map(([k, l], i, arr) => (
            <div key={k} style={{ borderBottom: i < arr.length - 1 ? `1px solid ${C.line}` : 'none' }}>
              <G3Toggle label={l} value={tw[k]} onChange={v => setS(k, v)} C={C} />
            </div>
          ))}
        </div>
        <div style={label}>{Icon.home({ size: 14 })}{en ? 'App' : 'Uygulama'}</div>
        {isStandalone ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '12px 14px', borderRadius: 14, background: C.dark ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.02)', border: `1px solid ${C.line}`, fontSize: 13.5, color: C.ink2 }}>
            {Icon.checkCircle ? Icon.checkCircle({ size: 16 }) : Icon.check({ size: 16 })}{en ? 'Running as an installed app.' : 'Uygulama olarak çalışıyor.'}
          </div>
        ) : (
          <>
            <G2Btn full size="lg" C={C} onClick={addToHome} icon={Icon.download}>{en ? 'Add to Home Screen' : 'Ana ekrana ekle'}</G2Btn>
            {iosHelp && isIOS && (
              <div style={{ marginTop: 11, 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: 13.5, color: C.ink2, lineHeight: 1.55 }}>
                {en
                  ? <>Tap the <b>Share</b> button below, then choose <b>Add to Home Screen</b>. The app opens full-screen, no browser bars.</>
                  : <>Alttaki <b>Paylaş</b> butonuna dokun, sonra <b>Ana Ekrana Ekle</b>'yi seç. Uygulama tam ekran açılır, tarayıcı çubukları olmaz.</>}
              </div>
            )}
          </>
        )}
        <div style={label}>{Icon.bell({ size: 14 })}{en ? 'Notifications' : 'Bildirimler'}</div>
        <G2Btn full size="lg" variant="soft" C={C} icon={Icon.bell} onClick={enablePush}>{en ? 'Enable notifications' : 'Bildirimleri aç'}</G2Btn>
        {pushMsg && <div style={{ marginTop: 9, fontSize: 12.5, color: C.muted, textAlign: 'center' }}>{pushMsg}</div>}

        <div style={{ height: 10 }} />
      </div>

      <div style={{ flexShrink: 0, borderTop: `1px solid ${C.line}`, padding: '14px 20px calc(14px + env(safe-area-inset-bottom))', background: C.bg2 }}>
        <G2Btn full size="lg" C={C} onClick={onClose}>{t.close}</G2Btn>
      </div>
    </G2Sheet>
  );
}

window.G3SettingsSheet = G3SettingsSheet;
