// Team v3 — TeamScreen, AgentInspector, MeetingModal

const TeamScreen = ({ onOpenAgent, onOpenMeeting }) => {
  const [filter, setFilter] = React.useState('all');
  const filtered = AGENTS.filter(a => filter === 'all' ? true : a.cat === filter);
  const filters = [
    { id: 'all',      label: 'Tümü',          n: AGENTS.length },
    { id: 'cos',      label: 'Chief of Staff', n: AGENTS.filter(a=>a.cat==='cos').length },
    { id: 'csuite',   label: 'C-Suite',       n: AGENTS.filter(a=>a.cat==='csuite').length },
    { id: 'director', label: 'Director',      n: AGENTS.filter(a=>a.cat==='director').length },
  ];

  return (
    <div className="fade-in team-v3">
      <div className="team-v3-head">
        <div>
          <h1 className="team-v3-title">Ekibiniz</h1>
          <div className="team-v3-meta">
            <span>15 üye</span>
            <span className="dot-sep">·</span>
            <span><span className="green-dot"></span>hepsi aktif</span>
            <span className="dot-sep">·</span>
            <span>son sentez 12 dk önce</span>
          </div>
        </div>
        <button className="team-v3-cta" onClick={onOpenMeeting}>
          <span className="team-v3-cta-icon">📅</span>
          <span>Toplantı Yap</span>
          <Icon name="chevron" size={14}/>
        </button>
      </div>

      <div className="team-v3-filters">
        {filters.map(f => (
          <button
            key={f.id}
            className={`team-v3-pill ${filter === f.id ? 'active' : ''}`}
            onClick={() => setFilter(f.id)}
          >
            {f.label}
            <span className="team-v3-pill-count">{f.n}</span>
          </button>
        ))}
      </div>

      <div className="team-v3-grid">
        {filtered.map((a, i) => (
          <button
            key={a.id}
            className="team-v3-card"
            style={{ animationDelay: `${i * 28}ms` }}
            onClick={() => onOpenAgent(a)}
          >
            <span className="team-v3-active" title="Aktif">
              <span className="green-dot"></span>
            </span>
            <span className="team-v3-avatar" style={{ background: a.color }}>
              <span className="team-v3-avatar-spec"></span>
              {a.avatar}
            </span>
            <div className="team-v3-card-body">
              <div className="team-v3-role">{a.role}</div>
              <div className="team-v3-name">{a.name}</div>
              <div className="team-v3-desc">{a.desc}</div>
            </div>
            <div className="team-v3-card-foot">
              <span className="team-v3-foot-cta">
                <Icon name="chat" size={14}/>
                <span>Sohbet aç</span>
              </span>
              <Icon name="chevron" size={14} className="team-v3-foot-chev"/>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
};

const AgentInspector = ({ agent, onClose, onPickAgent, onSendExample }) => {
  const [cap, setCap] = React.useState(null);

  React.useEffect(() => {
    if (!agent) { setCap(null); return; }
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);

    // Önce mock'ı göster (anında), sonra backend'den enrich et
    setCap(window.CAPABILITIES?.[agent.id] || null);
    if (window.KW?.online) {
      window.KW.getAgentCapabilities(agent.id).then(real => {
        if (!real) return;
        // Backend shape → UI shape
        setCap({
          pitch: real.pitch || real.headline || '',
          headline: real.headline,
          useFor: real.useFor || [],
          examples: real.examples || [],
        });
      }).catch(() => {});
    }

    return () => window.removeEventListener('keydown', onKey);
  }, [agent, onClose]);
  return (
    <>
      <div className={`agent-overlay ${agent ? 'open' : ''}`} onClick={onClose}></div>
      <aside className={`agent-inspector ${agent ? 'open' : ''}`}>
        {agent && cap && (
          <>
            <div className="agent-insp-head">
              <div className="agent-insp-id">
                <span className="agent-insp-avatar" style={{ background: agent.color }}>
                  <span className="team-v3-avatar-spec"></span>
                  {agent.avatar}
                </span>
                <span className="agent-insp-active"><span className="green-dot"></span>Aktif şimdi</span>
              </div>
              <button className="agent-insp-close" onClick={onClose} aria-label="Kapat">
                <Icon name="x" size={16}/>
              </button>
            </div>

            <div className="agent-insp-body">
              <div className="agent-insp-stagger" style={{ animationDelay: '60ms' }}>
                <div className="agent-insp-role">{agent.role}</div>
                <h2 className="agent-insp-name">{agent.name}</h2>
                <div className="agent-insp-sub">{agent.desc}</div>
              </div>

              <div className="agent-insp-pitch agent-insp-stagger" style={{ animationDelay: '140ms' }}>
                {cap.pitch}
              </div>

              <div className="agent-insp-stagger" style={{ animationDelay: '220ms' }}>
                <div className="agent-insp-label">Hangi konularda faydalı</div>
                <ul className="agent-insp-uses">
                  {cap.useFor.map((u, i) => (
                    <li key={i}>
                      <span className="agent-insp-check"><Icon name="check" size={11}/></span>
                      <span>{u}</span>
                    </li>
                  ))}
                </ul>
              </div>

              <div className="agent-insp-stagger" style={{ animationDelay: '300ms' }}>
                <div className="agent-insp-label">Örnek sorular</div>
                <div className="agent-insp-examples">
                  {cap.examples.map((ex, i) => (
                    <button key={i} className="agent-insp-example" onClick={() => onSendExample(agent, ex)}>
                      <span>{ex}</span>
                      <Icon name="arrow-up" size={13} className="agent-insp-ex-arrow"/>
                    </button>
                  ))}
                </div>
              </div>
            </div>

            <div className="agent-insp-foot">
              <button className="agent-insp-primary" onClick={() => onPickAgent(agent)}>
                <Icon name="chat" size={15}/>
                <span>{agent.name} ile sohbete başla</span>
                <Icon name="arrow-up" size={13} style={{ transform: 'rotate(90deg)' }}/>
              </button>
            </div>
          </>
        )}
      </aside>
    </>
  );
};

const MeetingModal = ({ open, onClose, onStart }) => {
  const [filter, setFilter] = React.useState('all');
  const [selected, setSelected] = React.useState(null);
  const [customTopic, setCustomTopic] = React.useState('');
  const [routing, setRouting] = React.useState(false);
  const [routedAgents, setRoutedAgents] = React.useState(null);
  const [routedTopic, setRoutedTopic] = React.useState(null);
  const [tplData, setTplData] = React.useState(null);  // { templates, categories } from backend

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  // Backend templates (gerçek), yoksa mock
  React.useEffect(() => {
    if (!open) return;
    if (window.KW?.online) {
      window.KW.listMeetingTemplates().then(data => {
        if (!data?.templates?.length) return;
        // Backend shape → UI shape
        const adapted = data.templates.map(t => ({
          id: t.id,
          title: t.title,
          desc: t.description || '',
          icon: t.icon || '📅',
          cat: t.category,
          agents: t.agents || [],
          dur: t.estimatedMinutes ? `${t.estimatedMinutes} dk` : '—',
          prompt: t.prompt,
        }));
        setTplData({
          templates: adapted,
          categories: [{ id: 'all', label: 'Tümü', icon: '◎' }, ...(data.categories || [])],
        });
      }).catch(() => {});
    }
  }, [open]);

  React.useEffect(() => {
    if (!open) {
      setTimeout(() => {
        setFilter('all'); setSelected(null); setCustomTopic(''); setRouting(false); setRoutedAgents(null); setRoutedTopic(null);
      }, 320);
    }
  }, [open]);

  if (!open) return null;

  // Veri kaynağı: backend templates varsa onu, yoksa mock
  const allTemplates = tplData?.templates || (window.MEETING_TEMPLATES || []);
  const allCategories = tplData?.categories || (window.MEETING_CATEGORIES || []);
  const templates = allTemplates.filter(t => filter === 'all' ? true : t.cat === filter);
  const isCustom = customTopic.trim().length > 0 && !selected;
  const selectedTemplate = selected ? allTemplates.find(t => t.id === selected) : null;

  const previewAgents = selectedTemplate
    ? selectedTemplate.agents
    : routedAgents || (isCustom && window.routeCustomTopic ? window.routeCustomTopic(customTopic) : null);

  const handleTemplate = (id) => {
    setSelected(id);
    setCustomTopic('');
    setRoutedAgents(null);
  };

  const handleCustomChange = (val) => {
    setCustomTopic(val);
    if (val.trim().length > 0) {
      setSelected(null);
      setRoutedAgents(null);
    }
  };

  const handleStart = async () => {
    if (selectedTemplate) {
      onStart({
        topic: selectedTemplate.title,
        agents: selectedTemplate.agents,
        message: selectedTemplate.prompt || selectedTemplate.desc,
      });
      return;
    }
    if (!isCustom) return;
    setRouting(true);
    try {
      // Backend AI router
      if (window.KW?.online) {
        const r = await window.KW.routeCustomMeeting(customTopic);
        setRoutedAgents(r.agents);
        setRoutedTopic(r.topic);
        setTimeout(() => {
          onStart({ topic: r.topic || customTopic, agents: r.agents, message: customTopic });
        }, 900);
      } else if (window.routeCustomTopic) {
        // Offline fallback
        const ids = window.routeCustomTopic(customTopic);
        setRoutedAgents(ids);
        setTimeout(() => {
          onStart({ topic: customTopic, agents: ids, message: customTopic });
        }, 900);
      }
    } catch (e) {
      alert('Toplantı oluşturulamadı: ' + e.message);
    } finally {
      setRouting(false);
    }
  };

  const canStart = (selectedTemplate || isCustom) && !routing;

  return (
    <div className="mm-overlay" onClick={onClose}>
      <div className="mm-card" onClick={e => e.stopPropagation()}>
        <button className="mm-close" onClick={onClose}><Icon name="x" size={16}/></button>
        <div className="mm-card-spec"></div>

        <div className="mm-head">
          <span className="mm-emoji">📅</span>
          <h2 className="mm-title">Toplantı yapmak istediğiniz konu nedir?</h2>
          <div className="mm-sub">
            Bir şablon seçin ya da kendi konunuzu yazın — ekibiniz otomatik toplanır,
            Managing Partner sentezi getirir.
          </div>
        </div>

        <div className="mm-divider"></div>

        <div className="mm-section">
          <div className="mm-label">Kategori</div>
          <div className="mm-cats">
            {allCategories.map(c => (
              <button
                key={c.id}
                className={`mm-cat ${filter === c.id ? 'active' : ''}`}
                onClick={() => setFilter(c.id)}
                disabled={isCustom}
              >
                <span className="mm-cat-icon">{c.icon}</span>
                <span>{c.label}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="mm-section">
          <div className="mm-label-row">
            <div className="mm-label">Şablonlar</div>
            <span className="mm-count">{templates.length}</span>
          </div>
          <div className={`mm-templates ${isCustom ? 'dimmed' : ''}`}>
            {templates.map(t => {
              const isSel = selected === t.id;
              return (
                <button
                  key={t.id}
                  className={`mm-tpl ${isSel ? 'selected' : ''}`}
                  onClick={() => handleTemplate(t.id)}
                  disabled={isCustom}
                >
                  <span className="mm-tpl-icon">{t.icon}</span>
                  <span className="mm-tpl-body">
                    <span className="mm-tpl-title">{t.title}</span>
                    <span className="mm-tpl-desc">{t.desc}</span>
                    <span className="mm-tpl-meta">
                      <span>⌛ {t.dur}</span>
                      <span className="dot-sep">·</span>
                      <span>{t.agents.length} kişi katılır</span>
                    </span>
                  </span>
                  {isSel && <span className="mm-tpl-check"><Icon name="check" size={12}/></span>}
                </button>
              );
            })}
          </div>
        </div>

        <div className="mm-divider"></div>

        <div className="mm-section">
          <div className="mm-label">✏️ Kendi konunuzu yazın</div>
          <textarea
            className={`mm-textarea ${isCustom ? 'active' : ''}`}
            placeholder='örn: "Forbes röportajı için ne soracaklar — basın, KW imajımız, EB-1A hikayemi nasıl konumlandırırım"'
            value={customTopic}
            onChange={e => handleCustomChange(e.target.value)}
            rows={3}
          />
          <div className="mm-helper">
            💡 Custom konu seçtiğinizde, hangi rollerin dahil edileceğini ekibiniz analiz edip seçer.
          </div>
        </div>

        {(selectedTemplate || isCustom || routing) && (
          <div className="mm-preview">
            <div className="mm-preview-head">
              {routing ? (
                <span className="mm-preview-loading">
                  <span className="mm-pulse"></span>
                  Konuyu analiz ediyorum…
                </span>
              ) : (
                <>
                  <span className="mm-preview-icon">{selectedTemplate ? selectedTemplate.icon : '✏️'}</span>
                  <span className="mm-preview-topic">
                    {selectedTemplate ? selectedTemplate.title : customTopic}
                  </span>
                </>
              )}
            </div>
            {!routing && previewAgents && (
              <div className="mm-preview-agents">
                <span className="mm-preview-label">Katılacak:</span>
                <span className="mm-preview-stack">
                  {previewAgents.map((id, i) => {
                    const a = AGENTS.find(x => x.id === id);
                    if (!a) return null;
                    return (
                      <span
                        key={id}
                        className="mm-preview-avatar"
                        style={{ background: a.color, animationDelay: `${i * 60}ms` }}
                        title={a.name}
                      >
                        {a.avatar}
                      </span>
                    );
                  })}
                </span>
                <span className="mm-preview-names">
                  {previewAgents.map(id => AGENTS.find(x => x.id === id)?.role).filter(Boolean).join(' · ')}
                </span>
              </div>
            )}
            {!routing && selectedTemplate && (
              <div className="mm-preview-dur">Tahmini: {selectedTemplate.dur}</div>
            )}
          </div>
        )}

        <button
          className="mm-primary"
          onClick={handleStart}
          disabled={!canStart}
        >
          {routing ? (
            <>
              <span className="mm-spinner"></span>
              <span>Hazırlanıyor…</span>
            </>
          ) : (
            <>
              <span>Toplantıyı Başlat</span>
              <Icon name="arrow-up" size={14} style={{ transform: 'rotate(90deg)' }}/>
            </>
          )}
        </button>
      </div>
    </div>
  );
};

window.TeamScreen = TeamScreen;
window.AgentInspector = AgentInspector;
window.MeetingModal = MeetingModal;
