// Saladizer Web — Chef Saladizer AI chat panel.

function ChefPanel({ open, onClose, t, lang, selections }) {
  const isAr = lang === 'ar';
  const initial = [{ role: 'bot', text: t.chefIntro }];
  const [messages, setMessages] = React.useState(initial);
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const bodyRef = React.useRef(null);

  // When language changes, reset intro
  React.useEffect(() => {
    setMessages([{ role: 'bot', text: t.chefIntro }]);
  }, [lang]);

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

  const send = async (text) => {
    const userText = (text ?? input).trim();
    if (!userText || busy) return;
    setInput('');
    const nextHistory = [...messages, { role: 'user', text: userText }];
    setMessages(nextHistory);
    setBusy(true);

    try {
      // Build current-bowl context for the backend AI route.
      const items = Object.entries(selections)
        .map(([id, qty]) => {
          const ing = ALL_INGREDIENTS.find(i => i.id === id);
          if (!ing) return null;
          return { name: ing.name, ar: ing.ar, qty };
        })
        .filter(Boolean);

      const chatHistory = nextHistory
        .filter(m => m.role !== 'thinking')
        .slice(-10)
        .map(m => ({
          role: m.role === 'user' ? 'user' : 'assistant',
          content: m.text,
        }));

      let replyText;
      try {
        const out = await window.api.chefChat({
          message: userText,
          ingredients: items.map(i => `${i.qty}× ${i.name}`),
          ingredientsAr: items.map(i => `${i.qty}× ${i.ar}`),
          language: isAr ? 'ar' : 'en',
          chatHistory,
        });
        const limitMsg = out && out.message && (out.message.ar || out.message.en)
          ? (isAr ? (out.message.ar || out.message.en) : (out.message.en || out.message.ar))
          : '';
        replyText = isAr
          ? (out.messageAr || out.message_ar || (typeof out.message === 'string' ? out.message : '') || out.textAr || out.text || limitMsg || '')
          : ((typeof out.message === 'string' ? out.message : '') || out.text || out.messageAr || limitMsg || '');
      } catch (err) {
        if (err && err.status === 401) {
          replyText = isAr
            ? 'يبدو أن جلستك انتهت. أعد تسجيل الدخول.'
            : 'Your session expired. Please sign in again.';
        } else if (err && err.status === 429) {
          replyText = isAr
            ? 'وصلت حد الأسئلة اليومي. حاول لاحقاً أو رقّ إلى Plus.'
            : 'Daily question limit reached. Try later or upgrade to Plus.';
        } else {
          replyText = isAr
            ? 'عذراً، حصلت عثرة بسيطة. جرّب تعيد السؤال؟'
            : 'Sorry — I hit a tiny snag. Try asking again?';
        }
      }
      setMessages(m => [...m, { role: 'bot', text: (replyText || '').trim() }]);
    } finally {
      setBusy(false);
    }
  };

  const suggestions = [t.chefSuggest1, t.chefSuggest2, t.chefSuggest3];

  return (
    <>
      <div className={'chef-backdrop' + (open ? ' open' : '')} onClick={onClose} />
      <aside className={'chef-panel' + (open ? ' open' : '')} aria-hidden={!open}>
        <div className="chef-head">
          <div className="chef-avatar">
            <Icon name="zap" size={20} color="#fff" />
            <span className="online" />
          </div>
          <div>
            <div className="chef-name">{t.chefName}</div>
            <div className="chef-sub">{t.chefSub}</div>
          </div>
          <button className="chef-close" onClick={onClose}>
            <Icon name="x" size={18} />
          </button>
        </div>

        <div className="chef-body" ref={bodyRef}>
          {messages.map((m, i) => (
            <div key={i} className={'chef-msg ' + m.role}>
              {m.text}
            </div>
          ))}
          {busy && (
            <div className="chef-msg thinking">
              <span className="dots">
                <span>•</span><span>•</span><span>•</span>
              </span>{' '}
              {isAr ? 'الشيف يفكر' : 'Chef Saladizer is thinking'}
            </div>
          )}
        </div>

        {messages.length <= 1 && !busy && (
          <div className="chef-suggest">
            {suggestions.map((s, i) => (
              <button key={i} onClick={() => send(s)}>
                <Icon name="zap" size={11} color="var(--accent)" /> {s}
              </button>
            ))}
          </div>
        )}

        <div className="chef-input-wrap">
          <div className="chef-input">
            <input
              type="text"
              value={input}
              placeholder={t.chefPlaceholder}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
              disabled={busy}
            />
            <button className="send" disabled={busy || !input.trim()} onClick={() => send()}>
              <Icon name="arrow-up" size={18} color="#fff" />
            </button>
          </div>
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { ChefPanel });
