const CHANNELS = ['announcements', 'general', 'mentor-chat'];
const CHANNEL_LABELS = {
  'announcements': 'Announcements',
  'general': 'General',
  'mentor-chat': 'Mentor Chat',
};

const MOCK_MESSAGES = {
  announcements: [
    { sender: 'Ayani', time: '09:00', text: 'Welcome to the Ayani community channel. This is a read-only space for official updates.' },
    { sender: 'Ayani', time: '09:05', text: 'Module 302 is now available. Head to the menu to enrol.' },
    { sender: 'Ayani', time: 'Yesterday', text: 'Scheduled maintenance completed. All systems are nominal.' },
  ],
  general: [
    { sender: 'Maya', time: '10:12', text: 'Anyone else on module 301 phase 2?' },
    { sender: 'Jordan', time: '10:14', text: 'Yeah, just finished it — really solid breakdown of the fundamentals.' },
    { sender: 'Maya', time: '10:15', text: 'Agreed. I had to pause and take notes halfway through.' },
    { sender: 'Jordan', time: '10:18', text: 'Same here. Onto the next one.' },
  ],
  'mentor-chat': [
    { sender: 'Mentor', time: '08:45', text: 'Morning everyone — drop any questions from this week here.' },
    { sender: 'Sam', time: '08:46', text: 'Thanks! Had a query on the module 301 worksheet.' },
    { sender: 'Mentor', time: '08:47', text: 'Go ahead, happy to walk through it.' },
    { sender: 'Sam', time: '09:02', text: 'Perfect, sending it over now.' },
  ],
};

function ChatScreen({ onExit, initialChannel }) {
  const ticketKey = initialChannel && !CHANNELS.includes(initialChannel) ? initialChannel : null;
  const ticketLabel = ticketKey
    ? 'Support Ticket #' + ticketKey.replace('support-ticket-', '')
    : null;

  const channels = ticketKey ? [...CHANNELS, ticketKey] : CHANNELS;
  const channelLabels = ticketKey
    ? { ...CHANNEL_LABELS, [ticketKey]: ticketLabel }
    : CHANNEL_LABELS;

  const now = new Date();
  const nowTime = now.getHours().toString().padStart(2, '0') + ':' + now.getMinutes().toString().padStart(2, '0');
  const initialMessages = ticketKey
    ? { ...MOCK_MESSAGES, [ticketKey]: [{ sender: 'Ayani', time: nowTime, text: `${ticketLabel} opened. A team member will be with you shortly.` }] }
    : MOCK_MESSAGES;

  const [activeChannel, setActiveChannel] = React.useState(initialChannel || 'announcements');
  const [messages, setMessages] = React.useState(initialMessages);
  const [draft, setDraft] = React.useState('');
  const bottomRef = React.useRef(null);

  React.useEffect(() => {
    if (bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, activeChannel]);

  function handleSend() {
    const text = draft.trim();
    if (!text) return;
    const now = new Date();
    const time = now.getHours().toString().padStart(2, '0') + ':' + now.getMinutes().toString().padStart(2, '0');
    setMessages(prev => ({
      ...prev,
      [activeChannel]: [...prev[activeChannel], { sender: 'You', time, text }],
    }));
    setDraft('');
  }

  function handleKeyDown(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  }

  const isAnnouncements = activeChannel === 'announcements';

  return (
    <div className="chat-screen">
      <div className="chat-sidebar">
        <div className="chat-sidebar-label">Channels</div>
        {channels.map(ch => (
          <div
            key={ch}
            className={`chat-channel-item ${ch === activeChannel ? 'is-active' : ''}`}
            onClick={() => setActiveChannel(ch)}
          >
            <span className="chat-channel-hash">#</span>
            {channelLabels[ch]}
          </div>
        ))}
      </div>

      <div className="chat-main">
        <div className="chat-main-header">
          <span className="chat-main-header-hash">#</span>
          <span className="chat-main-header-name">{channelLabels[activeChannel]}</span>
        </div>

        <div className="chat-messages">
          {messages[activeChannel].map((msg, i) => (
            <div key={i} className={`chat-message ${msg.sender === 'You' ? 'is-you' : ''}`}>
              <div className="chat-message-meta">
                <span className="chat-message-sender">{msg.sender}</span>
                <span className="chat-message-time">{msg.time}</span>
              </div>
              <div className="chat-message-text">{msg.text}</div>
            </div>
          ))}
          <div ref={bottomRef} />
        </div>

        {isAnnouncements ? (
          <div className="chat-announcements-notice">Read only</div>
        ) : (
          <div className="chat-input-row">
            <input
              className="chat-input"
              type="text"
              placeholder={`Message #${channelLabels[activeChannel].toLowerCase()}…`}
              value={draft}
              onChange={e => setDraft(e.target.value)}
              onKeyDown={handleKeyDown}
            />
            <button className="ay-btn" onClick={handleSend}>Send</button>
          </div>
        )}
      </div>

      <button className="ay-btn chat-exit" onClick={onExit}>Exit</button>
    </div>
  );
}
window.ChatScreen = ChatScreen;
