// aerOS Guest v3 — Concierge chat + Services list screen (v2 themed).
const { useState: _cc3S, useEffect: _cc3E, useRef: _cc3R } = React;

function G3Concierge({ C, t, lang, tw }) {
  const room = (window.G2CTX && (window.G2CTX.room || window.G2CTX.table)) || '-';
  const tkey = 'aeros-guest-thread-' + (window.aerosApi ? (window.aerosApi.getTenant() || '') : '') + '-' + room;
  const [threadId, setThreadId] = _cc3S(() => { try { return localStorage.getItem(tkey) || null; } catch { return null; } });
  const [msgs, setMsgs] = _cc3S([]);
  const [draft, setDraft] = _cc3S('');
  const [closed, setClosed] = _cc3S(false);
  const scroller = _cc3R(null);
  const alive = _cc3R(true);
  _cc3E(() => () => { alive.current = false; }, []);
  const now = lang === 'en' ? 'now' : 'şimdi';
  const fmt = (iso) => (iso || '').slice(11, 16) || now;
  const mapMsgs = (rows) => (rows || []).map(m => ({ from: m.sender === 'staff' ? 'staff' : 'guest', text: m.body, time: fmt(m.created_at) }));
  const reload = async (tid) => { try { const r = await window.guestApi.conciergeMessages(tid); if (alive.current) setMsgs(mapMsgs(r)); } catch (e) {} };
  _cc3E(() => { if (scroller.current) scroller.current.scrollTop = scroller.current.scrollHeight; }, [msgs]);
  // Pick up the room's active thread on open.
  _cc3E(() => { (async () => { try { const tid = await window.guestApi.conciergeActive(room); if (tid) { try { localStorage.setItem(tkey, tid); } catch (e) {} setThreadId(String(tid)); } else { setThreadId(null); setMsgs([]); } } catch (e) {} })(); }, []);
  // Poll for staff replies + detect archival.
  _cc3E(() => {
    if (!threadId || closed) return;
    let stop = false;
    const tick = async () => { try { const [, act] = await Promise.all([reload(threadId), window.guestApi.conciergeActive(room)]); if (!stop && String(act || '') !== String(threadId)) setClosed(true); } catch (e) {} };
    tick(); const id = setInterval(tick, 6000); return () => { stop = true; clearInterval(id); };
  }, [threadId, closed]);
  const startFresh = () => { try { localStorage.removeItem(tkey); } catch (e) {} setClosed(false); setThreadId(null); setMsgs([]); setDraft(''); };
  const push = async (txt) => {
    if (closed) return;
    setMsgs(m => [...m, { from: 'guest', text: txt, time: now }]);
    try {
      if (!threadId) { const res = await window.guestApi.startConcierge(room, txt, 'Oda ' + room); if (res && res.thread_id) { try { localStorage.setItem(tkey, res.thread_id); } catch (e) {} setThreadId(String(res.thread_id)); } }
      else { try { await window.guestApi.sendConcierge(threadId, txt); reload(threadId); } catch (e2) { setClosed(true); } }
    } catch (e) {}
  };
  const send = () => { if (!draft.trim()) return; push(draft.trim()); setDraft(''); };
  const quick = lang === 'en' ? ['May I get towels?', 'Dinner reservation', 'Late check-out?'] : ['Havlu rica edebilir miyim?', 'Akşam için rezervasyon', 'Geç check-out mümkün mü?'];

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: C.bg, fontFamily: G2THEME.BODY_FONT }}>
      <div style={{ flexShrink: 0, background: C.bg2, borderBottom: `1px solid ${C.line}`, padding: '50px 18px 14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 44, height: 44, borderRadius: 13, background: `linear-gradient(135deg, ${C.accent}, ${C.accentDark})`, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{Icon.headset({ size: 22 })}</div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: G2THEME.headFont(tw), fontSize: 20, fontWeight: 600, color: C.ink }}>{t.concierge}</div>
            <div style={{ fontSize: 12, color: C.accent, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 7, height: 7, borderRadius: 7, background: '#5FAE5F' }} />{t.conciergeSub}</div>
          </div>
        </div>
      </div>
      <div ref={scroller} className="g2-noscroll" style={{ flex: 1, overflowY: 'auto', padding: '18px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {msgs.map((m, i) => (
          <div key={m.time + '|' + m.from + '|' + i} style={{ alignSelf: m.from === 'guest' ? 'flex-end' : 'flex-start', maxWidth: '80%', animation: tw.animate ? 'g2up .3s cubic-bezier(.22,1,.36,1)' : 'none' }}>
            <div style={{ padding: '11px 15px', borderRadius: 18, borderBottomRightRadius: m.from === 'guest' ? 5 : 18, borderBottomLeftRadius: m.from === 'guest' ? 18 : 5, background: m.from === 'guest' ? `linear-gradient(180deg, ${C.accent}, ${C.accentDark})` : C.bg2, color: m.from === 'guest' ? C.accentInk : C.ink, fontSize: 14, lineHeight: 1.45, border: m.from === 'guest' ? 'none' : `1px solid ${C.line}` }}>{m.text}</div>
            <div style={{ fontSize: 10.5, color: C.muted, marginTop: 3, textAlign: m.from === 'guest' ? 'right' : 'left' }}>{m.time}</div>
          </div>
        ))}
      </div>
      <div style={{ flexShrink: 0, padding: '10px 14px calc(12px + env(safe-area-inset-bottom))', borderTop: `1px solid ${C.line}`, background: C.bg2 }}>
        {closed ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'center', padding: '6px 4px 2px' }}>
            <div style={{ fontSize: 13, color: C.muted, textAlign: 'center', lineHeight: 1.4 }}>{lang === 'en' ? 'Conversation closed. Start a new one to message again.' : 'Görüşme kapandı. Yeni mesaj için yeni görüşme başlatın.'}</div>
            <G2Btn C={C} onClick={startFresh} icon={Icon.refresh}>{lang === 'en' ? 'New conversation' : 'Yeni görüşme başlat'}</G2Btn>
          </div>
        ) : (<>
          <div className="g2-noscroll" style={{ display: 'flex', gap: 7, overflowX: 'auto', paddingBottom: 9 }}>
            {quick.map(q => <button key={q} onClick={() => push(q)} style={{ flexShrink: 0, padding: '7px 13px', borderRadius: 999, border: `1.5px solid ${C.line2}`, background: 'transparent', color: C.ink2, fontSize: 12.5, fontWeight: 600, cursor: 'pointer', fontFamily: G2THEME.BODY_FONT, whiteSpace: 'nowrap' }}>{q}</button>)}
          </div>
          <div style={{ display: 'flex', gap: 9 }}>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 10, background: C.dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)', borderRadius: 13, padding: '0 14px', height: 48, border: `1px solid ${C.line}` }}>
              <input value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} placeholder={t.msgPlaceholder} style={{ flex: 1, border: 'none', background: 'transparent', outline: 'none', fontSize: 14.5, fontFamily: G2THEME.BODY_FONT, color: C.ink }} />
            </div>
            <button onClick={send} aria-label="send" style={{ width: 48, height: 48, borderRadius: 13, border: 'none', background: `linear-gradient(180deg, ${C.accent}, ${C.accentDark})`, color: C.accentInk, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>{Icon.arrowRight({ size: 20 })}</button>
          </div>
        </>)}
      </div>
    </div>
  );
}

function G3ServiceList({ C, t, lang, tw, onService }) {
  const D = window.G2DATA;
  const all = [...D.SERVICE_TILES, 'tv', 'social', 'concierge'];
  return (
    <div className="g2-noscroll" style={{ height: '100%', overflowY: 'auto', background: C.bg, fontFamily: G2THEME.BODY_FONT }}>
      <div style={{ padding: '52px 18px 12px' }}>
        <h1 style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 28, color: C.ink }}>{t.services}</h1>
      </div>
      <div style={{ padding: '4px 16px 28px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {all.map(s => { const m = D.SERVICE_META[s]; if (!m) return null; return (
          <button key={s} onClick={() => onService(s)} style={{ display: 'flex', flexDirection: 'column', gap: 11, padding: 16, borderRadius: 18, border: tw.corners === 'sharp' ? `1px solid ${C.line}` : 'none', background: C.bg2, boxShadow: tw.corners === 'sharp' ? 'none' : C.cardShadow, cursor: 'pointer', fontFamily: G2THEME.BODY_FONT, textAlign: 'left', transition: 'transform 140ms' }} onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'} onMouseLeave={e => e.currentTarget.style.transform = 'none'}>
            <span style={{ width: 48, height: 48, borderRadius: 14, background: `color-mix(in oklab, ${m.color} 15%, ${C.bg2})`, color: m.color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{Icon[m.icon]({ size: 24 })}</span>
            <span style={{ fontSize: 14.5, fontWeight: 700, color: C.ink }}>{t[s]}</span>
          </button>
        ); })}
      </div>
    </div>
  );
}

Object.assign(window, { G3Concierge, G3ServiceList });
