/**
 * Oveyo PWA V7.8.1 — Page Assistant (fix scroll iOS + safe-area)
 * =================================================================
 * Même fix que FAQ : paddingBottom suffisante + scroll iOS fluide.
 */

const AssistantPage = ({ state, onClose, onOpenSheet }) => {
  const { Send, Bot, User: UserIcon, Loader, Sparkles, ArrowLeft } = window.LucideReact || {};
  const flash = window.OveyoUI?.useFlash ? window.OveyoUI.useFlash() : { show: () => {} };

  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [historyLoaded, setHistoryLoaded] = React.useState(false);
  const messagesEndRef = React.useRef(null);
  const inputRef = React.useRef(null);

  const token = state.user?.session_token;
  const isLoggedIn = !!token;

  React.useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  React.useEffect(() => {
    if (!isLoggedIn || historyLoaded) return;
    const loadHistory = async () => {
      try {
        const r = await fetch('/api/pwa/assistant/history?limit=20', {
          headers: { 'Authorization': 'Bearer ' + token },
        });
        if (r.ok) {
          const data = await r.json();
          const list = (data.history || []).map((h) => ({
            id: h.id,
            from: h.direction === 'in' ? 'user' : 'bot',
            text: h.content,
            time: h.created_at,
          }));
          setMessages(list);
        }
      } catch (e) {
        console.error('History load failed:', e);
      } finally {
        setHistoryLoaded(true);
      }
    };
    loadHistory();
  }, [isLoggedIn, token, historyLoaded]);

  const sendMessage = async (forcedText) => {
    const text = (forcedText || input).trim();
    if (!text || busy || !isLoggedIn) return;

    const userMsg = { id: 'temp-' + Date.now(), from: 'user', text, time: new Date().toISOString() };
    setMessages((prev) => [...prev, userMsg]);
    setInput('');
    setBusy(true);

    try {
      const r = await fetch('/api/pwa/assistant/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + token,
        },
        body: JSON.stringify({ message: text }),
      });

      if (r.status === 429) {
        flash.show('error', 'Trop de messages — attends 1 minute');
        setBusy(false);
        return;
      }

      if (!r.ok) {
        const errData = await r.json().catch(() => ({}));
        flash.show('error', errData.detail || 'Erreur du bot');
        setBusy(false);
        return;
      }

      const data = await r.json();

      // V7.8 : si bot désactivé, afficher un message + bouton WhatsApp
      if (data.disabled) {
        const botMsg = {
          id: 'bot-' + Date.now(),
          from: 'bot',
          text: data.reply,
          time: new Date().toISOString(),
        };
        setMessages((prev) => [...prev, botMsg]);
        setBusy(false);
        return;
      }

      const botMsg = {
        id: 'bot-' + Date.now(),
        from: 'bot',
        text: data.reply,
        intent: data.intent,
        time: new Date().toISOString(),
      };
      setMessages((prev) => [...prev, botMsg]);
    } catch (e) {
      console.error('Send failed:', e);
      flash.show('error', 'Erreur de connexion');
    } finally {
      setBusy(false);
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  const SUGGESTIONS = [
    "Combien le pain à Plateau ?",
    "Prix moyen du gaz",
    "Pharmacie de garde Dakar",
    "Quel est le prix officiel du sucre ?",
  ];

  if (!isLoggedIn) {
    return (
      <div
        className="fixed inset-0 z-[100]"
        style={{
          background: '#FFFFFF',
          maxWidth: 480,
          margin: '0 auto',
          display: 'flex',
          flexDirection: 'column',
          height: '100dvh',
          minHeight: '-webkit-fill-available',
        }}
      >
        <div className="flex items-center gap-3 px-4 py-3" style={{ borderBottom: '1px solid #EAEEF4' }}>
          <button onClick={onClose} className="p-2 -ml-2" aria-label="Fermer">
            <ArrowLeft size={22} className="text-ink" />
          </button>
          <h2 className="font-display font-bold text-base text-ink flex-1">Assistant Oveyo</h2>
        </div>
        <div className="flex-1 flex items-center justify-center p-6">
          <div className="text-center">
            <div className="w-16 h-16 rounded-2xl mx-auto mb-3 flex items-center justify-center" style={{ background: '#FEEEE3' }}>
              <Bot size={32} style={{ color: '#F4632B' }} />
            </div>
            <p className="text-sm text-slate mb-5">Connecte-toi pour utiliser l'assistant.</p>
            <button
              onClick={() => { onClose?.(); onOpenSheet?.('login'); }}
              className="px-5 py-3 rounded-xl font-bold text-white"
              style={{ background: '#F4632B' }}
            >
              Me connecter
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div
      className="fixed inset-0 z-[100]"
      style={{
        background: '#F1F4F9',
        maxWidth: 480,
        margin: '0 auto',
        display: 'flex',
        flexDirection: 'column',
        height: '100dvh',
        minHeight: '-webkit-fill-available',
      }}
    >
      <div
        className="flex items-center gap-3 px-4 py-3 flex-shrink-0"
        style={{
          background: '#FFFFFF',
          borderBottom: '1px solid #EAEEF4',
          paddingTop: 'calc(env(safe-area-inset-top, 0) + 12px)',
        }}
      >
        <button onClick={onClose} className="p-2 -ml-2" aria-label="Fermer">
          <ArrowLeft size={22} className="text-ink" />
        </button>
        <div
          className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0"
          style={{ background: '#FEEEE3' }}
        >
          <Bot size={18} style={{ color: '#F4632B' }} />
        </div>
        <div className="flex-1 min-w-0">
          <h2 className="font-display font-bold text-base text-ink leading-tight">Assistant Oveyo</h2>
          <p className="text-[11px] text-slate">Propulsé par Claude AI</p>
        </div>
      </div>

      <div
        className="flex-1 overflow-y-auto px-4 py-4 space-y-3"
        style={{
          minHeight: 0,
          WebkitOverflowScrolling: 'touch',
          overscrollBehavior: 'contain',
        }}
      >
        {messages.length === 0 && historyLoaded && (
          <div className="text-center py-4">
            <div
              className="w-14 h-14 rounded-2xl mx-auto mb-3 flex items-center justify-center"
              style={{ background: '#FEEEE3' }}
            >
              <Sparkles size={26} style={{ color: '#F4632B' }} />
            </div>
            <p className="text-sm text-slate mb-4">Pose ta première question 👇</p>
            <div className="space-y-2">
              {SUGGESTIONS.map((s, i) => (
                <button
                  key={i}
                  onClick={() => sendMessage(s)}
                  className="block w-full text-left px-4 py-2.5 bg-white rounded-xl text-sm text-ink active:bg-bg-2"
                  style={{ border: '1px solid #EAEEF4' }}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>
        )}

        {messages.map((m) => (
          <div
            key={m.id}
            className={`flex gap-2 ${m.from === 'user' ? 'flex-row-reverse' : 'flex-row'}`}
          >
            <div
              className="w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0"
              style={{ background: m.from === 'user' ? '#102A43' : '#FEEEE3' }}
            >
              {m.from === 'user'
                ? <UserIcon size={14} className="text-white" />
                : <Bot size={14} style={{ color: '#F4632B' }} />}
            </div>
            <div
              className="max-w-[78%] px-3.5 py-2.5 rounded-2xl text-sm"
              style={{
                background: m.from === 'user' ? '#102A43' : '#FFFFFF',
                color: m.from === 'user' ? '#FFFFFF' : '#0F1F36',
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-word',
                border: m.from === 'user' ? 'none' : '1px solid #EAEEF4',
              }}
            >
              {m.text}
            </div>
          </div>
        ))}

        {busy && (
          <div className="flex gap-2">
            <div
              className="w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0"
              style={{ background: '#FEEEE3' }}
            >
              <Bot size={14} style={{ color: '#F4632B' }} />
            </div>
            <div className="px-4 py-3 rounded-2xl bg-white" style={{ border: '1px solid #EAEEF4' }}>
              <div className="flex gap-1.5">
                <span className="w-1.5 h-1.5 rounded-full bg-slate animate-bounce" style={{ animationDelay: '0s' }} />
                <span className="w-1.5 h-1.5 rounded-full bg-slate animate-bounce" style={{ animationDelay: '0.15s' }} />
                <span className="w-1.5 h-1.5 rounded-full bg-slate animate-bounce" style={{ animationDelay: '0.3s' }} />
              </div>
            </div>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      <div
        className="px-3 py-2 flex-shrink-0"
        style={{
          background: '#FFFFFF',
          borderTop: '1px solid #EAEEF4',
          paddingBottom: 'calc(env(safe-area-inset-bottom, 0) + 8px)',
        }}
      >
        <div className="flex gap-2 items-end">
          <input
            ref={inputRef}
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Pose ta question…"
            disabled={busy}
            maxLength={500}
            className="flex-1 px-4 py-3 rounded-2xl text-sm outline-none"
            style={{ background: '#F1F4F9', border: '1px solid #EAEEF4' }}
          />
          <button
            onClick={() => sendMessage()}
            disabled={busy || !input.trim()}
            className="w-12 h-12 rounded-2xl flex items-center justify-center flex-shrink-0"
            style={{
              background: input.trim() && !busy ? '#F4632B' : '#DDE3EC',
              opacity: input.trim() && !busy ? 1 : 0.5,
            }}
          >
            {busy
              ? <Loader size={18} className="text-white animate-spin" />
              : <Send size={18} className="text-white" />}
          </button>
        </div>
        <p className="text-[10px] text-slate text-center mt-1.5">Le bot peut se tromper — vérifie les prix critiques</p>
      </div>
    </div>
  );
};

window.AssistantPage = AssistantPage;
