import React from "react";
import ReactDOM from "react-dom";
import { useEffect, useRef } from "react";

import PropTypes from "prop-types";

import axios from "axios";
import qs from "qs"; //post to php w/o file_get_contents('php://input');

import {
  Button,
  ButtonGroup,
  Checkbox,
  Form,
  FormGroup,
  Input,
  Message,
  Label,
  Icon,
  TextArea,
  Dropdown,
  Loader,
  Header,
  Modal,
  Divider,
  Segment,
  Select,
  Table,
  Flag
} from "semantic-ui-react";

import Linkify from "linkify-react";

import ChatHistory from "../components/ChatHistory";
import SupportFields from "../components/SupportFields";

import Recorder from '../components/Recorder';
import Uploads from '../components/Uploads';
import { trackConfiguredSupportEvent } from "../analytics";

//emoji
import data from "@emoji-mart/data";
import { Picker } from "emoji-mart";

import { checkText } from "smile2emoji";
import { max } from "lodash";

function EmojiPicker(props) {
  const ref = useRef();

  useEffect(() => {
    new Picker({ ...props, data, ref });
  }, []);

  return <div ref={ref} />;
}

export default class Ticket extends React.Component {
  static propTypes = {
    appState: PropTypes.object.isRequired,
    appStateUpdate: PropTypes.func.isRequired,
    callURL: PropTypes.string.isRequired,
  };

  constructor(props) {
    super(props);

    this.devMode = props.appState.devMode;

    this.serverCalled = false;
    this.timerStarted = false;
    this.updateRetryCount = 0;

    this.axiosConfig = {
      withCredentials: true,
      credentials: "include",
      timeout: 20000,
      headers: {
        Accept: "application/json",
        "Content-Type": "multipart/form-data",
        "X-WP-Nonce": props.appState.session.nonce,
      },
    };
   
    this.state = {
      representative: false,
      fields: {},
      name: "",
      email: "",
      message: "",
      department: 0,
      departmentOptions: [],
      departmentEdit: false,
      departmentEditValue: 0,
      departmentSaving: false,
      messages: [],
      contacts: [],
      agree: false,
      validated: false,
      validationInfo: "",
      created: false,
      loaded: false,
      loading: false,
      info: "",
      trackedEvents: {},
      url: "",
      meta: [],
      emojiModalShow: false,
      recordModalShow: false,
      uploadModalShow: false,
      languageModalShow: false,
      canModalShow: false,
  
      openContact: 0,
      contactModalShow: false,
    
      contactAddModalShow: false,
      tagAddModalShow: false,
   
      messageModalShow: false,
      messageEditModalShow: false,
      messageEditID: 0,
      messageEditText: '',
      messageEditSaving: false,
      wikiModalShow: false,
      wikiSearch: '',
      wikiItems: [],
      wikiLoading: false,
      wikiError: '',

      contactType: 'email',
      contactRole: 'client',
      contactName: '',
      contactContact: '',

      autosaveEnabled: true,
      drafts: [],
      savingDraft: false,
      loadingType: '',
      error: '',
      timedOut: false,
      lastFailedRequest: '',
      unreadMessageCount: 0,
      canScrollUp: false,
      canScrollDown: false,
    };

    this.layContent = null;
    this.setLayContentRef = this.setLayContentRef.bind(this); // Binding this to the method

    this.messageIDs = new Set();
    this.messagesLoaded = false;
    this.pendingScrollToBottom = false;

    this.autosaveTimer = null;
    this.lastAutosavedMessage = null; // tracks last content sent to draft endpoint
    this.draftLoaded = false;         // ensures draft is only pre-filled once
    this.lastRequestType = '';
    this.pendingSubmitMessage = '';
  }

  getErrorInfo(error) {
    const timedOut =
      error?.code === "ECONNABORTED" ||
      String(error?.message || "")
        .toLowerCase()
        .includes("timeout");

    return {
      timedOut,
      message: timedOut
        ? this.txt("Connection timed out. Please retry.")
        : error?.response?.data?.info ||
          error?.message ||
          this.txt("Could not connect to server. Please retry."),
    };
  }

  startRequest = (requestType) => {
    this.lastRequestType = requestType;
    this.setState({
      loading: true,
      loadingType: requestType,
      error: '',
      timedOut: false,
      lastFailedRequest: '',
    });
  }

  retryLastRequest = () => {
    const { state } = this;

    if (state.lastFailedRequest === 'submit') {
      this.serverSubmit();
      return;
    }

    this.serverUpdate();
  }

  onChange = (event, data) => {
    var value = data.type === "checkbox" ? data.checked : data.value;
    const name = data.name;

    //	if (this.devMode) console.log('VideoWhisper/screens/Ticket onChange', name, value, event);

    if (name == "message" || name == "messageLong") value = checkText(value);

    this.setState(
      {
        [name]: value,
      },
      () => this.validation()
    ); //validate AFTER
  };

  validation() {
    //validation
    const { state } = this;

    var valid = true;
    let validationInfo = "";

    if (!state.created) {
      if (!this.state.agree) 
      {
        valid = false;
        validationInfo = this.txt("Agree to Terms and Conditions (check box) to Send.") + " ";
      }

      if (!this.state.department) 
      {
        valid = false;
        validationInfo = this.txt("Select a Department to Open conversation with.") + " ";
      }
    }

    if (!this.state.message.length) 
    {
      valid = false;
      validationInfo = this.txt("Write a message to Send.") + " ";
    }

    if (valid !== state.validated || validationInfo !== state.validationInfo) this.setState({ validated: valid, validationInfo: validationInfo });

    //if (this.devMode) console.log('VideoWhisper/screens/Ticket validation', state.created, state.message.length, valid, state.validated);
  }

  componentDidMount() {
    if (!this.state.department && this.props.appState.config.departmentDefault)
      this.setState({
        department: this.props.appState.config.departmentDefault,
      });

    if (this.devMode) console.log('VideoWhisper/screens/Ticket componentDidMount', {
      ticket_id: this.props.appState.ticket_id,
      contact_id: this.props.appState.contact_id,
      pin: this.props.appState.pin ? '***' : '',
      rep: this.props.appState.rep ? '***' : '',
      confirm: this.props.appState.confirm ? '***' : '',
      isNewConversation: !this.props.appState.ticket_id,
    });

  }

  componentDidUpdate() {
    if (this.pendingScrollToBottom) {
      this.pendingScrollToBottom = false;
      window.requestAnimationFrame(() => this.scrollToBottom());
    }
    this.updateConversationScrollState();
    if (this.state.created && !this.autosaveTimer) this.autosaveStart();
  }

  componentWillUnmount() {
    this.timerStop();
    if (this.layContent) this.layContent.removeEventListener('scroll', this.onConversationScroll);
    if (this.autosaveTimer) {
      clearInterval(this.autosaveTimer);
      this.autosaveTimer = null;
    }
  }

 setLayContentRef(element) {
    if (this.layContent === element) return;

    if (this.layContent) this.layContent.removeEventListener('scroll', this.onConversationScroll);
    this.layContent = element;
    if (this.layContent) {
      this.layContent.addEventListener('scroll', this.onConversationScroll, { passive: true });
      this.updateConversationScrollState();
    }
    if (this.devMode) console.log('components/screens/Ticket setlayContentRef', this.layContent);
};

  getConversationScrollState = () => {
    if (!this.layContent) return { canScrollUp: false, canScrollDown: false };

    const { scrollTop, scrollHeight, clientHeight } = this.layContent;
    const maxScrollTop = Math.max(0, scrollHeight - clientHeight);

    return {
      canScrollUp: scrollTop > 1,
      canScrollDown: maxScrollTop - scrollTop > 1,
    };
  };

  updateConversationScrollState = () => {
    const next = this.getConversationScrollState();
    const atBottom = !next.canScrollDown;

    if (
      next.canScrollUp !== this.state.canScrollUp ||
      next.canScrollDown !== this.state.canScrollDown ||
      (atBottom && this.state.unreadMessageCount)
    ) {
      this.setState((state) => ({
        ...next,
        unreadMessageCount: atBottom ? 0 : state.unreadMessageCount,
      }));
    }
  };

  onConversationScroll = () => {
    this.updateConversationScrollState();
  };

  requestScrollToBottom = () => {
    this.pendingScrollToBottom = true;
  };

  scrollToTop = () => {
    if (!this.layContent) return;
    this.layContent.scrollTop = 0;
    this.updateConversationScrollState();
  };

  scrollToBottom = () => {
    const { layContent } = this;
    if (!layContent) return;
    layContent.scrollTop = Math.max(0, layContent.scrollHeight - layContent.clientHeight);
    this.updateConversationScrollState();

    if (this.devMode) console.log('components/screens/Ticket scrollToBottom', layContent);
  };

  showNewMessages = () => {
    this.requestScrollToBottom();
    this.forceUpdate();
  };

  processMessages = (messages, messageSent) => {
    const nextMessages = Array.isArray(messages) ? messages : [];
    const nextMessageIDs = new Set(
      nextMessages
        .map((message) => message?.ID)
        .filter((id) => id !== undefined && id !== null)
    );

    if (!this.messagesLoaded) {
      this.messagesLoaded = true;
      this.messageIDs = nextMessageIDs;
      this.requestScrollToBottom();
      return { messages: nextMessages };
    }

    const currentContactID = Number(
      this.props.appState.contact?.id || this.props.appState.contact_id || 0
    );
    const otherNewMessages = nextMessages.filter((message) =>
      message &&
      message.ID !== undefined &&
      !this.messageIDs.has(message.ID) &&
      Number(message.contactID || 0) > 0 &&
      Number(message.contactID) !== currentContactID
    );

    this.messageIDs = nextMessageIDs;

    if (messageSent) {
      this.requestScrollToBottom();
      return { messages: nextMessages, unreadMessageCount: 0 };
    }

    return {
      messages: nextMessages,
      unreadMessageCount: this.state.unreadMessageCount + otherNewMessages.length,
    };
  };

  onSubmit = (e) => {
    e.preventDefault();

    if (this.devMode)
      console.log("VideoWhisper/screens/Ticket onSubmit", this.state);

    this.serverSubmit();
  };

  serverSubmit = (params) => {
    //submits a message (including upload, recording)
    const { props, state } = this;
    const self = this;

    if (!params) params = new FormData();

    const params0 = {
      ticket_id: props.appState.ticket_id,
      contact_id: props.appState.contact.id,
      pin: props.appState.pin,
      confirm: props.appState.confirm,
      rep: props.appState.rep,
      message: state.message,
      mentionUser: props.appState.chatMentionUser,
      mentionMessage: props.appState.chatMentionMessage,
      language: props.appState.language,
      flag: props.appState.flag,
      department_id: state.department,
      site_id: props.appState.config.site_id,
      content_id: props.appState.config.content_id,
      creator_id: props.appState.config.creator_id,
      fields: state.fields,
      cansLoaded: props.appState.cansLoaded,
    };

    //support for objects
    for (var key in params0) {
      if (typeof params0[key] === 'object') {
        params.append(key, JSON.stringify(params0[key]));
      } else {
        params.append(key, params0[key]);
      }
    }

    if (this.devMode)
      console.log(
        "VideoWhisper/screens/Ticket serverSubmit",
        props.callURL, state.fields,
        ...params
      );

    if (state.message) this.pendingSubmitMessage = state.message;
    this.startRequest('submit');

    axios
      .post(props.callURL, params, this.axiosConfig)
      .then(function (response) {
        self.serverProcess(response);
      })
      .catch(this.serverError.bind(this));

    this.setState({ message: "" });
  };

  serverAction = (params) => {

    //sends other actions ( can )
    const { props, state } = this;
    const self = this;

    if (!params) params = new FormData();

    const params0 = {
      ticket_id: props.appState.ticket_id,
      contact_id: props.appState.contact_id,
      pin: props.appState.pin,
      rep: props.appState.rep,
      confirm: props.appState.confirm,
      cansLoaded: props.appState.cansLoaded,
    };

    for (var key in params0) {
      params.append(key, params0[key])
    }

    if (this.devMode)
      console.log(
        "VideoWhisper/screens/Ticket serverAction",
        props.callURL,
        params
      );

      this.updating = true;
      this.startRequest('action');

    axios
      .post(props.callURL, params, this.axiosConfig)
      .then(function (response) {
        self.serverProcess(response);
      })
      .catch(this.serverError.bind(this));
  };
  
  serverUpdate = () => {

    if (this.updating)
    {
      if (this.devMode) console.log("VideoWhisper/screens/Ticket serverUpdate already updating, skip once");
      this.updating = false;
      this.setState({ loading: false });
      return;
    }

    //ticket update interval
    const { props, state } = this;
    const self = this;

    var params = new FormData();

    const params0 = {
      ticket_id: props.appState.ticket_id,
      contact_id: props.appState.contact_id,
      pin: props.appState.pin,
      rep: props.appState.rep,
      confirm: props.appState.confirm,
      cansLoaded: props.appState.cansLoaded,
    };

    for (var key in params0) {
      params.append(key, params0[key])
    }

    if (this.devMode)
      console.log(
        "VideoWhisper/screens/Ticket serverUpdate",
        props.callURL,
        params
      );

    this.updating = true;
    this.startRequest('update');

    axios
      .post(props.callURL, params, this.axiosConfig)
      .then(function (response) {
        self.serverProcess(response);
      })
      .catch(this.serverUpdateError.bind(this));

    this.serverCalled = true;
  };

   	// Tracks the configured Google Ads conversion and matching GA4 event.
     trackSupportEvent(eventKey, adsSendTo, adsParams, ga4Event, ga4Params, eventState = '') {
      if (eventState && this.state.trackedEvents[eventState]) return;

      trackConfiguredSupportEvent({
        config: this.props.appState.config,
        eventKey,
        adsSendTo,
        adsParams,
        ga4Event,
        ga4Params,
        devMode: this.devMode,
        logPrefix: "VideoWhisper/screens/ticket",
        onSent: () => {
          if (!eventState) return;
          this.setState((state) => ({
            trackedEvents: {
              ...state.trackedEvents,
              [eventState]: true,
            },
          }));
        },
      });
    }

  serverProcess(response) {
    if (this.devMode)
      console.log(
        "VideoWhisper/screens/Ticket serverProcess:",
        response,
        this.state
      );

    const data = response.data;

    if (!data) {
      this.setState({
        loading: false,
        error: this.txt('Server returned no data. Please retry.'),
        timedOut: false,
        lastFailedRequest: this.lastRequestType || 'update',
      });
      this.updating = false;
      return;
    }

    const { state, props} = this;

    this.setState({ loading: false, error: '', timedOut: false, lastFailedRequest: '' });
    this.updateRetryCount = 0;

    if (data.ticket_id && !this.state.created) {

      this.trackSupportEvent('conversationView', props.appState.config?.gtag?.conversationView, {
          'event_category': 'VideoWhisper Support',
          'event_label': 'Conversation View',
          'value': 1
          }, 'conversation_view', {
          'event_category': 'engagement',
          'event_label': 'Conversation View',
          'ticket_id': data.ticket_id,
          'value': 1
          }, 'conversationView' + data.ticket_id);
          
      //updated created and ticket id if necessary
      this.setState({ created: true, error: '' });
      if (!this.props.appState.ticket_id)
        this.props.appStateUpdate({ ticket_id: data.ticket_id, pin: data.pin }); //update app ticket and access code
    }

    if (data.contact)
      if (!this.props.appState.contact.id)
        this.props.appStateUpdate({ contact: data.contact }); //update app contact if not present
    if (data.balance) this.props.appStateUpdate({ balance: data.balance }); //update balance if provided

    if (data.messages) {
      this.setState({
        ...this.processMessages(data.messages, Boolean(data.messageSent)),
        contacts: data.contacts,
        ticket_status: data.ticket_status,
      });
    } else if (data.messageSent) {
      this.requestScrollToBottom();
    }

    // Prefill textarea with saved drafts on first load (only if user hasn't typed anything)
    if (!this.draftLoaded && data.drafts !== undefined) {
      this.draftLoaded = true;
      const drafts = Array.isArray(data.drafts) ? data.drafts : [];
      this.setState({ drafts });
      if (drafts.length > 0 && !this.state.message) {
        const msg = drafts[0].message;
        this.setState({ message: msg });
        this.lastAutosavedMessage = msg;
        if (this.devMode) console.log('VideoWhisper/screens/Ticket serverProcess drafts loaded', drafts.length, msg.length);
      }
    }

    // Message was sent — all drafts cleared server-side, reset tracker
    if (data.messageSent) {
      this.lastAutosavedMessage = '';
      this.pendingSubmitMessage = '';
      this.setState({ drafts: [] });
    }

    if (data.info) this.setState({ info: data.info });

    if (data.tags) this.setState({ tags: data.tags });

    if (data.url)
      this.setState({
        url: data.url,
        meta: data.meta,
        departmentMeta: data.departmentMeta,
        department: data.departmentMeta?.value || this.state.department,
        departmentOptions: Array.isArray(data.departmentOptions) ? data.departmentOptions : this.state.departmentOptions,
        representative : data.representative,
      });
    //this.props.appStateUpdate({contactCheck: true, contact: response.data}, {screen: true});

    if (data.messageSent)
			this.trackSupportEvent('message', props.appState.config?.gtag?.message, {
				'event_category': 'VideoWhisper Support',
				'event_label': 'New Message',
				'value': 1
				}, 'message_submit', {
				'event_category': 'conversion',
				'event_label': 'New Message',
				'value': 1
				});
    

    if (data.conversationOpen)
    this.trackSupportEvent('conversation', props.appState.config?.gtag?.conversation, {
      'event_category': 'VideoWhisper Support',
      'event_label': 'New Conversation',
      'value': 20
      }, 'conversation_open', {
      'event_category': 'conversion',
      'event_label': 'New Conversation',
      'value': 20
      });

    //close modals for special actions
    if (data.recorderComplete)  this.recordModalClose();
    if (data.uploadComplete)  this.uploadModalClose();
    if (data.canComplete) this.canModalClose();
    if (data.contactAddComplete) this.contactAddModalClose();
    if (data.tagAddComplete) this.tagAddModalClose();
    if (data.messageEditComplete) {
      this.setState({ messageEditSaving: false });
      if (!data.error) this.messageEditModalClose();
    }
    if (data.departmentUpdateComplete) {
      this.setState({ departmentSaving: false });
      if (!data.error) {
        this.setState({ departmentEdit: false });
      }
    }

    if (data.cans) this.props.appStateUpdate({cans: data.cans, cansLoaded: true});

    if (!this.state.loaded) this.setState({ loaded: true });

    this.updating = false;

    if (!this.timerStarted) this.timerStart();

    //this.scrollToBottom();
  }

  serverError(error) {
    console.log("VideoWhisper/screens/Ticket serverError:", error);
    const errorInfo = this.getErrorInfo(error);
    const errorState = {
      loading: false,
      error: errorInfo.message,
      timedOut: errorInfo.timedOut,
      lastFailedRequest: this.lastRequestType || 'submit',
    };

    if (
      this.lastRequestType === 'submit' &&
      this.pendingSubmitMessage &&
      !this.state.message
    ) {
      errorState.message = this.pendingSubmitMessage;
    }

    this.setState(errorState);

    this.updating = false;
  }

  serverUpdateError(error) {
    console.log("VideoWhisper/screens/Ticket serverUpdateError:", error);
    this.updating = false;
    const errorInfo = this.getErrorInfo(error);

    //retry if timed out
    if (errorInfo.timedOut) if (this.updateRetryCount < 3) {
      this.updateRetryCount++;
      console.log("VideoWhisper/screens/Ticket serverUpdateError retry", this.updateRetryCount);

      this.setState({
        loading: true,
        timedOut: true,
        error: this.txt('Connection timed out. Retrying...') + ' (' + this.updateRetryCount + '/3)',
        lastFailedRequest: 'update',
      });

      setTimeout(this.serverUpdate, 1000);
      return;
    }

    this.setState({
      loading: false,
      error: errorInfo.message,
      timedOut: errorInfo.timedOut,
      lastFailedRequest: 'update',
    });

  }


  timerStart() {
    this.timerStarted = true;
    this.updateInterval = 15000;
    if (this.props.appState.config)
      if (this.props.appState.config.ticketUpdateInterval)
        this.updateInterval = this.props.appState.config.ticketUpdateInterval;
    this.timer = setInterval(this.timerTick, this.updateInterval); //timer to call webserver for web update (tick)

    if (this.devMode)
      console.log(
        "VideoWhisper/screens/Ticket timerStart",
        this.updateInterval
      );
  }

  timerStop() {
    if (this.timerStarted) clearInterval(this.timer);
    this.timerStarted = false;
  }

  autosaveStart() {
    if (this.autosaveTimer) return;
    if (!this.state.autosaveEnabled) return;
    const interval = this.props.appState.config?.autosaveInterval || 10000;
    this.autosaveTimer = setInterval(this.autosaveTick, interval);
    if (this.devMode) console.log('VideoWhisper/screens/Ticket autosaveStart interval', interval);
  }

  autosaveTick = (force = false) => {
    const { state, props } = this;
    if (!state.autosaveEnabled) return;
    if (!state.created) return;
    if (!props.appState.ticket_id) return;
    // Skip if message is empty
    if (!state.message) return;
    // Skip if nothing changed since last autosave (unless forced)
    if (!force && state.message === this.lastAutosavedMessage) return;

    const params = new FormData();
    params.append('ticket_id', props.appState.ticket_id);
    params.append('contact_id', props.appState.contact.id || props.appState.contact_id);
    params.append('confirm',    props.appState.confirm || '');
    params.append('pin',        props.appState.pin     || '');
    params.append('rep',        props.appState.rep     || '');
    params.append('message',    state.message);

    const draftURL = props.callURL.replace('/ticket', '/draft');
    const savedMessage = state.message;
    const savedAt = Math.floor(Date.now() / 1000);

    axios.post(draftURL, params, this.axiosConfig)
      .then(() => {
        this.lastAutosavedMessage = savedMessage;
        const maxDrafts = this.props.appState.config?.autosaveDrafts || 3;
        const newDraft = { message: savedMessage, created: savedAt };
        const updatedDrafts = [newDraft, ...(this.state.drafts || [])].slice(0, maxDrafts);
        this.setState({ drafts: updatedDrafts, savingDraft: true });
        setTimeout(() => this.setState({ savingDraft: false }), 1500);
        if (this.devMode) console.log('VideoWhisper/screens/Ticket autosaveTick saved', savedMessage.length, updatedDrafts.length);
      })
      .catch(err => {
        if (this.devMode) console.log('VideoWhisper/screens/Ticket autosaveTick error', err);
      });
  };

  timerTick = () => {
    this.serverUpdate();
  };

  txt = (text) => {
    //handle text translations from appState.config
    const { props } = this;
    if (!props.appState.config) return text;
    if (!props.appState.config.text) return text;

    if (text in props.appState.config.text)
      return props.appState.config.text[text];
    return text;
  };

  emojiModalClose = () => this.setState({ emojiModalShow: false });
  recordModalClose = () => this.setState({ recordModalShow: false })
  uploadModalClose = () => this.setState({ uploadModalShow: false })
  languageModalClose = () => this.setState({ languageModalShow: false })
  canModalClose = () => this.setState({ canModalShow: false })
  wikiModalClose = () => this.setState({ wikiModalShow: false })
  contactModalClose = () => this.setState({ contactModalShow: false, openContact: 0 })
  contactAddModalClose = () => this.setState({ contactAddModalShow: false, contactName: '', contactContact: '' })
  tagAddModalClose = () => this.setState({ tagAddModalShow: false})
  messageEditModalClose = () => this.setState({ messageEditModalShow: false, messageEditID: 0, messageEditText: '', messageEditSaving: false })

  messageModalClose = () => 
  {
    this.props.appStateUpdate({openMessage: 0});
    this.setState({ messageModalShow: false })
  }

  onEmojiButton = () => this.setState({ emojiModalShow: true });
  onRecordButton = () => this.setState({ recordModalShow: true});
  onUploadButton = () => this.setState({ uploadModalShow: true});
  onLanguageButton = () => this.setState({ languageModalShow: true});
  onWikiButton = () => {
    this.setState({ wikiModalShow: true }, () => {
      if (!this.state.wikiItems.length) this.wikiSearch();
    });
  };

  formatDraftAge(created) {
    const now = Math.floor(Date.now() / 1000);
    const age = now - created;
    if (age < 60) return age + 's';
    if (age < 3600) return Math.floor(age / 60) + 'm';
    if (age < 86400) return Math.floor(age / 3600) + 'h';
    return Math.floor(age / 86400) + 'd';
  }

  onAutosaveAction = (event, data) => {
    if (data.value === 'save') {
      this.autosaveTick(true);
    } else if (String(data.value).startsWith('restore_')) {
      const idx = parseInt(data.value.split('_')[1], 10);
      const draft = this.state.drafts[idx];
      if (draft) {
        this.setState({ message: draft.message });
        this.lastAutosavedMessage = draft.message;
      }
    } else if (data.value === 'toggle') {
      const enabled = !this.state.autosaveEnabled;
      this.setState({ autosaveEnabled: enabled });
      if (!enabled && this.autosaveTimer) {
        clearInterval(this.autosaveTimer);
        this.autosaveTimer = null;
      }
      if (enabled && this.state.created) this.autosaveStart();
    }
  };
  onContactAddButton = () => this.setState({ contactAddModalShow: true});
  onTagAddButton = () => this.setState({ tagAddModalShow: true});

  onTagAddChange = (event, data) => {
    if (data.name == "tagName") data.value = data.value.substring(0,64); //limit tag to 64 chars
    this.setState({ [data.name]: data.value });
  }

  onContactAddChange = (event, data) => {
    if (data.name == "contactName") data.value = data.value.substring(0,64); //limit name to 64 chars
    if (data.name == "contactContact") data.value = data.value.substring(0,128); //limit contact to 128 chars
    this.setState({ [data.name]: data.value });
  }
  language2flag(lang){
    const flags = { 'en-us':'us', 'en-gb':'gb', 'pt-br':'br', 'pt-pt':'pt', 'zh':'cn', 'ja':'jp', 'el':'gr', 'da':'dk', 'ko':'kr', 'nb':'no' };
    if (flags[lang]) return flags[lang];
    return lang;
  }

  onLanguageChange(event, data) {

    if (this.devMode)  console.log('VideoWhisper/screents/ticket onLanguageChange', data, event);

    this.serverAction({action:'user_option', 'name': data.name, 'value': data.value});

    this.setState({
      language: data.value,
      flag: this.language2flag(data.value),
      languageModalShow: false,
  });

    this.props.appStateUpdate( { language : data.value, flag: this.language2flag(data.value) } );
 }

  onCanButton = () => this.setState({ 
     canModalShow: true, 
     canMessage: this.state.message, 
     canTitle: this.state.message.substring(0,64) });

     onCanChange = (event, data) => {
      if (data.name == "canTitle") data.value = data.value.substring(0,64); //limit title to 64 chars
      this.setState({ [data.name]: data.value });
    };

    
  onCanSubmit = () => {
    const {state} = this;

    var params = new FormData();
    params.append("action", "can");
    params.append("canMessage", state.canMessage); 
    params.append("canTitle", state.canTitle);

    if (this.devMode) console.log("VideoWhisper/screens/Ticket onCanSubmit", params);
    this.serverAction(params);
  }

  onCanInsert = (event, data) => {
    this.setState({ 'message': this.state.message + "\r\n" + data.value });
  }

  appendMessageText = (text) => {
    if (!text) return;
    const current = this.state.message || '';
    const separator = current && !current.endsWith("\n") ? "\n" : "";
    this.setState({ message: current + separator + text }, () => this.validation());
  }

  onWikiSearchChange = (event, data) => {
    this.setState({ wikiSearch: data.value });
  }

  wikiSearch = () => {
    const { props, state } = this;
    const wikiURL = props.callURL.replace('/ticket', '/wiki');
    this.setState({ wikiLoading: true, wikiError: '' });

    axios.get(wikiURL, {
      withCredentials: true,
      credentials: "include",
      timeout: 20000,
      headers: {
        Accept: "application/json",
        "X-WP-Nonce": props.appState.session.nonce,
      },
      params: { search: state.wikiSearch || '' },
    }).then((response) => {
      const items = Array.isArray(response.data?.items) ? response.data.items : [];
      this.setState({ wikiItems: items, wikiLoading: false });
    }).catch((error) => {
      this.setState({
        wikiLoading: false,
        wikiError: error?.response?.data?.message || error?.message || this.txt('Could not search wiki.'),
      });
    });
  }

  onWikiAction = (item, action) => {
    const title = item.title || '';
    const url = item.url || '';
    const excerpt = item.excerpt || '';
    const content = item.agentic_content || '';

    if (action === 'open') {
      if (url) window.open(url, '_blank', 'noopener,noreferrer');
      return;
    }
    if (action === 'link') {
      this.appendMessageText(`[${title}](${url})`);
    } else if (action === 'link_excerpt') {
      this.appendMessageText(`[${title}](${url})${excerpt ? "\n" + excerpt : ""}`);
    } else if (action === 'content') {
      this.appendMessageText(content || (excerpt ? `[${title}](${url})\n${excerpt}` : `[${title}](${url})`));
    }
    this.setState({ wikiModalShow: false });
  }

  onTagAddSubmit = () => {
    const {state} = this;
    var params = new FormData();

    params.append("action", "tag_add");
    params.append("tag", state.tagName);

    if (this.devMode) console.log("VideoWhisper/screens/Ticket onTagAddSubmit", params);
    this.serverAction(params);
  }

  onContactAddSubmit = () => {
    const {state} = this;
    var params = new FormData();

    params.append("action", "contact_add");
    params.append("contactName", state.contactName);
    params.append("contactContact", state.contactContact);
    params.append("contactType", state.contactType);
    params.append("contactRole", state.contactRole);

    if (this.devMode) console.log("VideoWhisper/screens/Ticket onContactAddSubmit", params);
    this.serverAction(params);
  }

  onContactRemoveButton = (event, data) => {
    const {state} = this;
    var params = new FormData();

    params.append("action", "contact_remove");
    params.append("contactRemoveID", data.contact_id);

    if (this.devMode) console.log("VideoWhisper/screens/Ticket onContactRemoveButton", params);
    this.serverAction(params);
  }

  onTagRemoveButton = (event, data) => {
    const {state} = this;
    var params = new FormData();

    params.append("action", "tag_remove");
    params.append("tag", data.tag);

    if (this.devMode) console.log("VideoWhisper/screens/Ticket onTagRemoveButton", params);
    this.serverAction(params);
  }    


  addEmoji = (emoji) => {
    if (this.devMode)
      console.log("VideoWhisper/screens/Ticket addEmoji", emoji);
    var message = this.state.message;

    if (emoji) if (emoji.native) message = message + emoji.native;
    this.setState({ emojiModalShow: false, message: message });
  };

  EmojiPicker = (props) => {
    const ref = useRef();

    useEffect(() => {
      new Picker({ ...props, data, ref });
    }, []);

    return <div ref={ref} />;
  };

openContact = (event, data) => {
  const { state, props } = this;

  if (this.devMode) console.log("VideoWhisper/screens/Ticket openContact", data, event, state.contacts);

  if (data.contact_id) this.setState({ contactModalShow: true, openContact: data.contact_id });

}

openMessage = (event, data) => {
  const { state, props } = this;

  if (this.devMode) console.log("VideoWhisper/screens/ticket openMessage", data, event, state.messages);

  if (data.message_id) 
  {
    props.appStateUpdate({openMessage: data.message_id});
    this.setState({ messageModalShow: true });
  }

}

  onMessageEditButton = (event, message) => {
    if (event) event.stopPropagation();
    if (!message) return;

    this.setState({
      messageEditModalShow: true,
      messageEditID: message.ID,
      messageEditText: message.text || '',
      messageEditSaving: false,
    });
  }

  onMessageEditSubmit = () => {
    const { state } = this;
    const text = state.messageEditText || '';
    if (!state.messageEditID || !text.trim()) return;

    var params = new FormData();
    params.append("action", "message_edit");
    params.append("messageEditID", state.messageEditID);
    params.append("messageEditText", text);

    this.setState({ messageEditSaving: true });
    this.serverAction(params);
  }

  onDepartmentEditStart = () => {
    this.setState({
      departmentEdit: true,
      departmentEditValue: this.state.departmentMeta?.value || this.state.department || 0,
    });
  }

  onDepartmentEditCancel = () => {
    this.setState({
      departmentEdit: false,
      departmentEditValue: this.state.departmentMeta?.value || this.state.department || 0,
      departmentSaving: false,
    });
  }

  onDepartmentEditChange = (event, data) => {
    this.setState({ departmentEditValue: data.value });
  }

  onDepartmentEditSubmit = () => {
    if (!this.state.departmentEditValue) return;

    var params = new FormData();
    params.append("action", "department_update");
    params.append("departmentUpdateID", this.state.departmentEditValue);

    this.setState({ departmentSaving: true });
    this.serverAction(params);
  }

  render() {
    const { state, onChange, props, txt } = this;

    // New conversation = no ticket_id to load from server
    const isNewConversation = !props.appState.ticket_id;

    if (this.devMode && !this.renderLogged) {
      console.log('VideoWhisper/screens/Ticket render', {
        isNewConversation,
        ticket_id: props.appState.ticket_id,
        contact_id: props.appState.contact_id,
        loaded: state.loaded,
        created: state.created,
        serverCalled: this.serverCalled,
      });
      this.renderLogged = true;
    }

    //access:load existing ticket
    if (!isNewConversation && !this.serverCalled)
      this.serverUpdate();

    // Show loading/error UI only when loading an existing ticket
    if (!isNewConversation && !state.loaded)
      return (
        <div
          key="ticket"
          className="layoutTicket"
          style={{ backgroundColor: props.appState.config.backgroundColor }}>
          <Form
            className="layInputs"
            key="form"
            onSubmit={this.onSubmit}
            autoComplete="off">
            {state.loading || this.updating ? (
              <>
                <Loader active inline className="slow red" /> <br />
                {txt("Loading conversation")}...
              </>
            ) : (
              <Message negative>
                <Message.Header>
                  {state.timedOut ? txt('Connection timed out') : txt('Could not load conversation')}
                </Message.Header>
                <p>{state.error || txt('Could not connect to server. Please retry.')}</p>
                <Button
                  type="button"
                  color="grey"
                  size="small"
                  onClick={this.retryLastRequest}
                  inverted={props.appState.config.darkMode}>
                  {txt('Retry')} <Icon name="redo" />
                </Button>
              </Message>
            )}
          </Form>
        </div>
      );

    //emoji
    const emojiModalCode = (
      <Modal
        key="emojiModal"
        closeIcon
        open={state.emojiModalShow}
        onClose={this.emojiModalClose}
        size="small"
        basic={props.appState.config.darkMode}>
        <Header icon="smile" content={txt("Emoticons")} />
        <Modal.Content>
          <EmojiPicker
            onEmojiSelect={this.addEmoji}
            darkMode={props.appState.config.darkMode}
            native
            perLine={16}
          />
        </Modal.Content>
        <Modal.Actions>
          <Button
            inverted={props.appState.config.darkMode}
            color="red"
            onClick={this.emojiModalClose}>
            <Icon name="remove" /> {txt("Nevermind")}
          </Button>
        </Modal.Actions>
      </Modal>
    );

    //tag add modal
    let tagAddModalCode = '';
    let codeTagAdd = '';

    if (state.representative) {
      codeTagAdd = (
        <Button
          size="tiny"
          compact
          icon
          type="button"
          color="teal"
          data-tooltip={txt("Add Tag")}
          onClick={this.onTagAddButton}
          inverted={props.appState.config.darkMode}>
          <Icon name="tag plus" />
        </Button>
      );

      tagAddModalCode = (
        <Modal
          key="tagAddModal"
          closeIcon
          open={state.tagAddModalShow}
          onClose={this.tagAddModalClose}
          size="small"
          basic={props.appState.config.darkMode}>
          <Header icon="tag" content={txt("Add Tag")} />
          <Modal.Content>
            <Form>
              <Form.Field>
                <label>{txt("Tag Name")}</label>
                <Input
                  fluid
                  name="tagName"
                  placeholder={txt("Tag Name")}
                  value={state.tagName}
                  onChange={this.onTagAddChange}
                />
              </Form.Field>
            </Form>
          </Modal.Content>
          <Modal.Actions>
            <Button
              inverted={props.appState.config.darkMode}
              color="red"
              onClick={this.tagAddModalClose}>
              <Icon name="remove" /> {txt("Nevermind")}
            </Button>
            <Button
              inverted={props.appState.config.darkMode}
              color="green"
              onClick={this.onTagAddSubmit}>
              <Icon name="checkmark" /> {txt("Add")}
            </Button>
          </Modal.Actions>
        </Modal>
      );
    }


    //contact add modal
    let contactAddModalCode = '';
    let codeContactAdd = '';

      codeContactAdd = (
      <Button
          size="tiny"
          compact
          icon
          type="button"
          color="teal"
          data-tooltip={txt("Add Contact")}
          onClick={this.onContactAddButton}
          inverted={props.appState.config.darkMode}
          >
          <Icon name="user plus" />
        </Button>
      );

      const contactTypes = [ { key: 'email', text: txt("Email"), value: 'email' } ];
      const contactRoles = [ { key: 'client', text: txt("Client"), value: 'client' }];
      if (state.representative) contactRoles.push({ key: 'representative', text: txt("Representative"), value: 'representative' });

      contactAddModalCode = ( <Modal key="contactAddModal" closeIcon
      open={state.contactAddModalShow}
      onClose={this.contactAddModalClose}
      size='small' basic={props.appState.config.darkMode}
    >
      <Header icon='user plus' content={txt("Add Contact")} />
      <Modal.Content>
      <Form>

      <Form.Field>
      <label>{txt('Contact Name')}</label>
        <Input fluid name="contactName" placeholder={txt("Contact Name")} value={state.contactName} onChange={this.onContactAddChange} />
      </Form.Field>

      <FormGroup widths='equal'>
      <Form.Field>
        <label>{txt('Contact')}*</label>
        <Input fluid name="contactContact" placeholder={txt("Contact")} value={state.contactContact} onChange={this.onContactAddChange} />
        </Form.Field>
        <Form.Field>
        <label>{txt('Contact Type')}</label>
        <Dropdown name="contactType" selection compact fluid
               className={props.appState.config.className + " v-select"} data-position="right center" 
               value={state.contactType} options={contactTypes} 
               onChange={(e, data)=>this.onContactAddChange(e, data)} />
      </Form.Field>
      </FormGroup>
      
      <Form.Field>
      <label>{txt('Contact Role')}</label>
        <Dropdown name="contactRole" selection compact fluid
               className={props.appState.config.className + " v-select"} data-position="right center" 
               value={state.contactRole} options={contactRoles} 
               onChange={(e, data)=>this.onContactAddChange(e, data)} />
      </Form.Field>
      </Form>
      <Message size="small"> *{txt('If Contact does not exist, it will be created for Contact Name.')} </Message>
      </Modal.Content>
      <Modal.Actions>
        <Button inverted={props.appState.config.darkMode} color='red' onClick={this.contactAddModalClose} ><Icon name='remove' /> {txt("Nevermind")}</Button>
        <Button inverted={props.appState.config.darkMode} color='green' onClick={this.onContactAddSubmit} ><Icon name='checkmark' /> {txt("Add")}</Button>
      </Modal.Actions>

    </Modal> );
  
  //end contact add modal

    //contact modal
    let contactModalCode = '';
    var contactPropertiesCode = '';
    var contactFieldsCode = '';

    if (state.representative && state.openContact && state.contacts[state.openContact]) {
      const Contact = state.contacts[state.openContact];

      if (Contact.info) 
      {
        if (this.devMode) console.log("VideoWhisper/screens/Ticket Contact.info", Contact.info);

      if (Contact.info.properties)
      {        
        //display contact properties array in a table with columns type, name, value, category, group, status
        var contactProperties = Contact.info.properties;
        contactPropertiesCode = [];
        for (var i = 0; i < contactProperties.length; i++) {
          var property = contactProperties[i];
          
          //include date & time based on created, updated unix timestamps
          if (property.created) property.created = new Date(property.created * 1000).toLocaleString();
          else property.created = '';
          if (property.updated) property.updated = new Date(property.updated * 1000).toLocaleString();
          else property.updated = '';

          contactPropertiesCode.push(
            <Table.Row key={property.id}>
              <Table.Cell>{property.type}</Table.Cell>
              <Table.Cell>{property.name}</Table.Cell>
              <Table.Cell>{property.value}</Table.Cell>
              <Table.Cell>{property.category}</Table.Cell>
              <Table.Cell>{property.group}</Table.Cell>
              <Table.Cell>{property.status !='0' ? property.status : (<Icon name="check"/>)}</Table.Cell>
              <Table.Cell>{property.created}</Table.Cell>
              <Table.Cell>{property.updated}</Table.Cell>
            </Table.Row>
          );
        }

        contactPropertiesCode = (
          <Table celled striped size="small">
            <Table.Header>
              <Table.Row>
                <Table.HeaderCell><Header>{txt("Properties")}</Header></Table.HeaderCell>
                <Table.HeaderCell>{txt("Name")}</Table.HeaderCell>
                <Table.HeaderCell>{txt("Value")}</Table.HeaderCell>
                <Table.HeaderCell>{txt("Category")}</Table.HeaderCell>
                <Table.HeaderCell>{txt("Group")}</Table.HeaderCell>
                <Table.HeaderCell>{txt("Status")}</Table.HeaderCell>
                <Table.HeaderCell>{txt("Created")}</Table.HeaderCell>
                <Table.HeaderCell>{txt("Updated")}</Table.HeaderCell>
              </Table.Row>
            </Table.Header>
            <Table.Body>{contactPropertiesCode}</Table.Body>
          </Table>
        );
      } 

      if (Contact.info.fields || Contact.info.forms)
      {
        var contactFieldsRows = [];

       if (Contact.info.fields) Object.keys(Contact.info.fields).forEach((field) => {
          contactFieldsRows.push(
            <Table.Row>
              <Table.Cell>{field}</Table.Cell>
              <Table.Cell>{Contact.info.fields[field]}</Table.Cell>
            </Table.Row>
          );
        });

        if (Contact.info.forms) Object.keys(Contact.info.forms).forEach((field) => {
          contactFieldsRows.push(
            <Table.Row>
              <Table.Cell>{txt('Form') + ': ' + field}</Table.Cell>
              <Table.Cell>{new Date(Contact.info.forms[field]*1000).toLocaleString()}</Table.Cell>
            </Table.Row>
          );
        }); 

          contactFieldsCode = (
            <Table celled striped size="small">
              <Table.Header>
                <Table.Row>
                  <Table.HeaderCell>{txt("Details")}</Table.HeaderCell>
                  <Table.HeaderCell>{txt("Value")}</Table.HeaderCell>
                </Table.Row>
              </Table.Header>
              <Table.Body>{contactFieldsRows}</Table.Body>
            </Table>
          );    
     }
    }
      contactModalCode = ( <Modal key="contactModal" closeIcon
      open={state.contactModalShow}
      onClose={this.contactModalClose}
      size='large' basic={props.appState.config.darkMode}
    >
      <Header icon='box' content={txt("Contact Info") + ": " + Contact.name} />
      <Modal.Content scrolling>
     {contactPropertiesCode}
     {contactFieldsCode}
      </Modal.Content>
      <Modal.Actions>
       </Modal.Actions>
    </Modal> );
    }
    
    let messageModalCode = '';
    var messagePropertiesCode = '';

    if ((state.representative || props.appState.config.siteAdmin) && props.appState.openMessage) {


      if (!state.messageModalShow) this.setState({ messageModalShow: true });

      //find Message by ID property of element in state.messages being props.appState.openMessage 
      let Message = state.messages.find( (element) => element.ID == props.appState.openMessage );

      if (!Message)
      {
        this.messageModalClose();
        if (this.devMode) console.log("VideoWhisper/screens/Ticket openMessage not found", props.appState.openMessage, state.messages);
      } else if (this.devMode) console.log("VideoWhisper/screens/Ticket openMessage found", props.appState.openMessage, Message);

      if (Message && Message.info)
      {
        var messageFieldsRows = [];

        Object.keys(Message.info).forEach((field) => {
          messageFieldsRows.push(
            <Table.Row>
              <Table.Cell>{field}</Table.Cell>
              <Table.Cell>{Message.info[field]}</Table.Cell>
            </Table.Row>
          );
        }); 
        messagePropertiesCode = (
          <Table celled striped size="small">
            <Table.Header>
              <Table.Row>
                <Table.HeaderCell>{txt("Details")}</Table.HeaderCell>
                <Table.HeaderCell>{txt("Value")}</Table.HeaderCell>
              </Table.Row>
            </Table.Header>
            <Table.Body>{messageFieldsRows}</Table.Body>
          </Table>
        );    
      }

    messageModalCode = ( <Modal key="messageModal" closeIcon
    open={state.messageModalShow}
    onClose={this.messageModalClose}
    size='large' basic={props.appState.config.darkMode}
  >
    <Header icon='box' content={txt("Message Info") + " #" + Message.ID + " / " + Message.contactName} />
    <Modal.Content scrolling>
   {messagePropertiesCode}
    </Modal.Content>
    <Modal.Actions>
     </Modal.Actions>
  </Modal> );
    } else if (state.messageModalShow) this.setState({ messageModalShow: false });

    const messageEditModalCode = (
      <Modal
        key="messageEditModal"
        closeIcon
        open={state.messageEditModalShow}
        onClose={this.messageEditModalClose}
        size="small"
        basic={props.appState.config.darkMode}
      >
        <Header icon="edit" content={txt("Edit Message") + (state.messageEditID ? " #" + state.messageEditID : "")} />
        <Modal.Content>
          <Form inverted={props.appState.config.darkMode}>
            <Form.Field>
              <TextArea
                rows={8}
                value={state.messageEditText}
                onChange={(event, data) => this.setState({ messageEditText: data.value })}
              />
            </Form.Field>
          </Form>
        </Modal.Content>
        <Modal.Actions>
          <Button inverted={props.appState.config.darkMode} onClick={this.messageEditModalClose}>
            <Icon name="remove" /> {txt("Nevermind")}
          </Button>
          <Button
            color="green"
            inverted={props.appState.config.darkMode}
            onClick={this.onMessageEditSubmit}
            disabled={state.messageEditSaving || !String(state.messageEditText || '').trim()}
            loading={state.messageEditSaving}
          >
            <Icon name="save" /> {txt("Save")}
          </Button>
        </Modal.Actions>
      </Modal>
    );
  

    //autosave menu
    const autosaveMenuOptions = [
      { key: 'save',   text: txt('Save Draft'),   value: 'save',   icon: 'save' },
      { key: 'toggle', text: state.autosaveEnabled ? txt('Disable Autosave') : txt('Enable Autosave'), value: 'toggle', icon: state.autosaveEnabled ? 'pause circle' : 'play circle' },
    ];
    if (state.drafts && state.drafts.length > 0) {
      state.drafts.forEach((d, i) => {
        autosaveMenuOptions.push({
          key: 'restore_' + i,
          text: txt('Restore Draft') + ' ' + this.formatDraftAge(d.created),
          value: 'restore_' + i,
          icon: 'undo',
        });
      });
    }
    const codeAutosave = state.created ? (
      <Dropdown
        button
        compact
        className={`icon${state.savingDraft ? ' vws-autosave-saving' : ''}`}
        icon={state.autosaveEnabled ? 'cloud' : 'cloud upload'}
        title={txt('Autosave')}
        pointing='top left'
        selectOnBlur={false}
        value={null}
        options={autosaveMenuOptions}
        onChange={this.onAutosaveAction}
      />
    ) : '';

    //language
    var languageModalCode = '';
    var codeLanguage = '';

    if (props.appState.config.multilanguage && props.appState.config.languages) {

      codeLanguage = (<Button compact icon type="button" data-tooltip={txt('My Language')} onClick={this.onLanguageButton} inverted={props.appState.config.darkMode}><Flag name={props.appState.flag} /></Button> );

      const field = props.appState.config.languages;

       languageModalCode = (
        <Modal key='languageModal' closeIcon
        open={state.languageModalShow}
        onClose={this.languageModalClose}
        size='small' basic={props.appState.config.darkMode}
      >
        <Header icon='flag' content={txt("My Language")} />
        <Modal.Content>
        <Form>
        <Dropdown name={field.name} selection compact fluid
               className={props.appState.config.className + " v-select"} data-position="right center" 
               value={props.appState.language} options={field.options} flag={props.appState.flag}
               onChange={(e, data)=>this.onLanguageChange(e, data)} />
          <div>{field.details}</div>
        </Form>
        </Modal.Content>
      </Modal>
        );        
    }

    //wiki
    let wikiModalCode = '';
    let codeWiki = '';
    const canUseWiki = Boolean(props.appState.config.siteAdmin);
    if (canUseWiki) {
      codeWiki = (
        <Button
          compact
          icon
          type="button"
          color="blue"
          data-tooltip={txt("Wiki")}
          onClick={this.onWikiButton}
          inverted={props.appState.config.darkMode}>
          <Icon name="book" />
        </Button>
      );

      const wikiRows = (state.wikiItems || []).map((item) => {
        const breadcrumbs = Array.isArray(item.breadcrumbs) ? item.breadcrumbs.join(' > ') : item.title;
        return (
          <Table.Row key={item.id}>
            <Table.Cell>
              <strong>{breadcrumbs}</strong>
              {item.internal ? <Label size="tiny" color="grey">{txt("Internal")}</Label> : ''}
              {item.excerpt ? <div className="vwsWikiExcerpt">{item.excerpt}</div> : ''}
            </Table.Cell>
            <Table.Cell collapsing>
              <Dropdown button compact icon="ellipsis vertical" className="icon" direction="left">
                <Dropdown.Menu>
                  <Dropdown.Item icon="external" text={txt("Open Link")} onClick={() => this.onWikiAction(item, 'open')} />
                  <Dropdown.Item icon="linkify" text={txt("Insert Link")} onClick={() => this.onWikiAction(item, 'link')} />
                  <Dropdown.Item icon="quote left" text={txt("Insert Link & Excerpt")} onClick={() => this.onWikiAction(item, 'link_excerpt')} />
                  <Dropdown.Item icon="file text" text={txt("Insert Contents")} onClick={() => this.onWikiAction(item, 'content')} />
                </Dropdown.Menu>
              </Dropdown>
            </Table.Cell>
          </Table.Row>
        );
      });

      wikiModalCode = (
        <Modal key="wikiModal" closeIcon
          open={state.wikiModalShow}
          onClose={this.wikiModalClose}
          size="large" basic={props.appState.config.darkMode}>
          <Header icon="book" content={txt("Wiki")} />
          <Modal.Content>
            <Form onSubmit={(e) => { e.preventDefault(); this.wikiSearch(); }}>
              <Form.Group widths="equal">
                <Form.Field>
                  <Input
                    name="wikiSearch"
                    fluid
                    value={state.wikiSearch}
                    placeholder={txt("Search by title")}
                    onChange={this.onWikiSearchChange}
                    action={{
                      icon: 'search',
                      onClick: this.wikiSearch,
                      loading: state.wikiLoading,
                    }}
                  />
                </Form.Field>
              </Form.Group>
            </Form>
            {state.wikiError ? <Message negative>{state.wikiError}</Message> : ''}
            <Table compact basic="very" className={props.appState.config.darkMode ? 'inverted' : ''}>
              <Table.Body>
                {wikiRows.length ? wikiRows : (
                  <Table.Row>
                    <Table.Cell>{state.wikiLoading ? <Loader active inline size="small" /> : txt("No wiki pages found.")}</Table.Cell>
                  </Table.Row>
                )}
              </Table.Body>
            </Table>
          </Modal.Content>
        </Modal>
      );
    }

    //can
    let canModalCode = '';
    let codeCan = '';
    let insertCan = (<>{props.appState.cansLoaded}</>);

    if (state.representative) {

      codeCan = (
      <Button
          floated = "right"
          compact
          icon
          type="button"
          color="teal"
          data-tooltip={txt("Can Message")}
          onClick={this.onCanButton}
          inverted={props.appState.config.darkMode}
          disabled={state.message.length < 10}>
          <Icon name="box" />
        </Button>
      );

      if (props.appState.cans.length > 0) 
      insertCan =(
        <Dropdown
          button
          compact
          clearable
          className='icon'
          labeled
          icon='dropbox'
          options={props.appState.cans}
          search
          text='Insert Can'
          color="teal"
          onChange={this.onCanInsert}
        />
      )
      
      canModalCode = ( <Modal key="canModal" closeIcon
      open={state.canModalShow}
      onClose={this.canModalClose}
      size='small' basic={props.appState.config.darkMode}
    >
      <Header icon='box' content={txt("Can Message")} />
      <Modal.Content>
      <Form>
      <Form.Field>
      <label>{txt('Can Message')}</label>
        <TextArea name="canMessage" placeholder={txt("Can Message")} value={state.canMessage} onChange={this.onCanChange} />
      </Form.Field>
      <Form.Field>
        <label>{txt('Can Title')}</label>
        <Input fluid name="canTitle" placeholder={txt("Can Title")} value={state.canTitle} onChange={this.onCanChange} />
      </Form.Field>
      </Form>
      </Modal.Content>
      <Modal.Actions>
        <Button inverted={props.appState.config.darkMode} color='red' onClick={this.canModalClose} ><Icon name='remove' /> {txt("Nevermind")}</Button>
        <Button inverted={props.appState.config.darkMode} color='green' onClick={this.onCanSubmit} ><Icon name='checkmark' /> {txt("Save")}</Button>
      </Modal.Actions>
    </Modal> );
    }

    //recorder
    var recordModalCode = '';
    var codeRecorder = '';

    if ( !props.appState.config.recorderDisable  && state.created )  //insert media after creation
    {
    codeRecorder = (<Button compact icon type="button" color='orange' data-tooltip={txt('Insert Recording')} onClick={this.onRecordButton} inverted={props.appState.config.darkMode}><Icon name='camera video' /></Button> );

    recordModalCode = (
      <Modal key='recordModal' closeIcon
      open={state.recordModalShow}
      onClose={this.recordModalClose}
      size='small' basic={props.appState.config.darkMode}
    >
      <Header icon='file video' content={txt("Record")} />
      <Modal.Content>
      <Recorder config={props.config} user={props.user} room={props.room}
            appState={props.appState} appStateUpdate={props.appStateUpdate}
            serverSubmit={this.serverSubmit} recorderStatus={this.recorderStatus}
            options={{scenario: ( props.options ? props.options.scenario : 'ticket' ) }}
            />
      </Modal.Content>
      <Modal.Actions>
        <Button compact inverted={props.appState.config.darkMode}  color='red' onClick={this.recordModalClose}>
          <Icon name='remove' /> {txt('Nevermind')}
        </Button>
      </Modal.Actions>
    </Modal>
      );
    }

    //uploads
    var uploadModalCode = '';
    var codeUpload = '';

    if (!this.props.appState.config.uploadDisable && state.created )
    {
    codeUpload = (<Button compact icon type="button" color='teal' data-tooltip={txt('Upload')} onClick={this.onUploadButton} inverted={props.appState.config.darkMode}><Icon name='upload' /></Button> );

     uploadModalCode = (
      <Modal key='uploadModal' closeIcon
      open={state.uploadModalShow}
      onClose={this.uploadModalClose}
      size='small' basic={props.appState.config.darkMode}
    >
      <Header icon='upload' content={txt("Upload")} />
      <Modal.Content>
      <Uploads appState={props.appState} serverSubmit={this.serverSubmit} />
      </Modal.Content>
      <Modal.Actions>

        <Button inverted={props.appState.config.darkMode}  color='red' onClick={this.uploadModalClose}>
          <Icon name='remove' /> {txt('Nevermind')}
        </Button>

      </Modal.Actions>
    </Modal>
      );

    }

    var header = [];
    var form = [];

    //	if (props.appState.openTicket) header.push(<Form.Field key='BackButton'><Button fluid icon key='back' type='button' data-position='right center' data-tooltip={txt('Back to List')} inverted={props.appState.config.darkMode} onClick={()=>props.appStateUpdate({openTicket:0}, {screen:true})}><Icon name='left arrow' /> {txt('Back to List')}</Button></Form.Field>);

    if (state.departmentMeta)
      header.push(
        <Form.Field key="DepartmentName">
          <Label basic>
            <Icon name="box" /> {state.departmentMeta.text}
          </Label>
          {props.appState.config.siteAdmin ? (
            state.departmentEdit ? (
              <>
                <Dropdown
                  inline
                  selection
                  className={props.appState.config.className + " v-select"}
                  options={state.departmentOptions}
                  value={state.departmentEditValue}
                  onChange={this.onDepartmentEditChange}
                />
                <Button
                  basic
                  compact
                  size="tiny"
                  icon
                  type="button"
                  loading={state.departmentSaving}
                  disabled={state.departmentSaving || !state.departmentEditValue}
                  onClick={this.onDepartmentEditSubmit}>
                  <Icon name="save" />
                </Button>
                <Button
                  basic
                  compact
                  size="tiny"
                  icon
                  type="button"
                  disabled={state.departmentSaving}
                  onClick={this.onDepartmentEditCancel}>
                  <Icon name="close" />
                </Button>
              </>
            ) : (
              <Button
                basic
                compact
                size="tiny"
                icon
                type="button"
                data-tooltip={txt("Edit Department")}
                onClick={this.onDepartmentEditStart}>
                <Icon name="edit" />
              </Button>
            )
          ) : (
            ""
          )}
          {state.departmentMeta.content ? (
            <>
              {" "}
              <Label basic>
                <Icon name="file" /> {state.departmentMeta.content}
              </Label>
            </>
          ) : (
            ""
          )}{" "}
          {state.departmentMeta.creator ? (
            <>
              {" "}
              <Label basic>
                <Icon name="user" /> {state.departmentMeta.creator}
              </Label>
            </>
          ) : (
            ""
          )}{" "}
          {state.departmentMeta.url ? (
            <>
              {" "}
              <Button
                basic
                compact
                size="tiny"
                icon
                href={state.departmentMeta.url}
                target="Content">
                <Icon name="linkify" />{" "}
              </Button>
            </>
          ) : (
            ""
          )}
        </Form.Field>
      );

    if (state.ticket_status)
      header.push(
        <Form.Field key="Status">
          <Label basic>
            <Icon name="check" /> {state.ticket_status}
          </Label>{" "}
        </Form.Field>
      );

    if (state.loaded)
      if (state.contacts) {
        const contactList = Object.values(state.contacts).map((contact) => {
          return (
            <ButtonGroup key={"groupContact" + contact.id}>
            <Button 
            compact 
            size="tiny" 
            key={"contact" + contact.id} 
            contact_id={contact.id} 
            onClick={this.openContact} 
//           data-tooltip={"#" + contact.ticketCount} 
            >
              <Icon name={"user" + (contact.rep ? " md" : "")} />
              {contact.name}
            </Button>

{props.appState.openTicket && contact.info.ticketCount ? 
  <Button
size="tiny"
key={"tickets" + contact.id} 
contact_id={contact.id} 
compact
icon
type="button"
color="olive"
data-tooltip={txt("Browse Contact Conversations")}
onClick={
  () =>
  props.appStateUpdate({ openTicket: 0, filterContact: contact.id, filterContactName: contact.name }, { screen: true })
}
inverted={props.appState.config.darkMode}
>
  {contact.info.ticketCount }
<Icon name="comments" />
</Button>
 : ''}
<Button
size="tiny"
key={"remove" + contact.id} 
contact_id={contact.id} 
compact
icon
type="button"
color="grey"
data-tooltip={txt("Remove Contact")}
onClick={this.onContactRemoveButton}
inverted={props.appState.config.darkMode}
>
<Icon name="close" />
</Button>
</ButtonGroup>
          );
        });
        header.push(<Form.Field key="Contacts">{contactList} {codeContactAdd} </Form.Field>);
      }


    let tagCode = '';
    if (state.tags) {
      tagCode = Object.keys(state.tags).map((tag) => {

       if (state.representative) return (
          <Button
          size="tiny"
          key={tag} 
          tag={tag} 
          compact
          icon
          type="button"
          data-tooltip={new Date(state.tags[tag] * 1000).toLocaleString()}
          onClick={this.onTagRemoveButton}
          inverted={props.appState.config.darkMode}
          >
          {tag}
          <Icon name="close" />
          </Button>
        );
      else return <Label size="tiny" key={tag} data-tooltip={new Date(state.tags[tag] * 1000).toLocaleString()}>{tag}</Label>;
    });
    }

   if (tagCode || codeTagAdd) header.push(<Form.Field key="Tags"> {tagCode} {codeTagAdd} </Form.Field>);

      
    if (state.url)
      header.push(
        <Form.Field key="URL">
          <Label basic>
            <Icon name="linkify" /> {state.url}
          </Label>{" "}
        </Form.Field>
      );

    //display conversation (ticket) fields
    if (state.meta)
      if (state.meta.fields) {
        var conversationFields = [];
        let fieldNames = Object.keys(state.meta.fields);
        fieldNames.forEach((fieldName) => {
          if ( state.meta.fields[fieldName] ) conversationFields.push(
            <Form.Field key={fieldName}>
              <Label size="small">
                <Icon name="arrow right" /> {fieldName}
              </Label>{" "}
              <Label size="small" basic>
                {String(state.meta.fields[fieldName]).split("\n").map((i, key) => {
                  return (
                    <div key={key}>
                      <Linkify options={{ target: "_blank" }}>{i}</Linkify>
                    </div>
                  );
                })}
              </Label>
            </Form.Field>
          )
        }
        );
        if (conversationFields.length) header.push(<div key="ConversationFields">{conversationFields}</div>);
      }

    //form

    form.push(
      <span key="contactRow" style={{display:'flex', width:'100%', alignItems:'center', gap:'4px', flexWrap:'wrap', marginBottom:'2px'}}>
        <Label key="name">
          <Icon name="user" /> {props.appState.contact.name}{" "}
        </Label>
        <Label key="email">
          <Icon name="mail" /> {props.appState.contact.contact}{" "}
        </Label>
        {state.loading && state.created && state.loadingType !== 'submit' &&
          <Icon name="spinner" loading size="small" color="grey" className="vws-update-spinner" />
        }
      </span>
    );

    if (state.created)
      header.push(
        <ChatHistory
          key="history"
          appState={props.appState}
          appStateUpdate={props.appStateUpdate}
          messages={state.messages}
          messageEdit={this.onMessageEditButton}
        />
      );

    if (!state.created && !this.updating) {
      var contextCode = "";

      if (
        props.appState.config.context.content ||
        props.appState.config.context.creator
      )
        contextCode = (
          <Form.Field inline>
            {" "}
            {props.appState.config.context.content ? (
              <>
                {" "}
                <Label basic>
                  <Icon name="file" /> {props.appState.config.context.content}
                </Label>
              </>
            ) : (
              ""
            )}
            {props.appState.config.context.url ? (
              <>
                <Button
                  basic
                  compact
                  size="tiny"
                  icon
                  href={props.appState.config.context.url}
                  target="Content">
                  <Icon name="linkify" />{" "}
                </Button>
              </>
            ) : (
              ""
            )}{" "}
            {props.appState.config.context.creator ? (
              <>
                {" "}
                <Label basic>
                  <Icon name="user" /> {props.appState.config.context.creator}
                </Label>
              </>
            ) : (
              ""
            )}
          </Form.Field>
        );

      form.push(<Divider key="dividerDepartment" />);
      
      form.push(
        <Form.Group key="Department">
          <Form.Field>
          <label>
                <Icon name="box" /> {txt("Department")}
              </label>
            <Dropdown
              name="department"
              placeholder="Select Department..."
              selection
              options={props.appState.config.departments}
              value={state.department}
              onChange={onChange}
            />
          </Form.Field>
          {contextCode}
        </Form.Group>
      );

      //department fields
      var selectedDepartment = null; //selected department
      if (state.department)
        if (props.appState.config.departments) {
          selectedDepartment = props.appState.config.departments.find(
            (item) => item.value == state.department
          );

          if (selectedDepartment)
          {
            if (selectedDepartment.instructions) form.push(<Message size="small" key="instructions">{selectedDepartment.instructions}</Message>);
            
            if (selectedDepartment.fields) {
              form.push(
                <SupportFields
                  appState={props.appState}
                  upState={state}
                  upStateUpdate={(params) => this.setState(params)}
                  key="DepartmentFields"
                  fields={selectedDepartment.fields}
                />
              );
            }
          }
        }
    }

    form.push(
      <Form.Field key="message">
        {" "}
        <TextArea
          name="message"
          placeholder={txt("Write your message here") + "..."}
          onChange={onChange}
          value={state.message}></TextArea>{" "}
      </Form.Field>
    );

    if (!state.created)
      form.push(
        <Form.Field key="terms">
          <Checkbox
            id="agree-ticket"
            name="agree"
            label={txt("I agree to the Terms and Conditions")}
            checked={Boolean(state.agree)}
            onChange={onChange}
          /> &nbsp;
          <Button icon size="tiny" compact href={props.appState.config.termsURL} target="_terms" aria-label={txt("Read Terms and Conditions")}>
           <Icon name="external" aria-hidden="true" />
        </Button>    
        </Form.Field>
      );

    var costInfo = "";
    if (props.appState.config) {
      var cost = 0;
      if (!state.created && props.appState.config.costConversation)
        cost = props.appState.config.costConversation;
      if (state.created && props.appState.config.costMessage)
        cost = props.appState.config.costMessage;
      if (cost)
        costInfo = (
          <Label key="costInfo" tag size="small">
            <Icon name="money" /> {cost}
            {props.appState.config.costCurrency} / {props.appState.balance}
            {props.appState.config.costCurrency}
          </Label>
        );
    }

    var replyCode = "";
    //appStateUpdate({chatMentionMessage: messageID, chatMentionUser: userName}
    if (props.appState.chatMentionMessage) {
      replyCode = (
        <Label size="small" key="reply">
          <a href={ "#message" + props.appState.chatMentionMessage}><Icon name="reply" />{props.appState.chatMentionUser}</a> 
          <Button
            basic
            compact
            size="tiny"
            icon
            type="button"
            color="red"
            onClick={() =>
              props.appStateUpdate(
                { chatMentionMessage: 0, chatMentionUser: "" },
                { screen: true }
              )
            }>
            <Icon name="close" />
          </Button>
        </Label>
      );
    }

    form.push(
      <Form.Group widths="equal" key="SendBar">
        <Form.Field>
          <Button
            primary
            icon
            key="submit"
            disabled={!state.validated || state.loading}
            loading={state.loading && this.lastRequestType === 'submit'}
            type="submit"
            data-position="right center"
            data-tooltip={txt("Send Message")}
            inverted={props.appState.config.darkMode}>
            <Icon name="send" /> {txt("Send")}
          </Button>
          {costInfo}
          {codeLanguage}
          {props.appState.config.siteAdmin && <Button type="button" compact disabled={state.loading} onClick={() => {
            const recipients = Object.values(state.contacts || {}).filter(contact => !Number(contact.rep) && Number(contact.id) !== Number(props.appState.contact?.id));
            props.appStateUpdate({ screen: "staffDrafts", staffDraftReturn: "ticket", staffDraftConversation: state.created ? (state.ticket_id || props.appState.ticket_id || props.appState.openTicket || 0) : 0,
              staffDraftRecipient: recipients.length === 1 ? recipients[0].id : 0, staffDraftMessage: state.message || "" });
          }}>{txt("Draft reply")}</Button>}
          {codeAutosave}
          {codeWiki}
          {codeCan}
          {replyCode}
        </Form.Field>{" "}
        <Form.Field inline>
          <Button
            compact
            icon
            type="button"
            color="yellow"
            data-tooltip={txt("Emoticons")}
            onClick={this.onEmojiButton}
            inverted={props.appState.config.darkMode}>
            <Icon name="smile" />
          </Button>
             {codeUpload}
             {codeRecorder}
             {insertCan}
        </Form.Field>
      </Form.Group>
    );

    if (state.error)
      form.push(
        <Message negative key="requestError">
          <Message.Header>
            {state.timedOut ? txt('Connection timed out') : txt('Request failed')}
          </Message.Header>
          <p>{state.error}</p>
          <Button type="button" size="small" onClick={this.retryLastRequest}>
            <Icon name="redo" /> {txt('Retry')}
          </Button>
        </Message>
      );
    
    if (state.info) form.push(<Message key="info">{state.info}</Message>);
    if (state.validationInfo) form.push(<Message key="validationInfo">{state.validationInfo}</Message>);

    if (props.appState.openTicket)
      form.push(
        <Form.Field key="BackButton">
          <Button
            fluid
            icon
            key="back"
            type="button"
            data-position="top center"
            data-tooltip={txt("Back to Conversation List")}
            inverted={props.appState.config.darkMode}
            onClick={() =>
              props.appStateUpdate({ openTicket: 0 }, { screen: true })
            }>
            <Icon name="left arrow" /> {txt("Back to Conversation List")}
          </Button>
        </Form.Field>
      );

    form.push(emojiModalCode);
    form.push(recordModalCode);
    form.push(uploadModalCode);
    form.push(wikiModalCode);
    form.push(canModalCode);
    form.push(contactModalCode);
    form.push(languageModalCode);
    form.push(contactAddModalCode);
    form.push(messageModalCode);
    form.push(messageEditModalCode);
    form.push(tagAddModalCode);

    const newMessagesNotice = state.unreadMessageCount > 0 && state.canScrollDown ? (
      <div className="conversationNewMessageNotice" role="status" aria-live="polite">
        <Button
          type="button"
          size="small"
          color="blue"
          compact
          onClick={this.showNewMessages}
          inverted={props.appState.config.darkMode}>
          <Icon name="arrow down" />
          {state.unreadMessageCount === 1
            ? txt('New message')
            : state.unreadMessageCount + ' ' + txt('New messages')}
        </Button>
      </div>
    ) : null;

    const conversationScrollControls = state.canScrollUp || state.canScrollDown ? (
      <div className="conversationScrollControls" role="group" aria-label={txt('Conversation navigation')}>
        {state.canScrollUp && (
          <Button
            type="button"
            icon
            circular
            compact
            size="small"
            basic
            className="conversationScrollControlTop"
            onClick={this.scrollToTop}
            aria-label={txt('Scroll to first message')}
            data-position="left center"
            data-tooltip={txt('Scroll to first message')}
            inverted={props.appState.config.darkMode}>
            <Icon name="angle double up" />
          </Button>
        )}
        {state.canScrollDown && (
          <Button
            type="button"
            icon
            circular
            compact
            size="small"
            basic
            className="conversationScrollControlBottom"
            onClick={this.showNewMessages}
            aria-label={txt('Scroll to last message')}
            data-position="left center"
            data-tooltip={txt('Scroll to last message')}
            inverted={props.appState.config.darkMode}>
            <Icon name="angle double down" />
          </Button>
        )}
      </div>
    ) : null;

    if (state.created)
      return (
        <div
          key="ticket"
          className="layoutTicket"
          style={{ backgroundColor: props.appState.config.backgroundColor }}
          autoComplete="off">
          <div className="conversationPane">
            <div className="layContent" ref={this.setLayContentRef}>
              <Form key="formContent">{header}</Form>
            </div>
            {conversationScrollControls}
            {newMessagesNotice}
          </div>
          <Form
            className="layInputs"
            key="form"
            onSubmit={this.onSubmit}
            autoComplete="off"
            style={{ backgroundColor: props.appState.config.backgroundColor }}>
            {form}
          </Form>
        </div>
      );
    else
      return (
        <div
          key="ticket"
          style={{ backgroundColor: props.appState.config.backgroundColor }}
          autoComplete="off">
          <Form
            className="layInputs"
            key="form"
            onSubmit={this.onSubmit}
            autoComplete="off">
            <Header key="newticket">
              <Icon name="comments" size="small" />
              {txt("Open New Conversation")}
            </Header>
            <Divider />
            {form}
          </Form>
        </div>
      );
  }
}
