/* global React, Icon, Btn, Logo, Avatar, SUGGESTED */
// Taxai — Chat AI interface (Claude-style, light). Presentational; logic lives in App.
const { useState: useChatState, useRef: useChatRef, useEffect: useChatEffect } = React;

function Chat({ messages, pending, profile, tweaks, onSend, onBook, onNewChat, convos, activeConvo, setActiveConvo }) {
  const [draft, setDraft] = useChatState('');
  const scrollRef = useChatRef(null);
  const taRef = useChatRef(null);
  const empty = messages.length === 0;

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

  const send = (text) => {
    const t = (text != null ? text : draft).trim();
    if (!t || pending) return;
    onSend(t);
    setDraft('');
    if (taRef.current) taRef.current.style.height = 'auto';
  };

  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
  };
  const grow = (e) => { const el = e.target; el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 200) + 'px'; setDraft(el.value); };

  return (
    <div style={{ display: 'flex', height: '100%', background: 'var(--bg-1)' }}>
      <ChatSidebar profile={profile} onNewChat={onNewChat} convos={convos} activeConvo={activeConvo} setActiveConvo={setActiveConvo} onBook={onBook} />

      {/* main column */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', height: '100%', minWidth: 0 }}>
        <ChatTopbar profile={profile} />

        <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto' }}>
          {empty ? (
            <EmptyState profile={profile} onPick={send} tweaks={tweaks} />
          ) : (
            <div style={{ maxWidth: 760, margin: '0 auto', padding: '28px 24px 40px' }}>
              {messages.map((m, i) => (
                <Message key={i} msg={m} tweaks={tweaks} profile={profile} onBook={onBook} />
              ))}
              {pending && <TypingRow tweaks={tweaks} />}
            </div>
          )}
        </div>

        {/* composer */}
        <div style={{ borderTop: '1px solid var(--border-1)', background: 'var(--bg-1)', padding: '14px 24px 18px' }}>
          <div style={{ maxWidth: 760, margin: '0 auto' }}>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10, background: 'var(--surface)', border: '1px solid var(--border-2)', borderRadius: 'var(--r-lg)', padding: '10px 12px 10px 16px', boxShadow: 'var(--shadow-sm)' }}>
              <textarea ref={taRef} value={draft} onChange={grow} onKeyDown={onKey} rows={1}
                placeholder="Hỏi Taxai về thuế, hóa đơn, đăng ký kinh doanh…"
                style={{ flex: 1, border: 0, outline: 0, resize: 'none', background: 'transparent', fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.5, color: 'var(--fg-1)', maxHeight: 200, padding: '6px 0' }} />
              <button onClick={() => send()} disabled={!draft.trim() || pending} title="Gửi" style={{
                width: 38, height: 38, borderRadius: 'var(--r-md)', border: 0, flexShrink: 0, cursor: draft.trim() && !pending ? 'pointer' : 'not-allowed',
                background: draft.trim() && !pending ? 'var(--brand)' : 'var(--ink-100)', color: draft.trim() && !pending ? '#fff' : 'var(--ink-400)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', transition: 'all var(--dur)',
              }}>
                <Icon name="arrow-up" size={19} />
              </button>
            </div>
            <div style={{ textAlign: 'center', fontSize: 11.5, color: 'var(--fg-3)', marginTop: 9 }}>
              Taxai có thể sai sót. Với quyết định quan trọng,{' '}
              <button onClick={() => onBook('tax')} style={{ border: 0, background: 'none', padding: 0, font: 'inherit', fontSize: 11.5, fontWeight: 700, color: 'var(--brand)', cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 2 }}>hãy tham khảo chuyên gia</button>.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- Sidebar -------------------------------------------------------------
function ChatSidebar({ profile, onNewChat, convos, activeConvo, setActiveConvo, onBook }) {
  return (
    <div className="adflex-dark" style={{ width: 252, flexShrink: 0, background: 'var(--ink-950)', borderRight: '1px solid var(--ink-800)', display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ padding: '16px 16px 12px', display: 'flex', alignItems: 'center', gap: 9 }}>
        <Logo size={21} light />
        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.1em', color: 'var(--ink-500)', textTransform: 'uppercase', border: '1px solid var(--ink-700)', borderRadius: 4, padding: '2px 5px' }}>AI</span>
      </div>
      <div style={{ padding: '4px 12px 12px' }}>
        <button onClick={onNewChat} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 9, padding: '10px 12px', borderRadius: 'var(--r-md)', border: '1px solid var(--ink-700)', background: 'rgba(255,255,255,.03)', color: '#fff', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, cursor: 'pointer', transition: 'all var(--dur)' }}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(221,16,0,.16)'; e.currentTarget.style.borderColor = 'var(--brand)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,.03)'; e.currentTarget.style.borderColor = 'var(--ink-700)'; }}>
          <Icon name="plus" size={17} /> Cuộc trò chuyện mới
        </button>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '4px 8px' }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.1em', color: 'var(--ink-500)', textTransform: 'uppercase', padding: '8px 10px 6px' }}>Gần đây</div>
        {convos.map((c) => (
          <button key={c.id} onClick={() => setActiveConvo(c.id)} style={{
            width: '100%', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 9, padding: '9px 10px', borderRadius: 'var(--r-sm)',
            border: 0, background: activeConvo === c.id ? 'rgba(255,255,255,.06)' : 'transparent', color: activeConvo === c.id ? '#fff' : 'var(--ink-300)',
            fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13.5, cursor: 'pointer', boxShadow: activeConvo === c.id ? 'inset 2px 0 0 var(--brand)' : 'none',
          }}>
            <Icon name="message-square" size={15} style={{ flexShrink: 0, opacity: .8 }} />
            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.title}</span>
          </button>
        ))}
      </div>
      {/* booking shortcut */}
      <div style={{ padding: '10px 12px' }}>
        <button onClick={() => onBook('tax')} style={{ display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer', borderRadius: 'var(--r-md)', border: '1px solid var(--ink-800)', background: 'rgba(255,255,255,.02)', padding: 12, transition: 'all var(--dur)' }}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(221,16,0,.12)'; e.currentTarget.style.borderColor = 'var(--brand)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,.02)'; e.currentTarget.style.borderColor = 'var(--ink-800)'; }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: '#fff', fontWeight: 700, fontSize: 13 }}>
              <Icon name="calendar-check" size={15} color="var(--red-300)" /> Cần tư vấn chuyên sâu?
            </div>
            <Icon name="arrow-right" size={15} color="var(--ink-400)" />
          </div>
          <div style={{ color: 'var(--ink-400)', fontSize: 12, marginTop: 5, lineHeight: 1.45 }}>Đặt lịch 1-1 với chuyên gia thuế & thành lập DN.</div>
        </button>
      </div>
      {/* profile */}
      <div style={{ borderTop: '1px solid var(--ink-800)', padding: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
        <Avatar name={profile.name || 'Bạn'} size={34} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ color: '#fff', fontWeight: 700, fontSize: 13.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{profile.name || 'Khách'}</div>
          <div style={{ color: 'var(--ink-500)', fontSize: 11.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{profileLabel(profile)}</div>
        </div>
        <Icon name="settings" size={16} color="var(--ink-400)" />
      </div>
    </div>
  );
}

function profileLabel(p) {
  const map = { registered: 'Đã đăng ký HKD/DN', unregistered: 'Chưa đăng ký HKD/DN' };
  return map[p.type] || 'Chưa thiết lập';
}

// ---- Topbar --------------------------------------------------------------
function ChatTopbar({ profile }) {
  return (
    <div style={{ height: 58, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 24px', borderBottom: '1px solid var(--border-1)', background: 'rgba(255,255,255,.8)', backdropFilter: 'blur(12px)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16 }}>Trợ lý thuế</div>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 700, color: 'var(--success)', background: 'var(--success-bg)', padding: '3px 9px', borderRadius: 999, whiteSpace: 'nowrap' }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--success)' }} /> Trực tuyến
        </span>
      </div>
      {profile.type && (
        <div className="af" style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--fg-2)', fontWeight: 600, background: 'var(--bg-2)', border: '1px solid var(--border-1)', padding: '6px 12px', borderRadius: 999 }}>
          <Icon name="badge-check" size={15} color="var(--brand)" />
          Hồ sơ: <strong style={{ color: 'var(--fg-1)' }}>{profileLabel(profile)}</strong>
          {profile.industry && <span style={{ color: 'var(--fg-3)' }}>· {profile.industry}</span>}
        </div>
      )}
    </div>
  );
}

// ---- Empty state ---------------------------------------------------------
function EmptyState({ profile, onPick, tweaks }) {
  const name = profile.name ? profile.name.split(' ').slice(-1)[0] : 'bạn';
  return (
    <div style={{ maxWidth: 720, margin: '0 auto', padding: '64px 24px 40px', textAlign: 'center' }}>
      <div style={{ width: 60, height: 60, borderRadius: 'var(--r-lg)', background: 'var(--ink-950)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 22, boxShadow: 'var(--shadow-brand)' }}>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 26, color: '#fff' }}>T<span style={{ color: 'var(--red-400)' }}>a</span></span>
      </div>
      <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 30, letterSpacing: '-.02em', margin: 0 }}>Chào {name}, mình giúp gì về thuế?</h1>
      <p style={{ color: 'var(--fg-2)', fontSize: 15.5, marginTop: 10, maxWidth: 480, marginInline: 'auto', lineHeight: 1.6 }}>
        Hỏi bất cứ điều gì về kê khai, hóa đơn, hay đăng ký kinh doanh. Câu nào quá phức tạp, mình sẽ kết nối bạn với chuyên gia.
      </p>
      {tweaks.showSuggestions && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 32, textAlign: 'left' }}>
          {SUGGESTED.map((s) => (
            <button key={s.id} onClick={() => onPick(s.text)} className="af-card--hover" style={{
              display: 'flex', gap: 12, alignItems: 'flex-start', textAlign: 'left', cursor: 'pointer',
              background: 'var(--surface)', border: '1px solid var(--border-1)', borderRadius: 'var(--r-md)', padding: '15px 16px', boxShadow: 'var(--shadow-sm)', transition: 'all var(--dur)',
            }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--border-2)'; e.currentTarget.style.boxShadow = 'var(--shadow-md)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border-1)'; e.currentTarget.style.boxShadow = 'var(--shadow-sm)'; }}>
              <span style={{ width: 32, height: 32, borderRadius: 'var(--r-sm)', background: 'var(--red-50)', color: 'var(--brand)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={s.icon} size={17} />
              </span>
              <span style={{ fontSize: 14, lineHeight: 1.45, color: 'var(--fg-1)', fontWeight: 500 }}>{s.text}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

window.Chat = Chat;
