// ============================================================
// MOORE AI v13 — CONTACTS TAB
// Requires: shared/utils.js, shared/components.jsx loaded first
// ============================================================

const ContactsView = ({ contacts, loadingTabs, fetchContacts, setSelectedContact, showContactForm, setShowContactForm, contactForm, setContactForm, createContact }) => {
  const { useState, useEffect } = React;

  useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  });
  const [search, setSearch] = useState('');
  const [activeContact, setActiveContact] = useState(null);
  const [activity, setActivity] = useState([]);
  const [loadingActivity, setLoadingActivity] = useState(false);
  const [noteInput, setNoteInput] = useState('');
  const [sendType, setSendType] = useState('SMS');
  const [sendMsg, setSendMsg] = useState('');
  const [sending, setSending] = useState(false);
  const [activityTab, setActivityTab] = useState('all');
  const [panelExpanded, setPanelExpanded] = useState(false);

  const filtered = contacts.filter(c =>
    (c.name + c.email + c.phone + (c.tags||[]).join(' ')).toLowerCase().includes(search.toLowerCase())
  );

  const openContact = async (c) => {
    setActiveContact(c);
    setActivity([]);
    setActivityTab('all');
    setPanelExpanded(false);
    loadActivity(c.id);
  };

  const loadActivity = async (id) => {
    setLoadingActivity(true);
    try {
      const data = await API.fetchContactActivity(id);
      if (data.success) setActivity(data.activity || []);
    } catch(e) {}
    setLoadingActivity(false);
  };

  const addContactNote = async () => {
    if (!noteInput.trim() || !activeContact) return;
    await API.addNote(activeContact.id, noteInput);
    setActivity(prev => [{ type: 'note', body: noteInput, date: new Date().toISOString(), id: Date.now() }, ...prev]);
    setNoteInput('');
  };

  const sendMessage = async () => {
    if (!sendMsg.trim() || !activeContact) return;
    setSending(true);
    try {
      await API.sendConversationMessage({ type: sendType, contactId: activeContact.id, message: sendMsg, subject: `Message from Jake` });
      setActivity(prev => [{ type: sendType.toLowerCase(), body: sendMsg, date: new Date().toISOString(), direction: 'outbound', id: Date.now() }, ...prev]);
      setSendMsg('');
    } catch(e) { alert('Send failed: ' + e.message); }
    setSending(false);
  };

  const filteredActivity = activity.filter(a => {
    if (activityTab === 'sms') return a.type === 'sms';
    if (activityTab === 'email') return a.type === 'email';
    if (activityTab === 'notes') return a.type === 'note';
    if (activityTab === 'tasks') return a.type === 'task';
    if (activityTab === 'event') return a.type === 'event';
    return true;
  });

  const activityIcon = (type) => {
    if (type === 'sms') return 'message-square';
    if (type === 'email') return 'mail';
    if (type === 'call') return 'phone';
    if (type === 'note') return 'file-text';
    if (type === 'task') return 'check-square';
    if (type === 'event') return 'zap';
    return 'activity';
  };

  const activityColors = (type, direction) => {
    if (type === 'sms') return direction === 'inbound'
      ? 'text-emerald-300 bg-emerald-500/5 border-emerald-500/20'
      : 'text-blue-300 bg-blue-500/5 border-blue-500/20';
    if (type === 'email') return direction === 'inbound'
      ? 'text-cyan-300 bg-cyan-500/5 border-cyan-500/20'
      : 'text-violet-300 bg-violet-500/5 border-violet-500/20';
    if (type === 'call') return 'text-amber-300 bg-amber-500/5 border-amber-500/20';
    if (type === 'note') return 'text-slate-300 bg-slate-800/50 border-slate-700/40';
    if (type === 'task') return 'text-orange-300 bg-orange-500/5 border-orange-500/20';
    if (type === 'event') return 'text-teal-300 bg-teal-500/5 border-teal-500/20';
    return 'text-slate-300 bg-slate-800/50 border-slate-700/40';
  };

  const activityLabel = (item) => {
    if (item.type === 'sms') return item.direction === 'inbound' ? '← SMS' : '→ SMS';
    if (item.type === 'email') return item.direction === 'inbound' ? '← Email' : '→ Email';
    if (item.type === 'call') return item.direction === 'inbound' ? '← Call' : '→ Call';
    if (item.type === 'note') return 'Note';
    if (item.type === 'task') return item.completed ? '✓ Task' : 'Task';
    if (item.type === 'event') return item.event || 'Event';
    return item.type;
  };

  // Filter tabs include events
  const ACTIVITY_TABS = [['all','All'],['sms','SMS'],['email','Email'],['notes','Notes'],['tasks','Tasks'],['event','Events']];

  return (
    <div className="h-full flex overflow-hidden">
      {/* Contacts List */}
      <div className={`flex flex-col ${activeContact && panelExpanded ? 'hidden' : activeContact ? 'hidden lg:flex lg:w-2/5' : 'flex-1'} overflow-hidden border-r border-slate-800/50`}>
        <div className="p-5 border-b border-slate-800/50">
          <div className="flex items-center justify-between mb-4">
            <div>
              <div className="text-xs mono text-slate-500 uppercase tracking-widest mb-0.5">CRM Directory</div>
              <h2 className="font-black text-white text-2xl italic tracking-tight">Contacts</h2>
            </div>
            <div className="flex items-center gap-2">
              <button onClick={() => setShowContactForm(!showContactForm)}
                className="flex items-center gap-2 px-3 py-2 bg-blue-600 hover:bg-blue-500 rounded-xl text-xs font-bold text-white transition-all">
                <i data-lucide="user-plus" style={{width:13,height:13}} className="inline-block"></i> New
              </button>
              <button onClick={fetchContacts} className="p-2 bg-slate-900/60 border border-slate-800 rounded-xl text-slate-400 hover:text-white transition-colors">
                <i data-lucide="refresh-cw" style={{width:14,height:14}} className="inline-block"></i>
              </button>
            </div>
          </div>
          <div className="relative">
            <i data-lucide="search" style={{width:13,height:13}} className="inline-block absolute left-3 top-1/2 -translate-y-1/2 text-slate-600"></i>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search name, email, phone, tags..."
              className="w-full bg-slate-900/60 border border-slate-800 rounded-xl pl-9 pr-4 py-2 text-xs text-slate-300 outline-none focus:border-blue-500/50 placeholder:text-slate-700" />
          </div>
        </div>

        {showContactForm && (
          <div className="bg-slate-900/60 border-b border-blue-500/20 p-4 fade-in">
            <div className="font-bold text-white text-sm mb-3 flex items-center gap-2">
              <i data-lucide="user-plus" style={{width:14,height:14}} className="inline-block text-blue-400"></i> New Contact
            </div>
            <div className="grid grid-cols-2 gap-2 mb-3">
              {[['firstName','First Name'],['lastName','Last Name'],['email','Email'],['phone','Phone']].map(([k,l]) => (
                <input key={k} value={contactForm[k]} onChange={e => setContactForm(p=>({...p,[k]:e.target.value}))}
                  placeholder={l}
                  className="bg-slate-900/80 border border-slate-700/60 rounded-lg px-3 py-2 text-xs text-white outline-none focus:border-blue-500/50 placeholder:text-slate-700" />
              ))}
            </div>
            <div className="flex justify-end gap-2">
              <button onClick={() => setShowContactForm(false)} className="px-3 py-1.5 text-xs text-slate-500 hover:text-white transition-colors">Cancel</button>
              <button onClick={createContact} className="px-3 py-1.5 bg-blue-600 hover:bg-blue-500 rounded-lg text-xs font-bold text-white transition-all">Create</button>
            </div>
          </div>
        )}

        <div className="flex-1 overflow-y-auto">
          {loadingTabs.contacts ? (
            <div className="flex justify-center py-20"><div className="w-7 h-7 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" /></div>
          ) : (
            <table className="w-full">
              <thead className="sticky top-0 bg-[#0a0f1a] z-10">
                <tr className="border-b border-slate-800/50">
                  {['Contact', 'Email', 'Phone', 'Tags', 'Added'].map((h, i) => (
                    <th key={i} className="text-left px-5 py-3 text-[10px] mono text-slate-600 uppercase tracking-[0.15em] font-bold">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.map(c => (
                  <tr key={c.id} onClick={() => openContact(c)}
                    className={`border-b border-slate-800/30 cursor-pointer transition-colors hover:bg-slate-800/20
                      ${activeContact?.id === c.id ? 'bg-blue-600/5 border-l-2 border-blue-500' : ''}`}>
                    <td className="px-5 py-3.5">
                      <div className="flex items-center gap-3">
                        <Avatar name={c.name} size={32} photo={c.avatar} />
                        <div>
                          <div className="font-bold text-white text-sm">{c.name}</div>
                          {c.source && <div className="text-[10px] text-slate-600">{c.source}</div>}
                        </div>
                      </div>
                    </td>
                    <td className="px-5 py-3.5 text-xs mono text-slate-400 max-w-[180px] truncate">{c.email || '—'}</td>
                    <td className="px-5 py-3.5 text-xs mono text-slate-400">{c.phone || '—'}</td>
                    <td className="px-5 py-3.5">
                      <div className="flex flex-wrap gap-1">
                        {(c.tags || []).slice(0, 2).map((t, i) => (
                          <span key={i} className="text-[10px] mono px-2 py-0.5 rounded-md bg-slate-800 text-slate-400 border border-slate-700/50">{t}</span>
                        ))}
                      </div>
                    </td>
                    <td className="px-5 py-3.5 text-xs mono text-slate-600">{fmtDate(c.createdAt)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
          {!loadingTabs.contacts && filtered.length === 0 && (
            <div className="py-16 text-center text-xs mono text-slate-700 uppercase tracking-widest">
              {contacts.length === 0 ? 'No contacts — click Refresh' : 'No matches'}
            </div>
          )}
        </div>
      </div>

      {/* Contact Detail Panel */}
      {activeContact && (
        <div className={`flex flex-col border-l border-slate-800/50 bg-[#0a0f1a] slide-in-right overflow-hidden ${panelExpanded ? 'flex-1' : ''}`} style={panelExpanded ? {} : {width: 480, minWidth: 400}}>
          <div className="p-5 border-b border-slate-800/50 flex items-start justify-between shrink-0">
            <div className="flex items-center gap-4">
              <Avatar name={activeContact.name} size={48} photo={activeContact.avatar} />
              <div>
                <div className="text-xs mono text-blue-400 uppercase tracking-wider mb-0.5">Contact</div>
                <div className="font-black text-white text-lg italic tracking-tight">{activeContact.name}</div>
                <div className="text-xs text-slate-500">{activeContact.source || 'Direct'}</div>
              </div>
            </div>
            <div className="flex items-center gap-1 shrink-0">
              <button onClick={() => setPanelExpanded(v => !v)} className="p-2 hover:bg-slate-800 rounded-lg transition-colors" title={panelExpanded ? 'Collapse' : 'Expand'}>
                <i data-lucide={panelExpanded ? 'minimize-2' : 'maximize-2'} style={{width:14,height:14}} className="inline-block text-slate-500 hover:text-slate-300"></i>
              </button>
              <button onClick={() => { setActiveContact(null); setPanelExpanded(false); }} className="p-2 hover:bg-slate-800 rounded-lg transition-colors">
                <i data-lucide="x" style={{width:15,height:15}} className="inline-block text-slate-500"></i>
              </button>
            </div>
          </div>

          <div className={`flex-1 overflow-y-auto ${panelExpanded ? 'max-w-4xl mx-auto w-full' : ''}`}>
            {/* Contact info */}
            <div className="p-4 space-y-2 border-b border-slate-800/40">
              {activeContact.email && (
                <a href={`mailto:${activeContact.email}`} className="flex items-center gap-3 text-xs group hover:text-blue-300 transition-colors">
                  <div className="p-2 bg-slate-900/60 rounded-lg shrink-0"><i data-lucide="mail" style={{width:12,height:12}} className="inline-block text-slate-500 group-hover:text-blue-400"></i></div>
                  <span className="mono text-slate-400 group-hover:text-blue-300 truncate">{activeContact.email}</span>
                </a>
              )}
              {activeContact.phone && (
                <a href={`tel:${activeContact.phone}`} className="flex items-center gap-3 text-xs group hover:text-blue-300 transition-colors">
                  <div className="p-2 bg-slate-900/60 rounded-lg shrink-0"><i data-lucide="phone" style={{width:12,height:12}} className="inline-block text-slate-500 group-hover:text-blue-400"></i></div>
                  <span className="mono text-slate-400 group-hover:text-blue-300">{activeContact.phone}</span>
                </a>
              )}
              {(activeContact.tags||[]).length > 0 && (
                <div className="flex items-start gap-3">
                  <div className="p-2 bg-slate-900/60 rounded-lg shrink-0 mt-0.5"><i data-lucide="tag" style={{width:12,height:12}} className="inline-block text-slate-500"></i></div>
                  <div className="flex flex-wrap gap-1 pt-1">
                    {activeContact.tags.map((t,i) => (
                      <span key={i} className="text-[10px] mono px-2 py-0.5 rounded-md bg-blue-600/10 text-blue-400 border border-blue-500/20">{t}</span>
                    ))}
                  </div>
                </div>
              )}
              <div className="text-[10px] mono text-slate-700 pl-1">ID: {activeContact.id}</div>
            </div>

            {/* Send Message */}
            <div className="p-4 border-b border-slate-800/40 space-y-2">
              <div className="text-[10px] mono text-slate-500 uppercase tracking-widest font-bold mb-2">Send Message</div>
              <div className="flex gap-1 mb-2">
                {['SMS', 'Email'].map(t => (
                  <button key={t} onClick={() => setSendType(t)}
                    className={`px-3 py-1 rounded-lg text-xs font-bold mono transition-all ${sendType === t ? 'bg-blue-600 text-white' : 'bg-slate-900/60 border border-slate-800 text-slate-500 hover:text-white'}`}>
                    {t}
                  </button>
                ))}
              </div>
              <textarea value={sendMsg} onChange={e => setSendMsg(e.target.value)}
                placeholder={`Type ${sendType} message...`} rows={3}
                className="w-full bg-slate-900/60 border border-slate-700/60 rounded-xl px-3 py-2.5 text-xs text-white outline-none focus:border-blue-500/50 placeholder:text-slate-700 resize-none" />
              <button onClick={sendMessage} disabled={sending || !sendMsg.trim()}
                className="w-full py-2 bg-blue-600 hover:bg-blue-500 disabled:opacity-40 rounded-xl text-xs font-bold text-white transition-all flex items-center justify-center gap-2">
                <i data-lucide="send" style={{width:12,height:12}} className="inline-block"></i>
                {sending ? 'Sending...' : `Send ${sendType}`}
              </button>
            </div>

            {/* Activity Feed */}
            <div className="p-4 space-y-3">
              <div className="flex items-center justify-between">
                <div className="text-[10px] mono text-slate-500 uppercase tracking-widest font-bold">
                  Activity {activity.length > 0 && <span className="text-slate-700 ml-1">({activity.length})</span>}
                </div>
                <button onClick={() => loadActivity(activeContact.id)} className="p-1 text-slate-600 hover:text-slate-400 transition-colors">
                  <i data-lucide="refresh-cw" style={{width:11,height:11}} className="inline-block"></i>
                </button>
              </div>

              {/* Add note inline */}
              <div className="flex gap-2">
                <input value={noteInput} onChange={e => setNoteInput(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && addContactNote()}
                  placeholder="Add note..."
                  className="flex-1 bg-slate-900/60 border border-slate-700/60 rounded-lg px-3 py-2 text-xs text-white outline-none focus:border-blue-500/50 placeholder:text-slate-700" />
                <button onClick={addContactNote} disabled={!noteInput.trim()} className="px-3 py-2 bg-slate-700 hover:bg-slate-600 disabled:opacity-40 rounded-lg text-xs font-bold text-white transition-colors">Add</button>
              </div>

              {/* Filter tabs */}
              <div className="flex gap-1 flex-wrap">
                {ACTIVITY_TABS.map(([v,l]) => (
                  <button key={v} onClick={() => setActivityTab(v)}
                    className={`px-2.5 py-1 rounded-lg text-[10px] font-bold mono transition-all ${activityTab === v ? 'bg-slate-700 text-white' : 'text-slate-600 hover:text-slate-400'}`}>
                    {l}
                  </button>
                ))}
              </div>

              {/* List */}
              {loadingActivity ? (
                <div className="flex justify-center py-8"><div className="w-5 h-5 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" /></div>
              ) : filteredActivity.length === 0 ? (
                <div className="text-xs mono text-slate-800 text-center py-8">No activity</div>
              ) : (
                <div className="space-y-2">
                  {filteredActivity.map((item, i) => {
                    const cls = activityColors(item.type, item.direction);
                    const icon = activityIcon(item.type);
                    const label = activityLabel(item);
                    return (
                      <div key={item.id || i} className={`border rounded-xl p-3 ${cls}`}>
                        <div className="flex items-start gap-2.5">
                          <i data-lucide={icon} style={{width:12,height:12}} className="inline-block shrink-0 mt-0.5 opacity-70"></i>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center justify-between gap-2 mb-1">
                              <span className="text-[10px] mono font-bold uppercase tracking-wide opacity-60">{label}</span>
                              <span className="text-[10px] mono opacity-40 shrink-0">{fmtDate(item.date)}</span>
                            </div>
                            {item.subject && item.type === 'email' && (
                              <div className="text-[11px] font-bold mb-0.5 truncate opacity-80">{item.subject}</div>
                            )}
                            <div className={`text-xs leading-relaxed opacity-90 whitespace-pre-wrap break-words ${panelExpanded ? '' : 'line-clamp-4'}`}>
                              {item.body || (item.type === 'call' ? '(call — no transcript)' : '(no content)')}
                            </div>
                            {item.meta && (
                              <div className="text-[10px] mono opacity-40 mt-0.5 truncate">{item.meta}</div>
                            )}
                            {item.type === 'task' && (
                              <span className={`text-[10px] mono mt-1 inline-block ${item.completed ? 'text-emerald-400' : 'text-orange-400'}`}>
                                {item.completed ? '✓ Done' : '○ Pending'}
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
