// aerOS Guest v2 — Product detail sheet + Filter sheet + Waiter call sheet.
const { useState: _pr2S, useEffect: _pr2E } = React;

function G2ProductSheet({ product, C, t, lang, tw, onClose, onAdd, animate }) {
  const [qty, setQty] = _pr2S(1);
  const [portion, setPortion] = _pr2S(null);
  const [mods, setMods] = _pr2S([]);
  const [note, setNote] = _pr2S('');
  const [allInfo, setAllInfo] = _pr2S(false);
  _pr2E(() => { if (product) { setQty(1); setPortion(product.portions[0]?.id || null); setMods([]); setNote(''); setAllInfo(false); } }, [product]);
  if (!product) return null;
  const D = window.G2DATA;
  const name = lang === 'en' ? product.en : product.name;
  const desc = lang === 'en' ? product.en_desc : product.desc;
  const portObj = product.portions.find(p => p.id === portion);
  const modSum = product.mods.filter(m => mods.includes(m.id)).reduce((s, m) => s + (m.price || 0), 0);
  const unit = product.price + (portObj?.price || 0) + modSum;
  const toggleMod = id => setMods(m => m.includes(id) ? m.filter(x => x !== id) : [...m, id]);
  const lbl = o => lang === 'en' ? (o.en || o.label) : o.label;

  const optRow = (selected, isRadio, label, price, onClick) => (
    <button key={label} onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', borderRadius: 13, border: `1.5px solid ${selected ? C.accent : C.line2}`, background: selected ? C.accentSoft : 'transparent', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT, transition: 'all 130ms' }}>
      <span style={{ width: 20, height: 20, borderRadius: isRadio ? '50%' : 6, border: `1.5px solid ${selected ? C.accent : C.line2}`, background: selected && !isRadio ? C.accent : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        {selected && (isRadio ? <span style={{ width: 10, height: 10, borderRadius: '50%', background: C.accent }} /> : Icon.check({ size: 13, style: { color: '#fff' } }))}
      </span>
      <span style={{ flex: 1, textAlign: 'left', fontSize: 14.5, fontWeight: 600, color: C.ink }}>{label}</span>
      {price > 0 && <span className="tnum" style={{ fontSize: 14, fontWeight: 700, color: C.ink2 }}>+{G2THEME.money(price, tw.currency)}</span>}
    </button>
  );

  return (
    <G2Sheet open={!!product} onClose={onClose} C={C} full animate={animate}>
      <div className="g2-noscroll" style={{ flex: 1, overflowY: 'auto' }}>
        <div style={{ position: 'relative' }}>
          <G2Photo id={'d-' + product.id} color={product.color} ratio={1.6} radius={0} C={C} t={t} photoMode={tw.photoMode} src={product.image} />
          <button onClick={onClose} style={{ position: 'absolute', top: 14, right: 14, width: 36, height: 36, borderRadius: '50%', border: 'none', background: 'rgba(255,255,255,0.92)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: '#1c1712', backdropFilter: 'blur(6px)' }}>{Icon.x({ size: 19 })}</button>
          {tw.showBadge && product.badge && <div style={{ position: 'absolute', bottom: 14, left: 18 }}><G2Badge kind={product.badge} t={t} /></div>}
        </div>
        <div style={{ padding: '20px 18px 8px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 14 }}>
            <h2 style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 27, color: C.ink, lineHeight: 1.08 }}>{name}</h2>
            {tw.showPrice && <span className="tnum" style={{ fontWeight: 800, fontSize: 22, color: C.accent, flexShrink: 0 }}>{G2THEME.money(product.price, tw.currency)}</span>}
          </div>
          <p style={{ fontSize: 14.5, color: C.ink2, lineHeight: 1.55, margin: '11px 0 0' }}>{desc}</p>

          {/* meta row: diet + cal + prep */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 15, flexWrap: 'wrap' }}>
            {tw.showDiet && <G2Diet ids={product.diet} C={C} />}
            {product.cal != null && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 13, fontWeight: 600, color: C.ink2 }}>{Icon.flame({ size: 15, style: { color: C.muted } })}<span className="tnum">{product.cal}</span> {t.cal}</span>}
            {product.prep != null && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 13, fontWeight: 600, color: C.ink2 }}>{Icon.clock({ size: 15, style: { color: C.muted } })}<span className="tnum">{product.prep}</span> {t.prepTime}</span>}
          </div>

          {product.allergens.length > 0 && (
            <div style={{ marginTop: 16, padding: '13px 14px', borderRadius: 14, background: C.dark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.03)', border: `1px solid ${C.line}` }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11.5, fontWeight: 700, color: C.muted, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{t.allergens}</div>
                <button onClick={() => setAllInfo(true)} aria-label={t.allergenInfo} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '5px 10px 5px 8px', borderRadius: 999, border: `1px solid ${C.line2}`, background: 'transparent', color: C.accent, fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: G2THEME.BODY_FONT }}>{Icon.info({ size: 15 })}{t.allergenInfo}</button>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
                {product.allergens.map(a => <G2AllergenChip key={a} id={a} t={t} C={C} />)}
              </div>
            </div>
          )}

          {product.portions.length > 0 && (
            <div style={{ marginTop: 22 }}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: C.ink, marginBottom: 10 }}>{t.size}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>{product.portions.map(p => optRow(portion === p.id, true, lbl(p), p.price, () => setPortion(p.id)))}</div>
            </div>
          )}

          {product.mods.length > 0 && (
            <div style={{ marginTop: 22 }}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: C.ink, marginBottom: 10 }}>{t.extras}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>{product.mods.map(m => optRow(mods.includes(m.id), false, lbl(m), m.price, () => toggleMod(m.id)))}</div>
            </div>
          )}

          <div style={{ marginTop: 22 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: C.ink, marginBottom: 10 }}>{t.note}</div>
            <textarea value={note} onChange={e => setNote(e.target.value)} placeholder={t.itemNote} rows={2} style={{ width: '100%', boxSizing: 'border-box', borderRadius: 13, border: `1.5px solid ${C.line2}`, padding: '12px 14px', fontSize: 14.5, fontFamily: G2THEME.BODY_FONT, resize: 'none', color: C.ink, outline: 'none', background: C.dark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.02)' }} />
          </div>
        </div>
      </div>

      <div style={{ flexShrink: 0, borderTop: `1px solid ${C.line}`, padding: '14px 18px calc(14px + env(safe-area-inset-bottom))', display: 'flex', alignItems: 'center', gap: 14, background: C.bg2 }}>
        <G2Stepper value={qty} onChange={setQty} C={C} />
        <G2Btn full size="lg" C={C} onClick={() => onAdd({ id: product.id + '-' + Date.now(), pid: product.id, name, qty, unit, portionLabel: portObj && lbl(portObj), modLabels: product.mods.filter(m => mods.includes(m.id)).map(lbl), note, color: product.color })}>
          {tw.mode === 'view' ? t.add : t.addToCart} · {G2THEME.money(unit * qty, tw.currency)}
        </G2Btn>
      </div>

      {/* allergen info popup */}
      {allInfo && (
        <div onMouseDown={e => { if (e.target === e.currentTarget) setAllInfo(false); }} style={{ position: 'absolute', inset: 0, background: 'rgba(8,6,4,0.6)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 22, zIndex: 90, animation: animate ? 'g2fade .2s ease' : 'none' }}>
          <div style={{ width: '100%', maxWidth: 320, background: C.bg2, borderRadius: 22, overflow: 'hidden', boxShadow: '0 24px 60px rgba(0,0,0,0.5)', border: `1px solid ${C.line}`, animation: animate ? 'g2pop .3s cubic-bezier(.34,1.56,.64,1)' : 'none' }}>
            <div style={{ padding: '18px 20px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: `1px solid ${C.line}` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                <span style={{ width: 34, height: 34, borderRadius: 10, background: C.accentSoft, color: C.onAccentSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{Icon.info({ size: 19 })}</span>
                <span style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 19, color: C.ink }}>{t.allergenInfo}</span>
              </div>
              <button onClick={() => setAllInfo(false)} aria-label={t.close} style={{ width: 30, height: 30, 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' }}>{Icon.x({ size: 16 })}</button>
            </div>
            <div className="g2-noscroll" style={{ padding: '8px 12px', maxHeight: 300, overflowY: 'auto' }}>
              {product.allergens.map(a => { const ic = ALLERGEN_ICON[((window.G2DATA.ALLERGEN_ICOKEY || {})[a]) || a] || Icon.info; return (
                <div key={a} style={{ display: 'flex', gap: 12, padding: '11px 8px', borderBottom: `1px solid ${C.line}` }}>
                  <span style={{ width: 38, height: 38, borderRadius: 11, background: C.accentSoft, color: C.onAccentSoft, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{ic({ size: 21 })}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 700, color: C.ink }}>{D.ALLERGENS[a]}</div>
                    <div style={{ fontSize: 12.5, color: C.muted, marginTop: 2, lineHeight: 1.4 }}>{(D.ALLERGEN_DESC[lang] || D.ALLERGEN_DESC.tr)[a]}</div>
                  </div>
                </div>
              ); })}
            </div>
            <div style={{ padding: '12px 16px', display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 12, color: C.muted, lineHeight: 1.4 }}>{Icon.alert({ size: 15, style: { flexShrink: 0, marginTop: 1 } })}{t.allergenNote}</div>
          </div>
        </div>
      )}
    </G2Sheet>
  );
}

function G2FilterSheet({ open, onClose, C, t, tw, diet, toggleDiet, counts, priceMax, setPriceMax, calMax, setCalMax, maxP, maxC, resultCount, onClear, animate }) {
  const opts = [['veg', t.veg, 'leaf'], ['vegan', t.vegan, 'leaf'], ['gf', t.gf, 'shield'], ['spicy', t.spicy, 'flame']];
  const slider = (val, set, min, max, step, fmt) => (
    <div>
      <input type="range" min={min} max={max} step={step} value={val} onChange={e => set(Number(e.target.value))} style={{ width: '100%', accentColor: C.accent, height: 4, cursor: 'pointer' }} />
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: C.muted, marginTop: 4 }}><span>{fmt(min)}</span><span className="tnum" style={{ fontWeight: 800, color: C.accent, fontSize: 13 }}>{val >= max ? (t.all) : '≤ ' + fmt(val)}</span><span>{fmt(max)}</span></div>
    </div>
  );
  return (
    <G2Sheet open={open} onClose={onClose} C={C} animate={animate}>
      <div style={{ padding: '8px 20px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <h2 style={{ fontFamily: G2THEME.headFont({ headingFont: 'bodoni' }), fontWeight: 600, fontSize: 23, color: C.ink }}>{t.filters}</h2>
        <button onClick={onClear} style={{ border: 'none', background: 'none', color: C.accent, fontSize: 13.5, fontWeight: 700, cursor: 'pointer', fontFamily: G2THEME.BODY_FONT }}>{t.clear}</button>
      </div>
      <div className="g2-noscroll" style={{ padding: '16px 20px 8px', overflowY: 'auto' }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: C.muted, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 12 }}>{t.diet}</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 11 }}>
          {opts.map(([id, label, icon]) => { const on = diet.includes(id); const m = DIET_META[id]; return (
            <button key={id} onClick={() => toggleDiet(id)} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '14px 15px', borderRadius: 14, border: `1.5px solid ${on ? m.c : C.line2}`, background: on ? `color-mix(in oklab, ${m.c} 12%, ${C.bg2})` : 'transparent', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT, textAlign: 'left' }}>
              <span style={{ width: 38, height: 38, borderRadius: 11, background: `color-mix(in oklab, ${m.c} 16%, ${C.bg2})`, color: m.c, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{Icon[icon]({ size: 19 })}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: C.ink }}>{label}</div>
                <div className="tnum" style={{ fontSize: 11.5, color: C.muted }}>{counts[id]} {t.items}</div>
              </div>
              {on && <span style={{ color: m.c, display: 'flex' }}>{Icon.checkCircle({ size: 20 })}</span>}
            </button>
          ); })}
        </div>

        <div style={{ fontSize: 12, fontWeight: 700, color: C.muted, textTransform: 'uppercase', letterSpacing: '0.05em', margin: '22px 0 12px' }}>{t.priceRange}</div>
        {slider(priceMax, setPriceMax, 90, maxP, 10, v => G2THEME.money(v, tw.currency))}

        <div style={{ fontSize: 12, fontWeight: 700, color: C.muted, textTransform: 'uppercase', letterSpacing: '0.05em', margin: '22px 0 12px' }}>{t.cal}</div>
        {slider(calMax, setCalMax, 100, maxC, 20, v => v + ' ' + t.cal)}
      </div>
      <div style={{ padding: '12px 20px calc(18px + env(safe-area-inset-bottom))' }}>
        <G2Btn full size="lg" C={C} onClick={onClose}>{t.apply}{resultCount != null ? ` · ${resultCount} ${t.items}` : ''}</G2Btn>
      </div>
    </G2Sheet>
  );
}

function G2WaiterSheet({ open, onClose, C, t, lang, toast, tableLabel, animate }) {
  const D = window.G2DATA;
  return (
    <G2Sheet open={open} onClose={onClose} C={C} animate={animate}>
      <div style={{ padding: '10px 20px 0', display: 'flex', alignItems: 'center', gap: 13 }}>
        <div style={{ width: 46, height: 46, borderRadius: 14, background: `linear-gradient(135deg, ${C.accent}, ${C.accentDark})`, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{Icon.headset({ size: 23 })}</div>
        <div>
          <h2 style={{ fontFamily: G2THEME.headFont({ headingFont: 'bodoni' }), fontWeight: 600, fontSize: 22, color: C.ink, lineHeight: 1.05 }}>{t.waiterTitle}</h2>
          <div style={{ fontSize: 13, color: C.muted, marginTop: 2 }}>{tableLabel} · {t.waiterDesc}</div>
        </div>
      </div>
      <div style={{ padding: '18px 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {D.WAITER_ACTIONS.map(a => (
          <button key={a.id} onClick={async () => { onClose(); try { if (window.guestApi) await window.guestApi.serviceRequest(a.id); toast(t.sent + ' · ' + t[a.label]); } catch (e) { toast((lang === 'en' ? 'Could not send request' : 'İstek gönderilemedi')); } }} style={{ display: 'flex', flexDirection: 'column', gap: 11, padding: 17, borderRadius: 16, border: `1px solid ${C.line}`, background: C.dark ? 'rgba(255,255,255,0.03)' : 'transparent', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT, textAlign: 'left', transition: 'transform 130ms' }} onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'} onMouseLeave={e => e.currentTarget.style.transform = 'none'}>
            <span style={{ width: 44, height: 44, borderRadius: 13, background: `color-mix(in oklab, ${a.color} 15%, ${C.bg2})`, color: a.color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{Icon[a.icon]({ size: 22 })}</span>
            <span style={{ fontSize: 14.5, fontWeight: 700, color: C.ink }}>{t[a.label]}</span>
          </button>
        ))}
      </div>
      <div style={{ padding: '0 20px calc(18px + env(safe-area-inset-bottom))', fontSize: 12.5, color: C.muted, textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>{Icon.info({ size: 14 })}{t.onWay}</div>
    </G2Sheet>
  );
}

Object.assign(window, { G2ProductSheet, G2FilterSheet, G2WaiterSheet });
