// ============================================================
// MOORE AI v13 — AI STRATEGY TAB (Jake Moore AI)
// Requires: shared/utils.js, shared/components.jsx loaded first
// ============================================================

const AICommandView = ({ messages, isTyping, chatInput, setChatInput, handleSendMessage, toggleListening, isListening, chatEndRef, jakeAvatar, crmData, isVoiceEnabled, toggleMute, liveTranscript, activeCalls, approveActions, cancelActions }) => {
  const { useState } = React;
  const [showHistory, setShowHistory] = useState(false);

  return (
    <div className="h-full flex flex-col">
      {/* Header */}
      <div className="px-8 py-5 border-b border-slate-800/50 bg-gradient-to-r from-blue-950/40 to-indigo-950/40 shrink-0">
        <div className="flex items-center gap-5">
          <div className="relative">
            <div className="w-14 h-14 rounded-2xl overflow-hidden border-2 border-blue-500/40">
              <img src={jakeAvatar} className="w-full h-full object-cover" />
            </div>
            <div className="absolute -bottom-1 -right-1 w-4 h-4 bg-emerald-500 rounded-full border-2 border-[#030712] animate-pulse" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-xs mono text-blue-400 uppercase tracking-[0.2em] mb-0.5">Neural Architect</div>
            <h2 className="font-black text-white text-xl italic tracking-tight">Jake Moore AI — Strategy</h2>
            <div className="text-xs text-slate-500 mt-0.5">{crmData.stats.totalLeads} leads · {fmt$(crmData.stats.pipelineValue)} pipeline</div>
          </div>
          {activeCalls && activeCalls.length > 0 && (
            <div className="flex items-center gap-2 px-3 py-1.5 bg-emerald-500/10 border border-emerald-500/30 rounded-xl">
              <span className="w-2 h-2 bg-emerald-400 rounded-full animate-pulse" />
              <span className="text-xs mono text-emerald-400 font-bold">CALL ACTIVE · {activeCalls[0].contactName}</span>
            </div>
          )}
          <button onClick={() => setShowHistory(true)}
            className="flex items-center gap-2 px-3 py-2 bg-slate-900/60 border border-slate-800 rounded-xl text-xs mono text-slate-400 hover:text-white hover:border-slate-600 transition-all">
            <Icon name="history" size={12} />
            History
          </button>
        </div>
      </div>

      {/* Chat area */}
      <div className="flex-1 overflow-y-auto p-8 space-y-5">
        {messages.map((m, i) => {
          if (m.type === 'action-approval') {
            return (
              <div key={i} className="flex gap-4 justify-start fade-in">
                <div className="w-10 h-10 rounded-2xl overflow-hidden shrink-0 border border-slate-700/60 mt-1">
                  <img src={jakeAvatar} className="w-full h-full object-cover" />
                </div>
                <ActionApprovalCard m={m} approveActions={approveActions} cancelActions={cancelActions} />
              </div>
            );
          }
          return (
            <div key={i} className={`flex gap-4 ${m.role === 'user' ? 'justify-end' : 'justify-start'} fade-in`}>
              {m.role === 'ai' && (
                <div className="w-10 h-10 rounded-2xl overflow-hidden shrink-0 border border-slate-700/60 mt-1">
                  <img src={jakeAvatar} className="w-full h-full object-cover" />
                </div>
              )}
              <div className={`max-w-[80%] px-5 py-4 rounded-2xl text-sm leading-relaxed shadow-lg
                ${m.role === 'user' ? 'bg-blue-600 text-white rounded-tr-md shadow-blue-900/40'
                  : m.type === 'action-success' ? 'bg-emerald-950/60 text-emerald-300 border border-emerald-700/40 rounded-tl-md font-mono text-xs'
                  : m.type === 'action-error' ? 'bg-red-950/60 text-red-300 border border-red-700/40 rounded-tl-md font-mono text-xs'
                  : m.type === 'action-pending' ? 'bg-blue-950/40 text-blue-300 border border-blue-700/30 rounded-tl-md font-mono text-xs animate-pulse'
                  : m.type === 'call-result' ? 'bg-teal-950/60 text-teal-200 border border-teal-700/40 rounded-tl-md'
                  : 'bg-slate-900/80 text-slate-200 border border-slate-800/60 rounded-tl-md ai-prose'}`}>
                {m.role === 'ai' && window.marked && !m.type
                  ? <div dangerouslySetInnerHTML={{ __html: window.marked.parse(m.text) }} />
                  : m.text
                }
              </div>
              {m.role === 'user' && <Avatar name="Jake" size={40} />}
            </div>
          );
        })}
        {isTyping && (
          <div className="flex gap-4">
            <div className="w-10 h-10 rounded-2xl overflow-hidden border border-slate-700/60">
              <img src={jakeAvatar} className="w-full h-full object-cover" />
            </div>
            <div className="bg-slate-900/80 border border-slate-800/60 rounded-2xl rounded-tl-md px-5 py-4 flex gap-2 items-center">
              {[0, 200, 400].map(d => (
                <div key={d} className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: `${d}ms` }} />
              ))}
            </div>
          </div>
        )}
        <div ref={chatEndRef} />
      </div>

      {/* Suggestions */}
      <div className="px-6 pb-3 flex gap-2 flex-wrap shrink-0">
        {[
          { text: "Summarize my pipeline", icon: "bar-chart-2" },
          { text: "Who's closest to closing?", icon: "target" },
          { text: "Call my top lead", icon: "phone" },
          { text: "Who needs follow-up?", icon: "clock" },
          { text: "Show won deals", icon: "trophy" },
          { text: "Create action items for this week", icon: "check-square" },
        ].map(({text, icon}, i) => (
          <button key={i} onClick={() => handleSendMessage(null, text)}
            className="text-xs mono px-3 py-1.5 bg-slate-900/60 border border-slate-800 rounded-xl text-slate-400 hover:text-blue-400 hover:border-blue-500/30 transition-all flex items-center gap-1.5">
            <Icon name={icon} size={11} />
            {text}
          </button>
        ))}
      </div>

      {/* Input */}
      <div className="px-8 pb-8 pt-3">
        {isListening && liveTranscript && (
          <div className="mb-2 px-4 py-2 bg-blue-600/10 border border-blue-500/20 rounded-xl text-sm text-blue-300/80 italic fade-in">
            🎤 {liveTranscript}
          </div>
        )}
        <form onSubmit={handleSendMessage} className="flex gap-3">
          <button type="button" onClick={toggleListening}
            className={`w-11 h-11 rounded-xl flex items-center justify-center shrink-0 transition-all relative overflow-hidden
              ${isListening ? 'bg-red-600 text-white shadow-lg shadow-red-900/40' : 'bg-slate-900/60 border border-slate-700/60 text-slate-400 hover:text-blue-400 hover:border-blue-500/40'}`}>
            {isListening && <span className="absolute inset-0 bg-red-500/30 sonar-ring rounded-xl" />}
            <Icon name={isListening ? 'mic-off' : 'mic'} size={15} />
          </button>
          <input value={chatInput} onChange={e => setChatInput(e.target.value)}
            placeholder={isListening ? '🎤 Listening... (auto-sends after 2s silence)' : 'Command Jake (e.g. "Mark Bathtub Made New as won")'}
            className="flex-1 bg-slate-900/60 border border-slate-700/60 rounded-xl px-5 py-3 text-sm text-white outline-none focus:border-blue-500/50 placeholder:text-slate-600 transition-colors" />
          <button type="button" onClick={toggleMute} title={isVoiceEnabled ? 'Mute Jake' : 'Unmute Jake'}
            className={`w-11 h-11 rounded-xl flex items-center justify-center shrink-0 transition-all border
              ${isVoiceEnabled ? 'bg-slate-900/60 border-slate-700/60 text-slate-400 hover:text-white' : 'bg-slate-800 border-slate-700 text-slate-600'}`}>
            <Icon name={isVoiceEnabled ? 'volume-2' : 'volume-x'} size={15} />
          </button>
          <button type="submit" disabled={!chatInput.trim() || isListening}
            className="w-11 h-11 bg-blue-600 hover:bg-blue-500 disabled:opacity-40 rounded-xl flex items-center justify-center transition-all btn-glow shrink-0">
            <Icon name="send" size={16} className="text-white" />
          </button>
        </form>
        <div className="mt-2 text-center text-[10px] mono text-slate-800">
          {isListening ? 'Speak now — auto-sends after 2s silence' : 'Click mic to use voice · Chrome/Edge only'}
        </div>
      </div>

      {/* Conversation History Modal */}
      {showHistory && (
        <div className="fixed inset-0 bg-black/70 z-[400] flex items-center justify-center p-6 fade-in" onClick={() => setShowHistory(false)}>
          <div className="bg-[#0a0f1a] border border-slate-800 rounded-2xl w-full max-w-2xl max-h-[80vh] flex flex-col shadow-2xl" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between px-6 py-4 border-b border-slate-800/50">
              <div className="font-bold text-white">Conversation History</div>
              <button onClick={() => setShowHistory(false)} className="text-slate-600 hover:text-white transition-colors">
                <Icon name="x" size={16} />
              </button>
            </div>
            <div className="flex-1 overflow-y-auto p-6 space-y-3">
              {messages.slice(-20).map((m, i) => (
                <div key={i} className={`flex gap-3 ${m.role === 'user' ? 'justify-end' : 'justify-start'}`}>
                  <div className={`max-w-[85%] px-4 py-2.5 rounded-xl text-xs leading-relaxed
                    ${m.role === 'user' ? 'bg-blue-600/80 text-white' : 'bg-slate-800/80 text-slate-300 border border-slate-700/40'}`}>
                    {m.text}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
