// components/rinpo-phone-chat.jsx — in-phone dark chat + VoiceProvider STT/TTS

function RinpoPhoneChat({ onAskAbout }) {
  const store = useStore();
  const route = useRoute();
  const user = store.state.user;
  const [q, setQ] = React.useState(store.state.rinpoChatPrefill || '');
  const [messages, setMessages] = React.useState([]);
  const [voiceOn, setVoiceOn] = React.useState(true);
  const [listening, setListening] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const listRef = React.useRef(null);
  const listenHandle = React.useRef(null);
  const speakHandle = React.useRef(null);
  const pageProduct = route.name === 'product' ? HAP.productBySlug(route.params.slug) : null;

  React.useEffect(() => {
    if (store.state.rinpoChatPrefill) {
      setQ(store.state.rinpoChatPrefill);
      store.state.rinpoChatPrefill = '';
    }
    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 (!voiceOn || !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 send = (text) => {
    const intent = String(text || q).trim();
    if (!intent || busy) return;
    setMessages(function (m) { return m.concat([{ role: 'user', text: intent }]); });
    setQ('');
    setBusy(true);
    if (window.RinpoRuntime) window.RinpoRuntime.setState('thinking');
    window.setTimeout(function () {
      try {
        const res = window.CustomerRinpo.ask(intent, { user: user, product: pageProduct });
        setMessages(function (m) {
          return m.concat([{ role: 'bot', text: res.text, products: res.products, href: res.href }]);
        });
        speak(res.text);
      } 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');
      }
    }, 280);
  };

  const onSubmit = (e) => {
    e.preventDefault();
    send(q);
  };

  const startMic = () => {
    if (!window.RinpoVoice) {
      HAPStore.notify('Voice not available');
      return;
    }
    const provider = window.RinpoVoice.getProvider();
    if (!provider.canListen()) {
      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'}
            {user ? ' · ' + user.email : ''}
          </div>
        </div>
      </div>

      <div className="rinpo-os-chat__messages" ref={listRef}>
        <div className="rinpo-os-chat__bubble rinpo-os-chat__bubble--bot">
          Hi! I'm RINPO, your Ambady garden assistant. Ask about pebbles, pack sizes, orders, or bulk supply.
        </div>
        {messages.map(function (msg, i) {
          return (
            <div key={i} className={'rinpo-os-chat__bubble rinpo-os-chat__bubble--' + msg.role}>
              {msg.text}
              {msg.products && msg.products.length > 0 && (
                <div className="rinpo-os-chat__products">
                  {msg.products.map(function (p) {
                    return (
                      <a key={p.id || p.slug} href={p.href || ('#/products/' + p.slug)}>
                        {p.name}{p.price != null ? ' · ' + HAP.formatPrice(p.price) : ''}
                      </a>
                    );
                  })}
                </div>
              )}
              {msg.href && <a href={msg.href} className="rinpo-os-chat__link">Open</a>}
            </div>
          );
        })}
        {busy && (
          <div className="rinpo-os-chat__bubble rinpo-os-chat__bubble--bot rinpo-os-chat__typing">
            Looking that up…
          </div>
        )}
      </div>

      <div className="rinpo-os-chat__controls">
        <button type="button" className={'rinpo-os-chat__voice' + (voiceOn ? ' on' : '')} onClick={() => setVoiceOn(!voiceOn)}>
          Voice {voiceOn ? 'on' : 'off'}
        </button>
        {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={onSubmit}>
          <input
            className="rinpo-os-chat__input"
            value={q}
            onChange={(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}
          >
            <Icon name="mic" size={18} />
          </button>
          <button type="submit" className="rinpo-os-chat__send" disabled={busy}>Send</button>
        </form>
        <p className="rinpo-os-chat__hint">Tap mic for voice · RINPO never changes prices or stock</p>
      </div>
    </div>
  );
}

window.RinpoPhoneChat = RinpoPhoneChat;
