// components/admin-rinpo-phone.jsx — Owner RINPO Phone overlay (same shell language as store)

function AdminRinpoPhoneChat() {
  const [q, setQ] = React.useState('');
  const [messages, setMessages] = React.useState([]);
  const [listening, setListening] = React.useState(false);
  const [voiceOut, setVoiceOut] = React.useState(true);
  const [busy, setBusy] = React.useState(false);
  const listRef = React.useRef(null);
  const listenHandle = React.useRef(null);
  const speakHandle = React.useRef(null);

  React.useEffect(() => {
    try {
      const seed = sessionStorage.getItem('apg.rinpo.adminSeed');
      if (seed) {
        setQ(seed);
        sessionStorage.removeItem('apg.rinpo.adminSeed');
      }
    } catch (e) { /* ignore */ }
    return function () {
      if (listenHandle.current) listenHandle.current.stop();
      if (speakHandle.current) speakHandle.current.stop();
      if (window.RinpoVoice) window.RinpoVoice.getProvider().stopAll();
    };
  }, []);

  React.useEffect(() => {
    if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [messages, busy]);

  const speak = (text) => {
    if (!voiceOut || !window.RinpoVoice) return;
    const provider = window.RinpoVoice.getProvider();
    if (!provider.canSpeak()) return;
    if (window.RinpoRuntime) window.RinpoRuntime.setState('speaking');
    speakHandle.current = provider.speak(text, {
      onEnd: function () {
        if (window.RinpoRuntime) window.RinpoRuntime.setState('idle');
      },
    });
  };

  const askOwner = (intent) => {
    setBusy(true);
    if (window.RinpoRuntime) window.RinpoRuntime.setState('thinking');
    window.setTimeout(function () {
      try {
        var answer = '';
        var data = null;
        if (window.OwnerIntelligence && window.OwnerIntelligence.ask) {
          var res = window.OwnerIntelligence.ask(intent, { role: 'owner', locale: 'en' });
          answer = (res && res.answer) || (res && res.result && res.result.message) || '';
          data = res;
        } else if (window.OwnerMetrics && window.OwnerMetrics.rinpoInsights) {
          var ins = window.OwnerMetrics.rinpoInsights();
          answer = (ins && ins.briefing && ins.briefing.lines && ins.briefing.lines.join(' ')) || 'Intelligence Fabric not loaded.';
        } else {
          answer = 'Owner intelligence is not loaded yet.';
        }
        if (!answer) answer = 'I don’t have enough data to answer that yet.';
        setMessages(function (m) {
          return m.concat([{ role: 'bot', text: answer, meta: data }]);
        });
        speak(answer);
      } catch (err) {
        setMessages(function (m) {
          return m.concat([{ role: 'bot', text: err.message || 'Something went wrong' }]);
        });
        if (window.RinpoRuntime) window.RinpoRuntime.setState('error');
      }
      setBusy(false);
      if (window.RinpoRuntime && window.RinpoRuntime.getState().uiState === 'thinking') {
        window.RinpoRuntime.setState('idle');
      }
    }, 220);
  };

  const send = (text) => {
    const intent = String(text || q).trim();
    if (!intent || busy) return;
    setMessages(function (m) { return m.concat([{ role: 'user', text: intent }]); });
    setQ('');
    askOwner(intent);
  };

  const startMic = () => {
    if (!window.RinpoVoice) {
      if (window.HAPStore) HAPStore.notify('Voice not available');
      return;
    }
    const provider = window.RinpoVoice.getProvider();
    if (!provider.canListen()) {
      if (window.HAPStore) HAPStore.notify('Voice input not supported in this browser');
      return;
    }
    if (listenHandle.current) listenHandle.current.stop();
    setListening(true);
    if (window.RinpoRuntime) window.RinpoRuntime.setState('listening');
    listenHandle.current = provider.listen({
      onResult: function (t) {
        setListening(false);
        send(t);
      },
      onError: function () {
        setListening(false);
        if (window.RinpoRuntime) window.RinpoRuntime.setState('idle');
      },
      onEnd: function () {
        setListening(false);
      },
    });
  };

  return (
    <div className="rinpo-os-chat">
      <div className="rinpo-os-chat__head">
        <RinpoAvatarImage variant="compact" showPill={false} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="rinpo-os-chat__title">
            {(window.RinpoAssets && window.RinpoAssets.brand && window.RinpoAssets.brand.phone) || 'RINADS PHONE'}
          </div>
          <div className="rinpo-os-chat__sub">
            <span className="rinpo-online-dot" aria-hidden="true" />
            {(window.RinpoAssets && window.RinpoAssets.brand && window.RinpoAssets.brand.intelligence) || 'RINPO Intelligence OS'}
            {' · Owner'}
          </div>
        </div>
        <button
          type="button"
          className={'rinpo-os-chat__voice' + (voiceOut ? ' on' : '')}
          onClick={() => setVoiceOut(!voiceOut)}
          aria-label="Toggle voice output"
        >
          Voice {voiceOut ? 'on' : 'off'}
        </button>
      </div>

      <div className="rinpo-os-chat__messages" ref={listRef}>
        <div className="rinpo-os-chat__bubble rinpo-os-chat__bubble--bot">
          Hi — I’m RINPO for the Owner OS. Ask about sales, pending orders, stock, or what needs attention.
        </div>
        {messages.map(function (msg, i) {
          return (
            <div key={i} className={'rinpo-os-chat__bubble rinpo-os-chat__bubble--' + msg.role}>
              {msg.text}
            </div>
          );
        })}
        {busy && (
          <div className="rinpo-os-chat__bubble rinpo-os-chat__bubble--bot rinpo-os-chat__typing">
            Checking your business…
          </div>
        )}
      </div>

      <div className="rinpo-os-chat__controls">
        {listening && (
          <div className="rinpo-mic-listening" aria-live="polite">
            <span className="rinpo-mic-ripple" />
            <span className="rinpo-mic-ripple rinpo-mic-ripple--2" />
            Listening…
          </div>
        )}
        <form
          className="rinpo-os-chat__form"
          onSubmit={function (e) { e.preventDefault(); send(q); }}
        >
          <input
            className="rinpo-os-chat__input"
            value={q}
            onChange={function (e) { setQ(e.target.value); }}
            placeholder="Type or say something…"
            aria-label="Message RINPO"
          />
          <button
            type="button"
            className={'rinpo-os-chat__mic' + (listening ? ' rinpo-os-chat__mic--live' : '')}
            onClick={startMic}
            aria-label="Voice input"
            disabled={listening || busy}
          >
            <AIcon name="mic" size={18} />
          </button>
          <button type="submit" className="rinpo-os-chat__send" disabled={busy}>Send</button>
        </form>
        <p className="rinpo-os-chat__hint">High-risk actions always need your confirmation</p>
      </div>
    </div>
  );
}

function AdminRinpoPhoneOverlay() {
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    const sync = function (s) {
      setOpen(!!(s && s.open && s.surface === 'admin'));
    };
    if (window.RinpoRuntime) {
      sync(window.RinpoRuntime.getState());
      return window.RinpoRuntime.subscribe(sync);
    }
    return undefined;
  }, []);

  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return function () { document.body.style.overflow = ''; };
  }, [open]);

  if (!open) return null;

  const close = function () {
    if (window.RinpoRuntime) window.RinpoRuntime.close();
    else setOpen(false);
  };

  return (
    <div className="rinpo-phone-overlay rinpo-phone-overlay--admin" role="dialog" aria-modal="true" aria-label="RINPO">
      <button type="button" className="rinpo-phone-overlay__scrim" aria-label="Close RINPO" onClick={close} />
      <div className="rinpo-phone-overlay__panel">
        <div className="rinpo-phone-overlay__bar">
          <div>
            <div className="rinpo-phone-overlay__title">
              {(window.RinpoAssets && window.RinpoAssets.brand && window.RinpoAssets.brand.phone) || 'RINADS PHONE'}
            </div>
            <div className="rinpo-phone-overlay__sub">
              <span className="rinpo-online-dot" />
              {(window.RinpoAssets && window.RinpoAssets.brand && window.RinpoAssets.brand.intelligence) || 'RINPO Intelligence OS'}
              {' · Owner'}
            </div>
          </div>
          <button type="button" className="rinpo-phone-overlay__close" onClick={close} aria-label="Close">×</button>
        </div>
        <div className="rinpo-phone-os" style={{ minHeight: 420, maxHeight: 'min(72vh, 640px)' }}>
          <AdminRinpoPhoneChat />
        </div>
      </div>
    </div>
  );
}

window.AdminRinpoPhoneOverlay = AdminRinpoPhoneOverlay;
window.AdminRinpoPhoneChat = AdminRinpoPhoneChat;
