// Ask NalarX — chat / search interface with citations.

const ChatScreen = ({ vertical }) => {
  const V = window.NX_DATA.VERTICALS[vertical];
  const [messages, setMessages] = React.useState([]); // {role, content, citations?, streaming?}
  const [input, setInput] = React.useState('');
  const [scope, setScope] = React.useState('all'); // all|databases|files|messaging
  const inputRef = React.useRef(null);
  const scrollRef = React.useRef(null);

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

  // When vertical changes, clear convo
  React.useEffect(() => { setMessages([]); setInput(''); }, [vertical]);

  const send = (q) => {
    const text = (q ?? input).trim();
    if (!text) return;
    setInput('');
    const userMsg = { role: 'user', content: text };
    const aiMsg = { role: 'ai', content: '', citations: V.citations, streaming: true, lead: V.answerLead, bullets: V.answerBullets };
    setMessages(m => [...m, userMsg, aiMsg]);

    // Simulate streaming
    setTimeout(() => {
      setMessages(m => m.map((msg, i) => i === m.length - 1 ? { ...msg, streaming: false } : msg));
    }, 1800);
  };

  const SourceBadge = ({ kind, source }) => {
    const c = window.NX_DATA.CONNECTORS.find(x => x.name.toLowerCase().includes(source.toLowerCase())) || { tone: 'var(--ink-3)', mono: source.slice(0,2) };
    return <ConnectorTile c={c} size={18} radius={4} />;
  };

  const Citation = ({ cite, idx }) => (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      width: 17, height: 17, borderRadius: 4,
      background: 'var(--accent-soft)',
      color: 'var(--accent-ink)',
      fontSize: 10, fontWeight: 600,
      justifyContent: 'center',
      marginLeft: 4, verticalAlign: 'top', marginTop: 1,
      cursor: 'pointer',
      fontFamily: 'var(--font-mono)',
    }}>{idx}</span>
  );

  return (
    <div className="nx-page" style={{
      height: '100%', display: 'flex', flexDirection: 'column',
      maxWidth: 880, margin: '0 auto',
      width: '100%',
      padding: '0 24px',
    }}>
      {/* Empty state */}
      {messages.length === 0 && (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', paddingBottom: 60 }}>
          <div style={{ textAlign: 'center', marginBottom: 28 }}>
            <div style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: 44, height: 44, borderRadius: 12,
              background: 'var(--accent)',
              marginBottom: 18,
            }}>
              <Icon name="sparkle" size={22} style={{ color: 'white' }} stroke={1.8} />
            </div>
            <h1 style={{
              margin: 0, fontSize: 30, fontWeight: 400,
              letterSpacing: '-0.02em', color: 'var(--ink)',
            }}>
              <span className="nx-serif" style={{ fontStyle: 'italic' }}>Ask anything </span>
              about your {V.short.toLowerCase()} data.
            </h1>
            <div style={{ marginTop: 8, color: 'var(--ink-3)', fontSize: 14 }}>
              NalarX searches across all 18 connected sources, with permissions respected.
            </div>
          </div>

          <ChatComposer
            input={input} setInput={setInput} send={send}
            scope={scope} setScope={setScope}
            example={V.askExample}
            inputRef={inputRef}
          />

          <div style={{ marginTop: 22 }}>
            <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 10, textAlign: 'center' }}>
              Try asking
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
              {V.suggestions.map((q, i) => (
                <button key={i} onClick={() => send(q)}
                  style={{
                    textAlign: 'left', padding: '10px 12px',
                    background: 'var(--bg-elev)',
                    border: '0.5px solid var(--line)',
                    borderRadius: 8, cursor: 'pointer',
                    fontSize: 13, color: 'var(--ink-2)',
                    display: 'flex', alignItems: 'center', gap: 10,
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--line-strong)'; e.currentTarget.style.background = 'var(--bg-hover)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.background = 'var(--bg-elev)'; }}
                >
                  <Icon name="search" size={13} style={{ color: 'var(--ink-4)', flexShrink: 0 }} />
                  <span style={{ flex: 1 }}>{q}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Conversation view */}
      {messages.length > 0 && (
        <>
          <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '24px 0 12px' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
              {messages.map((m, i) => (
                <div key={i}>
                  {m.role === 'user' ? (
                    <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                      <div style={{
                        background: 'var(--ink)', color: 'var(--bg)',
                        padding: '10px 14px', borderRadius: 14, borderBottomRightRadius: 4,
                        fontSize: 14, maxWidth: '78%',
                      }}>{m.content}</div>
                    </div>
                  ) : (
                    <AIMessage msg={m} CitationCmp={Citation} SourceBadge={SourceBadge} />
                  )}
                </div>
              ))}
            </div>
          </div>
          <div style={{ paddingBottom: 20 }}>
            <ChatComposer
              input={input} setInput={setInput} send={send}
              scope={scope} setScope={setScope}
              inputRef={inputRef}
            />
          </div>
        </>
      )}
    </div>
  );
};

const AIMessage = ({ msg, CitationCmp, SourceBadge }) => {
  return (
    <div style={{ display: 'flex', gap: 12 }}>
      <div style={{
        width: 26, height: 26, borderRadius: 7,
        background: 'var(--accent)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <Icon name="sparkle" size={13} style={{ color: 'white' }} stroke={1.8} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        {msg.streaming ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--ink-3)', fontSize: 13.5 }}>
            <Icon name="refresh" size={13} className="nx-spin" />
            <span>Searching across <b style={{ color: 'var(--ink)' }}>18 sources</b>…</span>
            <span className="nx-mono" style={{ color: 'var(--ink-4)', fontSize: 11.5 }}>
              postgres · bigquery · sharepoint · whatsapp · +14
            </span>
          </div>
        ) : (
          <>
            <div style={{ fontSize: 14.5, lineHeight: 1.55, color: 'var(--ink)' }}>
              {msg.lead}
            </div>
            <ul style={{ margin: '12px 0 0', padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
              {msg.bullets.map((b, i) => (
                <li key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                  <div style={{
                    width: 5, height: 5, borderRadius: 50,
                    background: 'var(--ink-4)', marginTop: 9, flexShrink: 0,
                  }} />
                  <span style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--ink-2)' }}>
                    {b.text}
                    <CitationCmp idx={b.cite} />
                  </span>
                </li>
              ))}
            </ul>

            {/* Citations panel */}
            <div style={{ marginTop: 16, padding: 12, background: 'var(--bg-sunken)', borderRadius: 10 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>
                Sources
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {msg.citations.map((c, i) => (
                  <div key={i} style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '7px 9px', background: 'var(--bg-elev)',
                    borderRadius: 7, border: '0.5px solid var(--line)',
                  }}>
                    <div style={{
                      width: 17, height: 17, borderRadius: 4, fontSize: 9.5, fontWeight: 600,
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      background: 'var(--accent-soft)', color: 'var(--accent-ink)',
                      fontFamily: 'var(--font-mono)',
                    }}>{i + 1}</div>
                    <SourceBadge kind={c.kind} source={c.source} />
                    <span style={{ fontSize: 12.5, color: 'var(--ink-2)', flex: 1 }}>{c.label}</span>
                    <Icon name="external" size={12} style={{ color: 'var(--ink-4)' }} />
                  </div>
                ))}
              </div>
            </div>

            <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
              <button className="nx-btn sm ghost" style={{ color: 'var(--ink-3)' }}><Icon name="check" size={12} /> Helpful</button>
              <button className="nx-btn sm ghost" style={{ color: 'var(--ink-3)' }}><Icon name="refresh" size={12} /> Regenerate</button>
              <button className="nx-btn sm ghost" style={{ color: 'var(--ink-3)' }}><Icon name="external" size={12} /> Export</button>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

const ChatComposer = ({ input, setInput, send, scope, setScope, example, inputRef }) => {
  const scopes = [
    { id: 'all',       label: 'All sources' },
    { id: 'databases', label: 'Databases' },
    { id: 'files',     label: 'Files' },
    { id: 'messaging', label: 'Messaging' },
  ];
  return (
    <div style={{
      background: 'var(--bg-elev)',
      border: '0.5px solid var(--line-strong)',
      borderRadius: 14,
      boxShadow: '0 2px 14px rgba(0,0,0,.04)',
    }}>
      <textarea
        ref={inputRef}
        value={input}
        onChange={(e) => setInput(e.target.value)}
        onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        placeholder={example || 'Ask a question, or describe what you\'re looking for…'}
        rows={2}
        style={{
          width: '100%', resize: 'none', border: 0, outline: 'none',
          background: 'transparent',
          padding: '14px 16px 6px',
          fontSize: 14.5, fontFamily: 'inherit',
          color: 'var(--ink)', lineHeight: 1.5,
        }}
      />
      <div style={{
        display: 'flex', alignItems: 'center',
        padding: '8px 10px 10px',
        gap: 6,
      }}>
        <div style={{ display: 'flex', gap: 2, padding: 2, background: 'var(--bg-sunken)', borderRadius: 7 }}>
          {scopes.map(s => (
            <button key={s.id}
              onClick={() => setScope(s.id)}
              style={{
                padding: '4px 9px', height: 22, border: 0, borderRadius: 5,
                background: scope === s.id ? 'var(--bg-elev)' : 'transparent',
                color: scope === s.id ? 'var(--ink)' : 'var(--ink-3)',
                fontSize: 11.5, fontWeight: 500, cursor: 'pointer',
                boxShadow: scope === s.id ? '0 1px 2px rgba(0,0,0,.06)' : 'none',
              }}
            >{s.label}</button>
          ))}
        </div>
        <div style={{ flex: 1 }} />
        <button className="nx-btn ghost sm" style={{ color: 'var(--ink-3)' }}>
          <Icon name="filter" size={12} /> Filters
        </button>
        <button
          onClick={() => send()}
          disabled={!input.trim()}
          className="nx-btn accent sm"
          style={{ height: 28, opacity: input.trim() ? 1 : 0.45, cursor: input.trim() ? 'pointer' : 'not-allowed' }}
        >
          <Icon name="send" size={12} />
          Ask
          <span className="nx-kbd" style={{ background: 'rgba(255,255,255,.2)', color: 'white', borderColor: 'transparent', marginLeft: 2 }}>↵</span>
        </button>
      </div>
    </div>
  );
};

window.ScreenChat = ChatScreen;
