import logo from './logo.svg';
import React from 'react';
import {useEffect, useRef} from 'react';
import '@shopify/polaris/build/esm/styles.css';
import './App.scss';
import './css/ui.scss';
import './css/grid.scss';
import enTranslations from '@shopify/polaris/locales/en.json';
import {
  AppProvider, 
  Autocomplete,
  Avatar,
  Badge,
  Banner,
  Button,
  ButtonGroup,
  Card,
  Checkbox,
  ChoiceList,
  ContextualSaveBar,
  DisplayText,
  EmptyState,
  Filters,
  FormLayout,
  Frame,
  Grid,
  Heading,
  Icon,
  IndexTable,
  Layout,
  Link,
  Modal,
  Page,
  Pagination,
  Popover,
  ResourceList,
  ResourceItem,
  Select,
  SkeletonBodyText,
  SkeletonDisplayText,
  SkeletonPage,
  Tabs,
  TextContainer,
  TextStyle,
  TextField,
  Tooltip,
  Label,
} from '@shopify/polaris';
import {
  AnalyticsMinor,
  BlogMajor,
  CircleInformationMajor,
  DeleteMajor,
  HomeMajor,
  PageMajor,
  ProductsMajor,
  QuestionMarkMajor,
  SearchMinor,
  SortMinor,
} from '@shopify/polaris-icons';

//refs?


//global components
import Plans from './components/global/Plans';
import IndexTableCustomHeadings from './components/global/IndexTableCustomHeadings';
import Configurables from './components/global/Configurables';

const ajaxUrl = 'https://dynasort.immersiveecommerce.com/ajax.php';
const planUrl = 'https://dynasort.immersiveecommerce.com/change-plans.php';
const downloadProductsUrl = 'https://dynasort.immersiveecommerce.com/download.php';
const adminAppSlug = 'dynasort';
var urlParams = new URLSearchParams(window.location.search);
var storeUrl = urlParams.get('shop');
let hasRunInit = false;
const resourceListItemCount = 25;

const revertToSelectOptions = [
  {label:'Best Selling',value:'best-selling'},
  {label:'Product title A-Z',value:'alpha-asc'},
  {label:'Product title Z-A',value:'apha-desc'},
  {label:'Highest price',value:'price-desc'},
  {label:'Lowest Price',value:'price-asc'},
  {label:'Newest',value:'created-desc'},
  {label:'Oldest',value:'created-asc'},
  {label:'Manual',value:'manual'},
];
const attributeOptionTypes = [
  {label:'Quantity',value:'quantity'},
  {label: 'Full Size Run', value: 'full-size-run'},
  {label:'Age Of Newest Variant',value:'age-of-newest-variant'},
  {label:'Sales (Last 30 Days)',value:'sales-last-30-days'},
  {label:'Sales (Last 7 Days)',value:'sales-last-7-days'},
  {label:'Margin',value:'margin'},
  {label:'Sold Out',value:'sold-out'},
  {label:'On Sale',value:'on-sale'},
  {label: 'Coming Soon', value: 'coming-soon'},
  {label: 'Brand Boost', value: 'brand-boost'},
  //{label: 'Yotpo Reviews', value: 'yotpo'}, //hidden for dev/review
]
const initAttributeRow = {
  select:{
    options:attributeOptionTypes,
    value:attributeOptionTypes[0].value,
  },
  value:0,
}
const soldOutOptions = [
  {label:'Move to bottom',value:'move-to-bottom'},
  {label:'Leave in place',value:'leave-in-place'},
];
const tieBreaker = [
  {label:'Highest price',value:'highest-price'},
  {label:'Highest margin',value:'highest-margin'},
  {label:'Best selling',value:'best-selling'},
  {label:'Lowest Cost',value:'lowest-cost'},
  {label:'Most inventory',value:'most-inventory'},
]


let settingsRevert = {};
let metricsRevert = {};
let metricsRevertIndex = 0;

class App extends React.Component {
  constructor(props) {
    super(props);    

    //refs yay

    this.state = {
      showOnboarding:true,
      showCacheStatus:false,
      onboarding_flow:{
        onboarding_modal_dismissed:true,
        onboarding_steps:{
          complete:true,
          metrics:true,
          collections:true,
          status:true,
        }
      },
      showOnboardingModal:false,
      cacheStatus:{
        products_cached:0,
        products_total:0,
        collections_cached:0,
        collections_total:0,
        orders_cached:0,
        orders_total:0,
      },
      metaData:{},
      date: new Date(),
      status:'On',
      statusModalOpen:false,
      init:{
        ui_loading:true,
        show_tabs:false,
        show_plans:false,
        plans:[],
        plan_token:'',
        password_enabled:'',
        shop_email:'',
        current_plan:'',
        permissions:{
          collections:0,
          metrics:0,
          custom_attributes:false,
          partner_attributes:false,
          boost:false,
          exports:false,        
        }
      },
      settings:{
        showProcessingSave:false,
        showNotificationsSave:false,
        processingSaveLoading:false,
        notificationsSaveLoading:false,
        processing_interval:{
          value:'',
          options:[],
        },
        days_of_the_week:{
          value:'',
          options:[],
        },
        hours_of_the_day:{
          value:'',
          options:[],
        },
        email_shop_owner:{
          value:"false",
        },
        additional_emails:'',
        additional_emails_valid:true,
        //:'',
        notify_order_changed:{
          value:'',
        },
        notify_collections_sorted:{
          value:'',
        },
      },
      /* save bar */
      saveBar:{
        show:false,
        context:'',
      },
      /* tabs vars */
      activeTab:0,
      tabs:[
        {
          id: 'collections',
          content: 'Collections',
          panelID: 'collections',
        },
        {
          id: 'metrics',
          content: 'Metrics',
          panelID: 'metrics',
        },
        {
          id: 'products',
          content: 'Products',
          panelID: 'products',
        },
        {
          id: 'attributes',
          content: 'Attributes',
          panelID: 'attributes',
        },
        {
          id: 'settings',
          content: 'Settings',
          panelID: 'settings',
        },
        {
          id: 'plans',
          content: 'Plans',
          panelID: 'plans',
        },
      ],
      activeCollectionsTab: 0,
      collectionsTabs: [
        {
          id: 'all',
          content: 'All',
          accessibilityLabel: 'All collections',
          panelID: 'collections-tabs-1',
        },
        {
          id: 'dynamic',
          content: 'Dynamic',
          accessibilityLabel: 'Dynamic collections',
          panelID: 'collections-tabs-2',
        },
        {
          id: 'traditional',
          content: 'Traditional',
          panelID: 'collections-tabs-3',
        },
      ],
      activeMetricsTab: 0,
      metricsTabs: [
        {
          id: 'all',
          content: 'All',
          accessibilityLabel: 'All metrics',
          panelID: 'metrics-tabs-1',
        },
        {
          id: 'booster',
          content: 'Boosted',
          accessibilityLabel: 'Boosted metrics',
          panelID: 'metrics-tabs-2',
        },
        {
          id: 'active',
          content: 'Active',
          panelID: 'metrics-tabs-3',
        },
      ],
      /* Autocomplete vars 
      collectionsFilterValue:'',
      collectionsOptions:[],
      metricsFilterValue:'',
      metricsOptions:[],
      */
      /* resource list vars */
      collectionsFilters:[
        /*
        {
          key: 'collectionFiltersType',
          label: 'Type',
          filter: (
            <TextField
              label="Type"
              value={''}
              onChange={() => { console.log('handleTaggedWithChange')}}
              autoComplete="off"
              labelHidden
            />
          ),
          shortcut: true,
        },
        */
      ],
      collectionsAllCheckboxSelected:false,
      collectionsSelectedItems:[],
      collectionsResourceItemsPage:0,
      collectionsResourceItemsPages:0,
      collectionsResourceItemsType:'',
      collectionsResourceItemEnabled:0,
      collectionsResourceItems:[],
      collectionBeingEditedModal:false,
      collectionBeingEditedModalBulk:false,      
      collectionBeingEdited:{
        enabled:'0',
        handle:'',
        id:0,
        lastSorted:'',
        metricId:"0",
        name:'',
        productCount:0,
        revertSorting:'',
        resourceIndex:0,
      },
      collectionsBulkEditMetricSetOptions:[],
      collectionsBulkEditMetricSetValue: '',
      collectionsBulkEditRevertOptions:[],
      collectionsBulkEditRevertValue:'',
      collectionsBulkEditShowSave:false,
      collectionsBulkEditShowSave:false,
      collectionsBulkEditSaveLoading:false,
      processingBulkEdit:false,
      collectionFilterQueryValue:'',
      /* metrics vars */
      metricssResourceItemsPage:0,
      metricsResourceItemsPages:0,
      metricsResourceItems:[],
      metricsResourceItemsCount:0,
      metricsDefaultId:0,
      metricsFilterQueryValue:'',
      //metricsBeingEditedId:0,
      metricsBeingEdited:{
        id:0,
        title:'',
        attributes:[],
        boost:false,
        is_default:false,
        soldOutValue:soldOutOptions[0],
        tieBreakerValue:tieBreaker[0],
        products:[],
      },
      metricsBeingEditedDefault:{
        id:0,
        title:'',
        attributes:[],
        boost:false,
        is_default:false,
        soldOutValue:soldOutOptions[0],
        tieBreakerValue:tieBreaker[0],
        products:[],
      },
      sidebarCollectionsValue:'',
      metricsSidebarCollections:[],
      /* product vars */
      productAttributes:{
        data:[],
        custom:[],
        partner:[],
      },
      //eof attributes
      /* products vars */
      productMetricsOptions:[],
      productsMetricsSelected:0,
      showProductCount:100,
      showProductIndex:0,
      productsCollectionsOptions:[],
      productsCollectionsSelected:'',
      filtersProduct: [
        /*
        {
          key: 'editProductRows',
          label: 'Edit Product Rows',
          filter: (
            <ChoiceList
              title="Edit Product Rows"
              titleHidden
              choices={[
                {label: 'Margin', value: 'margin'},
                {label: 'Sales', value: 'sales'},
                {label: 'On Sale', value: 'on-sale'},
                {label: 'Full Size Run', value: 'full-size-run'},
                {label: 'Quantity', value: 'quantity'},
              ]}
              selected={['margin','sales','on-sale','full-size-run','quantity']}
              onChange={() => { console.log('handleEditProductRowsChange')}}
              allowMultiple
            />
          ),
          shortcut: true,
        },
        */
      ],
      productsMetricsId:0,
      products:[],
      /* metrics vars */
      metricsCollectionProductsAttributes:{},
      metricsCollectionProductsBoost:"0",
      metrics:{
        createMetricsDisplay:false,
        demo:{
          attributes:[
            {
              type:'Margin',
              weight:35,
            },
            {
              type:'On Sale',
              weight:20,
            },
            {
              type:'Sales',
              weight:15,
            },

          ],
          products:[]
        },
      },
      metricsPreviewProducts:[],
      /* product vars */
      productsPreviewItems:[],
      productsResourceItems:[],
      /* heartbeat vars */
      heartbeat:{
        banners:{
          global:[],
        }
      },
      errors:{
        additional_emails:false,
      },
      popoverFilters:{
        collections:{
          value:'date-asc',
          show:false
        },
        collectionsActive:{
          value:'all',
          show:false,//run off of the above
        },
        metrics:{
          value:'date-asc',
          show:false,
        },
      }
    };

    //bindings 
    this.toggleStatus = this.toggleStatus.bind(this);
    this.statusShowModal = this.statusShowModal.bind(this);
    this.handleNavTabChange = this.handleNavTabChange.bind(this);
    this.handleCollectionsNavChange = this.handleCollectionsNavChange.bind(this);
    this.handleMetricsNavChange = this.handleMetricsNavChange.bind(this);
    this.changeCollectionsFilterValue = this.changeCollectionsFilterValue.bind(this);
    this.changeMetricsFilterValue = this.changeMetricsFilterValue.bind(this);
    this.setCollectionsSelectedItems = this.setCollectionsSelectedItems.bind(this);
    this.getCollectionResourceItems = this.getCollectionResourceItems.bind(this);
    this.collectionResourcePage = this.collectionResourcePage.bind(this);
    this.setCollectionStatus = this.setCollectionStatus.bind(this);
    this.collectionDetailsModal = this.collectionDetailsModal.bind(this);
    this.displayEditMetrics = this.displayEditMetrics.bind(this);
    this.getMetrics = this.getMetrics.bind(this);
    this.editMetricsObject = this.editMetricsObject.bind(this);
    this.addMetricsAttributeRow = this.addMetricsAttributeRow.bind(this);
    this.removeMetricAttribute = this.removeMetricAttribute.bind(this);
    this.getMetricsPreviewProducts = this.getMetricsPreviewProducts.bind(this);
    this.getPreviewProducts = this.getPreviewProducts.bind(this);
    this.getMetricsProductsPreview = this.getMetricsProductsPreview.bind(this);
    this.getMetricsCollections = this.getMetricsCollections.bind(this);
    this.doDiscardAction = this.doDiscardAction.bind(this);
    this.doSaveAction = this.doSaveAction.bind(this);
    this.doSaveMetrics = this.doSaveMetrics.bind(this);
    this.editMetrics = this.editMetrics.bind(this);
    this.metricsChangeCollection = this.metricsChangeCollection.bind(this);
    this.productsMetricsChanged = this.productsMetricsChanged.bind(this);
    this.getMetricsCollectionProducts = this.getMetricsCollectionProducts.bind(this);
    this.changeProductsCollectionsChanged = this.changeProductsCollectionsChanged.bind(this);
    this.loadMoreProducts = this.loadMoreProducts.bind(this);
    this.changeSettingsSelect = this.changeSettingsSelect.bind(this);
    this.saveProcessingSettings = this.saveProcessingSettings.bind(this);
    this.discardProcessingSettings = this.discardProcessingSettings.bind(this);
    this.changeSettingsCheckbox = this.changeSettingsCheckbox.bind(this);
    this.changeSettingsAdditionalEmails = this.changeSettingsAdditionalEmails.bind(this);
    this.saveNotificationsSettings = this.saveNotificationsSettings.bind(this);
    this.discardNotificationsSettings = this.discardNotificationsSettings.bind(this);   
    this.getAttributes = this.getAttributes.bind(this); 
    this.changeConfigurables = this.changeConfigurables.bind(this);
    this.changeConfigurableTitle = this.changeConfigurableTitle.bind(this);
    this.saveConfigurables = this.saveConfigurables.bind(this);
    this.attributeStatus = this.attributeStatus.bind(this);
    this.collectionsAllCheckboxToggle = this.collectionsAllCheckboxToggle.bind(this);
    this.collectionsToggleCheckAll = this.collectionsToggleCheckAll.bind(this);
    this.isCollectionsAllChecked = this.isCollectionsAllChecked.bind(this);
    this.selectCollectionItem = this.selectCollectionItem.bind(this);
    this.uncheckAllCollectionsResourceItems = this.uncheckAllCollectionsResourceItems.bind(this);
    this.collectionsBulkToggle = this.collectionsBulkToggle.bind(this);
    this.collectionsBulkEdit = this.collectionsBulkEdit.bind(this);
    this.saveCollectionsEditBulk = this.saveCollectionsEditBulk.bind(this);
    this.discardCollectionsEditBulk = this.discardCollectionsEditBulk.bind(this);
    this.changeCollectionsEditBulkMetrics = this.changeCollectionsEditBulkMetrics.bind(this);
    this.changeCollectionsEditBulkRevert = this.changeCollectionsEditBulkRevert.bind(this);
    this.collectionFilterChangeQueryValue = this.collectionFilterChangeQueryValue.bind(this);
    this.togglePopover = this.togglePopover.bind(this);
    this.changePopover = this.changePopover.bind(this);
    this.metricsFilterChangeQueryValue = this.metricsFilterChangeQueryValue.bind(this);
    this.sidebarCollectionsChange = this.sidebarCollectionsChange.bind(this);
    this.getMetricsSidebarCollections = this.getMetricsSidebarCollections.bind(this);
    this.editBoost = this.editBoost.bind(this);
    this.saveBoost = this.saveBoost.bind(this);
    this.viewProductScores = this.viewProductScores.bind(this);
    this.duplicateMetrics = this.duplicateMetrics.bind(this);
    this.checkCacheStatus = this.checkCacheStatus.bind(this);
    this.getAttributeOptionTypes = this.getAttributeOptionTypes.bind(this);
    this.showOnboardingModal = this.showOnboardingModal.bind(this);
    this.doOnboardingModalClick = this.doOnboardingModalClick.bind(this);
    this.updateOnboardingModal = this.updateOnboardingModal.bind(this);
    this.addAttribute = this.addAttribute.bind(this);
    this.deleteAttribute = this.deleteAttribute.bind(this);
  }
  /* Lifecycle methods */
  componentWillMount() {  
    if(!hasRunInit){
      //console.log('componentDidMount'); 
      this.doInit();
      //this.startHeartBeat();
      //this.getChartControls();
      //hasRunInit = true;
    }

  }

  /* Generic methods */

  doInit() {
    //console.log('doInit()');
    const data = {
      action: 'init',
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log(json);
      this.setState({ init: json });
      //check for no iframe
      if(window.top == window.self) {
        // Top level window
        console.log('not in frame!');
        window.location.replace('https://'+storeUrl+'/admin/apps/'+adminAppSlug+'/');
      }
      //set status
      let status;
      if(parseInt(json.app_status) > 0) {
        status = 'On';
      } else {
        status = 'Off';
      }
      //show plans tab if needed
      if(json.show_plans){
        console.log('show plans');
        this.setState({ activeTab: 5 }); //6 = last tab here
      }
      if(json.settings){
        //do all settings here
        this.setState({ 
          settings:json.settings,
          status:status,
        },() => {
          for (const property in json.settings) {
            //console.log(`${property}: ${object[property]}`);
            if(json.settings[property].hasOwnProperty('value')){
              settingsRevert[property] = json.settings[property].value;
            }
          }
          //console.log(settingsRevert);
        });
      }
      if(json.show_cache_status){
        this.setState({
          showCacheStatus:true,
          cacheStatus:json.show_cache_status
        },() =>{
          this.checkCacheStatus();
        })
      } else {
        this.setState({showCacheStatus:false})
      }
      if(json.meta_data){
        this.setState({
          metaData:json.meta_data,
        },() =>{
          //console.log(this.state.metaData);
        })
      } else {
        this.setState({showCacheStatus:false})
      }
      //onboarding
      if(json.onboarding_flow){
        if(!json.onboarding_flow.onboarding_steps.complete) {
          console.log('show onboarding modal');
          this.showOnboardingModal(true);
        }
        this.setState({onboarding_flow:json.onboarding_flow});
      }

    }).then(()=>{
      //console.log(this.state.init)
      this.getCollections();
      this.getMetrics();
      this.getAttributes();
    }).then(() => {
      //this.getProducts(); //get default products on first load
      hasRunInit = true;
    });
  }
  checkCacheStatus() {
    console.log('checkCacheStatus');
    const data = {
      action: 'get_shop_onboarding_status',
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log(json);
      if(json){
        this.setState({cacheStatus:json})
        const timer = setTimeout(() => {
          this.checkCacheStatus();
        }, 1000);
      } else {
        console.log('stop cache check');
        this.setState({
          cacheStatus:json,
          showCacheStatus:false,
          
        },() => {
          //console.log(this.state.cacheStatus);
          this.getCollections();
          this.getProducts();
        });
      }
      /*
      this.setState({
        statusModalOpen:false,
        status:newStatus,
      });
      */
    });

  }
  toggleStatus() {
    //console.log('toggleStatus: '+this.state.status);
    let newStatus;
    if(this.state.status == 'On'){
      newStatus = 'Off';
    } else {
      newStatus = 'On';
    }
    const data = {
      action: 'toggle_status',
      status:newStatus,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      console.log(json);
      this.setState({
        statusModalOpen:false,
        status:newStatus,
      });
      this.updateOnboardingModal();
    });

  }
  statusShowModal(bool){
    //console.log('statusShowModal: '+bool);
    this.setState({statusModalOpen:bool});
  }
  togglePopover(popoverType){
    console.log('togglePopover: '+popoverType);
    let popoverFiltersCopy = this.state.popoverFilters;
    popoverFiltersCopy[popoverType].show = !this.state.popoverFilters[popoverType].show;
    this.setState({
      popoverFilters:popoverFiltersCopy
    });
  }
  changePopover = (value,popoverType) => {
    console.log('changePopover: '+value+' '+popoverType);
    let popoverFiltersCopy = this.state.popoverFilters;
    popoverFiltersCopy[popoverType].value = value;
    popoverFiltersCopy[popoverType].show = !this.state.popoverFilters[popoverType].show;
    this.setState({
      popoverFilters:popoverFiltersCopy
    },() => {
      this.getCollections();
      this.getMetrics();
    });
  }

  doSaveAction() {
    console.log('doSaveAction: '+this.state.saveBar.context);
    switch(this.state.saveBar.context){
      case 'metrics':
        this.doSaveMetrics();
    }
  }
  doDiscardAction() {
    console.log('doDiscardAction: '+this.state.saveBar.context);
    if(this.state.saveBar.context == 'metrics'){
      //console.log('metrics edited');
      //console.log(this.state.metricsBeingEdited);
      //console.log('metricsRevert');
      //console.log(metricsRevertIndex);
      //console.log(metricsRevert);
      //let metricsCopy = this.state.metrics;
      //metricsCopy.createMetricsDisplay = false;
      //let metricsResourceItemsCopy = this.state.metricsResourceItems;
      //metricsResourceItemsCopy[metricsRevertIndex] = metricsRevert;

      let saveBarCopy = this.state.saveBar;
      saveBarCopy.show = false;
      saveBarCopy.context = '';

      this.setState({
        //metrics:metricsCopy,
        saveBar:saveBarCopy,
        //metricsResourceItems:metricsResourceItemsCopy,
      },() =>{
        this.displayEditMetrics(false,true);
        this.getMetrics();
      });
    }
  }
  /* Navigation Methods */
  handleNavTabChange(selectedTab) {
    //this.setState({selectedTab});
    //console.log('handleTabChange:'+selectedTab);
    this.setState({ activeTab: selectedTab},() => {
      //do stuff?
      //close edit metrics if no metrics tabs clicked
      if(selectedTab != 1){
        this.displayEditMetrics(false,true)
      }
    });
  }
  handleCollectionsNavChange(selectedTab) {
    //this.setState({selectedTab});
    //console.log('handleTabChange:'+selectedTab);
    this.setState({ 
      activeCollectionsTab: selectedTab,
      collectionsSelectedItems:[],
      collectionsAllCheckboxSelected:false,
      collectionsResourceItemsPage:0,
      collectionFilterQueryValue:'',
    },() => {
      this.getCollections();
    });
  }
  handleMetricsNavChange(selectedTab) {
    //this.setState({selectedTab});
    console.log('handleTabChange:'+selectedTab);
    this.setState({ activeMetricsTab: selectedTab},() => {
      this.getMetrics();
    });
  }
  metricsFilterChangeQueryValue = (value) => {
    console.log('metricsFilterChangeQueryValue: '+value);
    this.setState({metricsFilterQueryValue:value},() =>{
      this.getMetrics();
    });
  }

  /* Autocomplete methods */
  changeCollectionsFilterValue = (value) => {
    //console.log('changeCollectionsFilterValue: '+value);
    this.setState({collectionsFilterValue:value})
    
  }
  changeMetricsFilterValue = (value) => {
    //console.log('changeMetricsFilterValue: '+value);
    this.setState({metricsFilterValue:value})
    
  }
  /* Resource List Methods */
  /* collections methods */

  setCollectionsSelectedItems = (selected) => {
    this.setState({collectionsSelectedItems:selected});
  }
  collectionsBulkToggle(enable) {
    console.log('collectionsBulkToggle: '+enable);
    console.log(this.state.collectionsResourceItems);
    let collectionsResourceItemsCopy = this.state.collectionsResourceItems;
    let collectionsResourceItemEnabledCopy = 0;
    //let collectionsResourceItemEnabledCopy = this.state.collectionsResourceItemEnabled;
    let enabled;
    if(enable){
      enabled = "1";
    } else {
      enabled = "0";
    }
    for (let i = 0; i < collectionsResourceItemsCopy.length; i++) {
      let indexOfArray = this.state.collectionsSelectedItems.indexOf(collectionsResourceItemsCopy[i].id);
      console.log('indexOfArray :'+indexOfArray);
      if(indexOfArray > -1){
        if (indexOfArray > -1) { // only splice array when item is found
          collectionsResourceItemsCopy[i].enabled = enabled;
          /*
          if(
            enabled == "1"
            &&
            collectionsResourceItemsCopy[i].enabled == "0"
          ){
            collectionsResourceItemEnabledCopy++;
          } else if(
            enabled == "0"
            &&
            collectionsResourceItemsCopy[i].enabled == "1"
          ) {
            collectionsResourceItemEnabledCopy--;
          }
          */
        }      
      } 
      if(collectionsResourceItemsCopy[i].enabled == "1"){
        collectionsResourceItemEnabledCopy++;
      }
    }    
    const data = {
      action: 'collections_bulk_toggle',
      resources:this.state.collectionsSelectedItems,
      status:enable,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      console.log(json);
      this.setState({
        collectionsResourceItems:collectionsResourceItemsCopy,
        collectionsResourceItemEnabled:collectionsResourceItemEnabledCopy,
      },() => {
        this.updateOnboardingModal();
      });
    });
  }
  changeCollectionsEditBulkMetrics = (value) => {
    console.log('changeCollectionsEditBulkMetrics: '+value);
    this.setState({
      collectionsBulkEditMetricSetValue:value,
      collectionsBulkEditShowSave:true,
    });
  }
  changeCollectionsEditBulkRevert = (value) => {
    console.log('changeCollectionsEditBulkRevert: '+value);
    this.setState({
      collectionsBulkEditRevertValue:value,
      collectionsBulkEditShowSave:true,
    });
  }
  saveCollectionsEditBulk() {
    console.log('saveCollectionsEditBulk');
    this.setState({
      collectionsBulkEditSaveLoading:true
    },() =>{
      const data = {
        action: 'save_bulk_collections',
        resources:this.state.collectionsSelectedItems,
        metric:this.state.collectionsBulkEditMetricSetValue,
        revert:this.state.collectionsBulkEditRevertValue,
        store_url: storeUrl,
      }  
      fetch('/ajax.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })
      .then(response => response.json())
      .then((json) =>{
        console.log(json);
        let collectionsResourceItemsCopy = this.state.collectionsResourceItems;
        console.log('collectionsResourceItemsCopy n: '+collectionsResourceItemsCopy.length);
        for (let i = 0; i < collectionsResourceItemsCopy.length; i++) {
          console.log('checking id: '+collectionsResourceItemsCopy[i].id);
          const index = this.state.collectionsSelectedItems.indexOf(collectionsResourceItemsCopy[i].id);
          console.log('index: '+index);
          if (index > -1) { // only splice array when item is found
            //collectionsSelectedItemsCopy.splice(index, 1); // 2nd parameter means remove one item only
            console.log('change: '+collectionsResourceItemsCopy[i].name);
            console.log(collectionsResourceItemsCopy[i]);
            if(this.state.collectionsBulkEditMetricSetValue != ''){
              collectionsResourceItemsCopy[i].metricId = this.state.collectionsBulkEditMetricSetValue;
              collectionsResourceItemsCopy[i].metricName = json.name;
            }
            if(this.state.collectionsBulkEditRevertValue != ''){
              collectionsResourceItemsCopy[i].revertSorting = this.state.collectionsBulkEditMetricSetValue;
            }
          }
          /*
          collectionsResourceItemsCopy[i].checked = selected;
          if(selected){
            collectionsSelectedItemsCopy.push(collectionsResourceItemsCopy[i].id);
          } else {
            let id = collectionsResourceItemsCopy[i].id;
            const index = collectionsSelectedItemsCopy.indexOf(id);
            if (index > -1) { // only splice array when item is found
              collectionsSelectedItemsCopy.splice(index, 1); // 2nd parameter means remove one item only
            }
          }
          */
        }        
        this.setState({
          collectionsBulkEditSaveLoading:false,
          collectionsBulkEditShowSave:false,
          collectionsResourceItems:collectionsResourceItemsCopy,
          //collectionsResourceItemsPages:collectionsResourceItemsPages
          
        },()=> {
          //this.getPreviewProducts();
        });
      }); 
    });

       
  }
  discardCollectionsEditBulk(){
    console.log('discardCollectionsEditBulk');
    this.collectionsBulkEdit(true); //reset
    this.collectionsBulkEdit(false); //close

  }

  uncheckAllCollectionsResourceItems() {
    console.log('uncheckAllCollectionsResourceItems');
    let collectionsResourceItemsCopy = this.state.collectionsResourceItems;
    let collectionsSelectedItemsCopy = this.state.collectionsSelectedItems;
    //console.log('begin: '+begin+' end: '+end);    
    collectionsSelectedItemsCopy = [];
    for (let i = 0; i < collectionsResourceItemsCopy.length; i++) {
      collectionsResourceItemsCopy[i].checked = false;
    }
    this.setState({
      collectionsAllCheckboxSelected:false,
      collectionsResourceItems:collectionsResourceItemsCopy,
      collectionsSelectedItems:collectionsSelectedItemsCopy,
    },() => {
      this.isCollectionsAllChecked();
    });
  }
  collectionsAllCheckboxToggle = (selected) => {
    //console.log('collectionsAllCheckboxToggle: '+selected);
    //console.log('collectionsResourceItemsPage: '+this.state.collectionsResourceItemsPage);
    //const pagedItems = this.getCollectionResourceItems(this.state.collectionsResourceItemsPage);
    //console.log(this.state.collectionsResourceItems);
    //console.log(pagedItems);
    let collectionsResourceItemsCopy = this.state.collectionsResourceItems;
    let collectionsSelectedItemsCopy = this.state.collectionsSelectedItems;
    const page = this.state.collectionsResourceItemsPage;
    const begin = (0 + (page * resourceListItemCount));
    const end = (resourceListItemCount + (page * resourceListItemCount));
    console.log('begin: '+begin+' end: '+end);    
    for (let i = begin; i < end; i++) {
      if(collectionsResourceItemsCopy[i]){
        collectionsResourceItemsCopy[i].checked = selected;
        if(selected){
          collectionsSelectedItemsCopy.push(collectionsResourceItemsCopy[i].id);
        } else {
          let id = collectionsResourceItemsCopy[i].id;
          const index = collectionsSelectedItemsCopy.indexOf(id);
          if (index > -1) { // only splice array when item is found
            collectionsSelectedItemsCopy.splice(index, 1); // 2nd parameter means remove one item only
          }
        }
      }
    }
    this.setState({
      collectionsAllCheckboxSelected:selected,
      collectionsResourceItems:collectionsResourceItemsCopy,
      collectionsSelectedItems:collectionsSelectedItemsCopy,
    },() => {
      this.isCollectionsAllChecked();
    });
    //console.log(this.state.collectionsResourceItems);
  }
  selectCollectionItem = (item,index,checked) => {
    const page = this.state.collectionsResourceItemsPage;
    index = index + (page * resourceListItemCount);
    console.log('selectCollectionItem checked? '+item.checked+' index: '+index);
    let collectionsResourceItemsCopy = this.state.collectionsResourceItems;
    let collectionsSelectedItemsCopy = this.state.collectionsSelectedItems;
    collectionsResourceItemsCopy[index].checked = !collectionsResourceItemsCopy[index].checked;
    const indexOfArray = collectionsSelectedItemsCopy.indexOf(collectionsResourceItemsCopy[index].id);
    console.log('indexOfArray :'+indexOfArray);
    if(indexOfArray > -1){
      console.log('remove it: '+item.id);
      if (indexOfArray > -1) { // only splice array when item is found
        collectionsSelectedItemsCopy.splice(indexOfArray, 1); // 2nd parameter means remove one item only
      }      
    } else {
      if (indexOfArray < 0) { // only splice array when item is found
        console.log('add it: '+item.id);
        collectionsSelectedItemsCopy.push(item.id); // 2nd parameter means remove one item only
      } 
    }
    console.log(collectionsSelectedItemsCopy);
    this.setState({
      collectionsResourceItems:collectionsResourceItemsCopy,
      collectionsSelectedItems:collectionsSelectedItemsCopy,
    },() => {
      this.isCollectionsAllChecked();
    });
  }
  isCollectionsAllChecked() {
    const page = this.state.collectionsResourceItemsPage;
    const begin = (0 + (page * resourceListItemCount));
    const end = (resourceListItemCount + (page * resourceListItemCount));
    //console.log('begin: '+begin+' end: '+end);  
    let checkedCount = 0;  
    for (let i = begin; i < end; i++) {
      if(this.state.collectionsResourceItems[i] //if defined on last page
        &&
        this.state.collectionsResourceItems[i].checked
      ) {
        checkedCount++;
        //console.log('i: '+i+' checked, total: '+checkedCount);
      }
    }
    let checked;
    if(checkedCount == 0){
      checked = false;
    } else if (checkedCount == resourceListItemCount){
      checked =  true;
    } else {
      checked=  "indeterminate";
    }
    this.setState({
      collectionsAllCheckboxSelected:checked
    })
  }
  collectionsToggleCheckAll(checked) {
    console.log('collectionsToggleCheckAll: '+checked);
    let collectionsResourceItemsCopy = this.state.collectionsResourceItems;
    let collectionsSelectedItemsCopy = [];
    for (let i = 0; i < collectionsResourceItemsCopy.length; i++) {
      collectionsResourceItemsCopy[i].checked = checked;
      if(checked){
        collectionsSelectedItemsCopy.push(collectionsResourceItemsCopy[i].id);
      } 
    }
    //if(!checked){
    //  collectionsSelectedItemsCopy = [];
    //}
    this.setState({
      collectionsResourceItems: collectionsResourceItemsCopy,
      collectionsSelectedItems: collectionsSelectedItemsCopy,
    },() => {
      this.isCollectionsAllChecked();
    });    
  }
 

  getCollections() {
    //console.log('getCollections');
    const data = {
      action: 'get_collections',
      tab:this.state.activeCollectionsTab,
      query:this.state.collectionFilterQueryValue,
      sort:this.state.popoverFilters.collections.value,
      active:this.state.popoverFilters.collectionsActive.value,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log(json);
      let collectionsResourceItemEnabled = 0;
      for (let i = 0; i < json.collections.length; i++) {
        if(json.collections[i].enabled == "1"){
          collectionsResourceItemEnabled++;
        }
      }
      let collectionsResourceItemsPages = Math.ceil((json.collections.length / resourceListItemCount));
      this.setState({
        collectionsResourceItems:json.collections,
        collectionsResourceItemsPages:collectionsResourceItemsPages,
        collectionsResourceItemsPage:0,
        collectionsResourceItemEnabled:collectionsResourceItemEnabled,
      },()=> {
        this.getPreviewProducts();
      });
    }).then(()=>{
      //what else?

    });
  }
  collectionFilterChangeQueryValue = (value) => {
    console.log('collectionFilterChangeQueryValue: '+value);
    this.setState({
      collectionFilterQueryValue:value,
    },() =>{
      this.getCollections();
    });
  }
  getCollectionResourceItems(page){
    //console.log('collectionsResourceItemsPages: '+this.state.collectionsResourceItemsPages);
    const begin = (0 + (page * resourceListItemCount));
    const end = (resourceListItemCount + (page * resourceListItemCount));
    return this.state.collectionsResourceItems.slice(begin,end);
  }
  collectionResourcePage(i){
    const newPage = this.state.collectionsResourceItemsPage + i;
    this.setState({collectionsResourceItemsPage:newPage},() => {
      this.isCollectionsAllChecked();
    });
  }
  setCollectionStatus = (cid,index,value) => {
    //console.log('page: '+this.state.collectionsResourceItemsPage+' x '+resourceListItemCount);
    let resourceIndex = (this.state.collectionsResourceItemsPage * resourceListItemCount) + index;
    console.log('cid: '+cid+' index: '+index+' value: '+value);
    let collectionsResourceItemsCopy = this.state.collectionsResourceItems;
    let collectionsResourceItemEnabledCopy = this.state.collectionsResourceItemEnabled;
    if(parseInt(value) == 1){
      collectionsResourceItemEnabledCopy++;
    } else {
      collectionsResourceItemEnabledCopy--;
    }
    collectionsResourceItemsCopy[resourceIndex].enabled = value;
    this.setState({
      collectionsResourceItems:collectionsResourceItemsCopy,
      collectionsResourceItemEnabled:collectionsResourceItemEnabledCopy,
    });
    const data = {
      action: 'set_collection_status',
      status:value,
      collection_id:cid,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      console.log(json);
      this.updateOnboardingModal();
    });

  }
  collectionsBulkEdit(display) {
    console.log('collectionsBulkEdit');
    let collectionsBulkEditMetricSetOptions = [{label:"Keep Current Value",value:''}];
    let collectionsBulkEditRevertOptions = [{label:"Keep Current Value",value:''},...revertToSelectOptions];
    
    //setup metric sets
    console.log(this.state.metricsResourceItems);
    this.state.metricsResourceItems.map(function(item, i){
      collectionsBulkEditMetricSetOptions.push({label:item.name,value:item.id});
    });
    this.setState({
      collectionBeingEditedModalBulk:display,
      collectionsBulkEditShowSave:false,
      collectionsBulkEditMetricSetOptions:collectionsBulkEditMetricSetOptions,
      collectionsBulkEditRevertOptions:collectionsBulkEditRevertOptions,
      collectionsBulkEditMetricSetValue:collectionsBulkEditMetricSetOptions[0].value,
      collectionsBulkEditRevertValue:collectionsBulkEditRevertOptions[0].value,
    });    
  }
  collectionDetailsModal(cid,index,display){
    //console.log('page: '+this.state.collectionsResourceItemsPage+' x '+resourceListItemCount);
    let resourceIndex = (this.state.collectionsResourceItemsPage * resourceListItemCount) + index;
    console.log('resourceIndex: '+resourceIndex);
    console.log('cid: '+cid+' index: '+index+' display: '+display);
    let collectionBeingEditedCopy = this.state.collectionsResourceItems[resourceIndex];
    collectionBeingEditedCopy.resourceIndex = index;
    this.setState({
      collectionBeingEditedModal:display,
      collectionBeingEdited:collectionBeingEditedCopy,
    });
  }
  metricsChangeCollection(value,collectionObj,key) {
    //console.log('metricsChangeCollection -  key: '+key+' value: '+value);
    //console.log(collectionObj);
    collectionObj[key] = value;
    let collectionsResourceItemsCopy = this.state.collectionsResourceItems;
    //console.log(collectionsResourceItems[collectionObj.resourceIndex]);
    collectionsResourceItemsCopy[collectionObj.resourceIndex] = collectionObj;
    //console.log(collectionsResourceItemsCopy[collectionObj.resourceIndex]);
    this.setState({
      collectionBeingEdited:collectionObj,
      collectionsResourceItems:collectionsResourceItemsCopy,
    },() => {
      //console.log(collectionsResourceItems[collectionObj.resourceIndex]);
      //console.log('do ajax request to update collection');
      const data = {
        action: 'update_collection',
        collection:collectionObj,
        store_url: storeUrl
      }  
      fetch('/ajax.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })
      .then(response => response.json())
      .then((json) =>{
        //console.log(json);
        this.getCollections();
        //productsCollectionsOptions
        this.setState({

        },()=> {
          //this.getCollections();
        });
      });
      
    });
  }


  /* metrics methods */
  duplicateMetrics(metricId){
    console.log('duplicateMetrics: '+metricId);
    console.log(this.state.metrics);
    let duplicateMetrics = {
      id:0,
      name:this.state.metricsBeingEdited.name+' (Duplicate)',
      attributes:this.state.metricsBeingEdited.attributes,
      boost:this.state.metricsBeingEdited.boost,
      is_default:false,
      soldOutValue:this.state.metricsBeingEdited.soldOutValue,
      tieBreakerValue:this.state.metricsBeingEdited.tieBreakerValue,
      products:[],
    }
    let saveBarCopy = this.state.saveBar;
    saveBarCopy.show = true;
    saveBarCopy.context = 'metrics';
    console.log(duplicateMetrics);
    this.setState({
      metricsBeingEdited:duplicateMetrics,
      saveBar:saveBarCopy,
    });
  }
  displayEditMetrics = (display,create=false) => {
    console.log('displayEditMetrics: '+display+' / '+create);
    let metricsCopy = this.state.metrics;
    console.log(this.state.metrics);
    metricsCopy.createMetricsDisplay = display; 
    if(create){
      this.setState({
        metricsBeingEdited:this.state.metricsBeingEditedDefault,
        metrics:metricsCopy
      },() => {
        this.getMetricsPreviewProducts();
      });
    } else {
      this.setState({metrics:metricsCopy}, () => {
        this.getMetricsPreviewProducts();
      });
    }
    //createMetricsDisplay
  }
  getMetrics() {
    //console.log('getMetrics');
    const data = {
      action: 'get_metrics',
      tab:this.state.activeMetricsTab,
      query:this.state.metricsFilterQueryValue,
      sort:this.state.popoverFilters.metrics.value,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log(json);
      let collectionsResourceItemsPages;
      if(json.metrics){
        collectionsResourceItemsPages = Math.ceil((json.metrics.length / resourceListItemCount));
      } else {
        collectionsResourceItemsPages = 0;
      }
      let productMetricsOptions = [];
      let metricsCollectionsId = false;
      for (let i = 0; i < json.metrics.length; i++) {
        if(parseInt(json.metrics[i].collections) > 0){
          productMetricsOptions.push({label:json.metrics[i].name,value:json.metrics[i].id});
          if(metricsCollectionsId === false){
            metricsCollectionsId = json.metrics[i].id;
          }
        }
      }
      //console.log('metrics!');
      //console.log(json.metrics);
      let productMetricsSelected;
      //console.log('productMetricsOptions:');
      //console.log(productMetricsOptions);
      //console.log(productMetricsOptions[0]);
      //console.log(productMetricsOptions[0].value);
      if(productMetricsOptions.length == 0){
        productMetricsSelected = '';
      } else {
        productMetricsSelected = productMetricsOptions[0]['value'];
      }
      this.setState({
        metricsResourceItems:json.metrics,
        metricsResourceItemsCount:json.metrics.length,
        metricsDefaultId:json.default,
        productMetricsOptions:productMetricsOptions,
        //here??
        productsMetricsSelected:productMetricsSelected,
      },()=> {
        this.getPreviewProducts();
        this.getMetricsCollections(metricsCollectionsId);
        if(parseInt(json.metrics[0].collections) > 0){
        }
        
        //console.log('productsMetricsSelected? '+this.state.productsMetricsSelected)
      });
    }).then(()=>{
      //what else?

    });
  }
  sidebarCollectionsChange = (value) => {
    console.log('sidebarCollectionsChange: '+value);
    this.setState({sidebarCollectionsValue:value},() =>{
      console.log('sidebar metricsBeingEdited for ')
      console.log(this.state.metricsBeingEdited.id);
      this.getMetricsSidebarCollections(this.state.metricsBeingEdited.id,value)
    });
  }
  getMetricsSidebarCollections(id,search){
    //console.log('getMetricsSidebarCollections: '+id+' / '+search);
    const data = {
      action: 'get_metrics_sidebar_collections',
      id:id,
      search:search,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log(json);
      this.setState({
        metricsSidebarCollections:json,
      });
    }); 
  }
  editMetricsObject = (isNew,index=false,key,value) => {
    console.log('editMetricsObject ~ isNew: '+isNew+' index: '+index+' key: '+key+' value: '+value);
    let metricsBeingEditedCopy = this.state.metricsBeingEdited;
    console.log(metricsBeingEditedCopy);
    let saveBarCopy = this.state.saveBar;
    saveBarCopy.show = true;
    saveBarCopy.context = 'metrics';
    metricsBeingEditedCopy[key] = value;
    //metricsBeingEditedCopy.is_default = true;

    console.log(metricsBeingEditedCopy);
    this.setState({
      metricsBeingEdited:metricsBeingEditedCopy,
      saveBar:saveBarCopy
    }, () => {
      console.log(this.state.metricsBeingEdited);
      this.getMetricsPreviewProducts();
    });
  }
  addMetricsAttributeRow = () => {
    //console.log('addMetricsAttributeRow');
    //console.log(initAttributeRow);
    //console.log(this.state.metricsBeingEdited.attributes);
    let metricsBeingEditedCopy = this.state.metricsBeingEdited;
    let saveBarCopy = this.state.saveBar;
    saveBarCopy.show = true;
    saveBarCopy.context = 'metrics';
/*
const initAttributeRow = {
  select:{
    options:attributeOptionTypes,
    value:attributeOptionTypes[0].value,
  },
  value:0,
}
*/
  const initOptionTypes = this.getAttributeOptionTypes(-1);
  console.log('initOptionTypes');
  console.log(initOptionTypes);
  let initAttributeRowFuck = {
    select:{
      options:initOptionTypes[0],
      value:initOptionTypes[0].value
    },
    value:0
  }

    metricsBeingEditedCopy.attributes.push(initAttributeRowFuck);
    //console.log(metricsBeingEditedCopy.attributes);
    this.setState({metricsBeingEdited:metricsBeingEditedCopy, saveBar:saveBarCopy},() =>{
      this.getMetricsPreviewProducts();
    });
  }
  removeMetricAttribute = (i) => {
    //console.log('removeMetricAttribute: '+i);
    let metricsBeingEditedCopy = this.state.metricsBeingEdited;
    let saveBarCopy = this.state.saveBar;
    saveBarCopy.show = true;
    saveBarCopy.context = 'metrics';
    //console.log(metricsBeingEditedCopy.attributes);
    metricsBeingEditedCopy.attributes.splice(i,1);
    //console.log(metricsBeingEditedCopy.attributes);
    this.setState({metricsBeingEdited:metricsBeingEditedCopy, saveBar:saveBarCopy},() => {
      this.getMetricsPreviewProducts();
    });
  }
  editMetricsAttributes = (index,key,value) => {
    console.log('editMetricsAttributes: '+index+' key: '+key+' value: '+value);
    let metricsBeingEditedCopy = this.state.metricsBeingEdited;
    let saveBarCopy = this.state.saveBar;
    saveBarCopy.show = true;
    saveBarCopy.context = 'metrics';
    //console.log(metricsBeingEditedCopy);
    if(key == 'select') {
      metricsBeingEditedCopy.attributes[index] = {
        select:{
          options:this.state.metricsBeingEdited.attributes[index].select.options,
          value:value
        },
        value:this.state.metricsBeingEdited.attributes[index].value
      }
    }
    if(key == 'value') {
      metricsBeingEditedCopy.attributes[index] = {
        select:{
          options:this.state.metricsBeingEdited.attributes[index].select.options,
          value:this.state.metricsBeingEdited.attributes[index].select.value
        },
        value:value
      }
    }
    //console.log(metricsBeingEditedCopy);
    this.setState({metricsBeingEdited: metricsBeingEditedCopy, saveBar:saveBarCopy},() => {
      this.getMetricsPreviewProducts();
    });
  }
  getMetricsCollections(id){
    //console.log('getMetricsCollections: '+id);
    const data = {
      action: 'get_metrics_collections',
      id:id,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log('json:');
      //console.log(json);
      //console.log(json[0]);
      this.setState({
        productsCollectionsOptions:json,
        productsCollectionsSelected:json[0]['value'] || '',
        //metricsResourceItems:json.metrics,
        //collectionsResourceItemsPages:collectionsResourceItemsPages
      },() => {
        this.getMetricsCollectionProducts();
      });
    }).then(()=>{
      //what else?
      
    }); 
  }
  getMetricsProductsPreview(metricsId,metricsBeingEditedObj=false) {
    //old, not using
    console.log('getMetricsProductsPreview');
  }
  doSaveMetrics(){
    console.log('doSaveMetrics');
    console.log(this.state.metricsBeingEdited);
    const data = {
      action: 'save_metrics',
      metrics:this.state.metricsBeingEdited,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log(json);
      let metricsBeingEditedCopy = this.state.metricsBeingEdited;
      let saveBarCopy = this.state.saveBar;
      metricsBeingEditedCopy.products = json.products;
      metricsBeingEditedCopy.id = json.id;
      saveBarCopy.show = false;
      saveBarCopy.context = '';

      this.setState({
        metricsBeingEdited:metricsBeingEditedCopy,
        saveBar:saveBarCopy,
      });
    }).then(()=>{
      this.getMetrics();
      this.getCollections();
      this.updateOnboardingModal();
      //what else?
      //console.log(this.state.metricsBeingEdited);
    }); 
  }
  editMetrics(id,index){
    //console.log('editMetrics');
    //console.log(this.state.metricsResourceItems[index]);
    let metricsCopy =  this.state.metrics;
    metricsCopy.createMetricsDisplay = true;
    for (const property in this.state.metricsResourceItems[index]) {
      metricsRevert[property] = this.state.metricsResourceItems[index][property];
    }
    metricsRevertIndex = index;

    this.setState({
      metrics:metricsCopy,
      metricsBeingEdited:this.state.metricsResourceItems[index]
    },() => {
      this.getMetricsSidebarCollections(id,'');
      this.getMetricsPreviewProducts();
    });
  }
  viewProductScores(metricId){
    //console.log('viewProductScores: '+metricId);
    //change tag
    this.handleNavTabChange(2);
    //change dropdown
    this.setState({productsMetricsSelected:metricId},() => {
      this.getMetricsCollections(metricId);
    });
  }
  getMetricsPreviewProducts(){
    //console.log('getMetricsPreviewProducts');
    //  metricsPreviewProducts
    const data = {
      action: 'get_metrics_preview_products',
      metrics:this.state.metricsBeingEdited,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log(json);
      this.setState({
        metricsPreviewProducts:json,
        //collectionsResourceItemsPages:collectionsResourceItemsPages
      });
    }); 
  }

  /* products methods */
  getPreviewProducts() {
    //only run once both are set
    if(
      this.state.collectionsResourceItems.length == 0
      ||
      this.state.metricsResourceItems.length == 0
    ) {
      //console.log('getPreviewProducts state not set');
      return;      
    }
    //console.log('getPreviewProducts state set');
    //console.log('getPreviewProducts mid: '+this.state.collectionsResourceItems[0].id+' cid: '+this.state.metricsResourceItems[0].id);
    const data = {
      action: 'get_preview_products',
      collection:this.state.collectionsResourceItems[0].id,
      metrics:this.state.metricsResourceItems[0].id,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log(json);
      this.setState({
        //metricsResourceItems:json.metrics,
        //collectionsResourceItemsPages:collectionsResourceItemsPages
      });
    });    
  }
  getProducts(){
    console.log('getProducts: ');
    const data = {
      action: 'get_products',
      //collection:this.state.collectionsResourceItems[0].id,
      //metrics:this.state.metricsResourceItems[0].id,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log(json);
      this.setState({
        //productsMetricsId:json.product_metrics_id,
        //collectionsResourceItemsPages:collectionsResourceItemsPages
      });
    }); 
  }
  loadMoreProducts = () => {
    const showProductIndex = this.state.showProductIndex + 1;
    console.log('loadMoreProducts: '+showProductIndex);
    this.setState({showProductIndex:showProductIndex});
  }
  productsMetricsChanged = (value) => {
    console.log('productsMetricsChanged: '+value);
    this.setState({
      productsMetricsSelected:value,
      showProductIndex:0,
    },() => {
      this.getMetricsCollections(value);
    });
    //let productsMetricsSelectedCopy  = this.state.productsMetricsSelected;
  }
  changeProductsCollectionsChanged = (value) => {
    console.log('changeProductsCollectionsChanged: '+value);
    this.setState({
      productsCollectionsSelected:value,
      showProductIndex:0,
    },() => {
      this.getMetricsCollectionProducts();
    });    
  }
  getMetricsCollectionProducts(){
    //console.log('getMetricsCollectionProducts: '+this.state.productsCollectionsSelected);
    //get collections producst here
    const data = {
      action: 'get_metrics_collection_products',
      collection:this.state.productsCollectionsSelected,
      metrics:this.state.productsMetricsSelected,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      console.log(json);
      this.setState({
        products:json.products,
        metricsCollectionProductsAttributes:json.attributes,
        metricsCollectionProductsBoost:json.boost,
        //collectionsResourceItemsPages:collectionsResourceItemsPages
      });
    }); 
  }

  /* settings methods */
  changeSettingsSelect = (value,key) => {
    console.log('changeSettingsValues v: '+value+' k: '+key);
    let settingsCopy = this.state.settings;
    settingsCopy[key].value = value;
    this.setState({
      settings: settingsCopy,
      showProcessingSave:true
    });
  }
  saveProcessingSettings() {
    console.log('saveProcessingSettings');
    this.setState({
      processingSaveLoading:true,
    },() => {
      const data = {
        action: 'save_processing_settings',
        settings:this.state.settings,
        store_url: storeUrl
      }  
      fetch('/ajax.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })
      .then(response => response.json())
      .then((json) =>{
        console.log(json);
        this.setState({
          showProcessingSave:false,
          processingSaveLoading:false,
        });
      }); 
    });
    
  }
  discardProcessingSettings() {
    console.log('discardProcessingSettings');
    ///console.log(this.state.settings);
    console.log('settingsRevert 2');
    console.log(settingsRevert);
    this.setState({
      processingSaveLoading:true,
    },() => {
      let settingsCopy = this.state.settings;
      for (const property in settingsCopy) {
        if(settingsRevert.hasOwnProperty(property)){
          settingsCopy[property].value = settingsRevert[property];
        }
      }
      console.log('settingsRevert 2');
      console.log(settingsCopy);
      this.setState({
        showProcessingSave:false,
        processingSaveLoading:false,
      });
    });    
  }
  saveNotificationsSettings() {
    console.log('saveNotificationsSettings');
    this.setState({
      notificationsSaveLoading:true,
    },() => {
      const data = {
        action: 'save_notification_settings',
        settings:this.state.settings,
        store_url: storeUrl
      }  
      fetch('/ajax.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })
      .then(response => response.json())
      .then((json) =>{
        console.log(json);
        this.setState({
          showNotificationsSave:false,
          notificationsSaveLoading:false,
        });
      }); 
    });
  }
  discardNotificationsSettings() {
    console.log('discardNotificationsSettings');
    ///console.log(this.state.settings);
    console.log('settingsRevert 2');
    console.log(settingsRevert);
    this.setState({
      notificationsSaveLoading:true,
    },() => {
      let settingsCopy = this.state.settings;
      for (const property in settingsCopy) {
        if(settingsRevert.hasOwnProperty(property)){
          settingsCopy[property].value = settingsRevert[property];
        }
      }
      console.log('settingsRevert 2');
      console.log(settingsCopy);
      this.setState({
        showNotificationsSave:false,
        notificationsSaveLoading:false,
      });
    });    
  }
  changeSettingsCheckbox = (key,value) => {
    console.log('changeSettingsCheckbox '+key+' : '+value);
    let settingsCopy = this.state.settings;
    settingsCopy[key].value = value;
    this.setState({
      settings: settingsCopy,
      showNotificationsSave:true
    });
  }
  changeSettingsAdditionalEmails = (value) => {
    console.log('changeSettingsTextInput '+value);
    let settingsCopy = this.state.settings;
    let errorsCopy = this.state.errors;
    let additionalEmailsError = false;
    settingsCopy['additional_emails'].value = value;
    let emailAddresses = value.split(',');
    for (let i = 0; i < emailAddresses.length; i++) {
      //test each for valid email
      emailAddresses[i] = emailAddresses[i].trim();
      console.log("'"+emailAddresses[i]+"'");
      if(
        emailAddresses[i].match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)
        ||
        emailAddresses[i].length == 0
      ){
        //additionalEmailsError = false;
      } else {
        additionalEmailsError = 'Please enter valid email addresses separated by commas';
      }
    }    
    console.log('error? '+additionalEmailsError);
    errorsCopy.additional_emails = additionalEmailsError;
    this.setState({
      settings: settingsCopy,
      showNotificationsSave:true,
      errors:errorsCopy,
    },() => {
      //this.validateAdditionalEmails();
    });
  }
  //validateAdditionalEmails() {
  //  console.log('validate');
  //}
  /* attribute methods */
  getAttributeOptionTypes =  (index) => {
    let attributeOptionTypesFuck = [
      {label:'Quantity',value:'quantity'},
      {label:'Full Size Run', value: 'full-size-run'},
      {label:'Age Of Newest Variant',value:'age-of-newest-variant'},
      {label:'Sales (Last 30 Days)',value:'sales-last-30-days'},
      {label:'Sales (Last 7 Days)',value:'sales-last-7-days'},
      {label:'Margin',value:'margin'},
      {label:'Sold Out',value:'sold-out'},
      //{label:'On Sale',value:'on-sale'},
      //{label: 'Coming Soon', value: 'coming-soon'},
      //{label: 'Brand Boost', value: 'brand-boost'},
      //{label: 'Yotpo Reviews', value: 'yotpo'}, //hidden for dev/review
    ];
    //add custom attrs to list
    //console.log('getAttributeOptionTypes productAttributes');
    //console.log(this.state.productAttributes);
    if(this.state.productAttributes !== null && this.state.productAttributes.custom && this.state.productAttributes.custom.length > 0){
      for (let i = 0; i < this.state.productAttributes.custom.length; i++) {
        attributeOptionTypesFuck.push({label:this.state.productAttributes.custom[i].name,value:this.state.productAttributes.custom[i].attribute_key})
      }
    }


    let fuckingAlreadyUsed = [];
    for (let i = 0; i < this.state.metricsBeingEdited.attributes.length; i++) {
      fuckingAlreadyUsed.push(this.state.metricsBeingEdited.attributes[i].select.value);
    }

    let fuck = [];
    let empty = true;
    for (let i = 0; i < this.state.metricsBeingEdited.attributes.length; i++) {
      //console.log('val: '+this.state.metricsBeingEdited.attributes[i].select.value);
      empty = false;
      for (let i2 = 0; i2 < attributeOptionTypesFuck.length; i2++) {
        //console.log('val: '+this.state.metricsBeingEdited.attributes[i].select.value+' fuck? '+attributeOptionTypesFuck[i2].value);
        if(
          (
            this.state.metricsBeingEdited.attributes[i].select.value == attributeOptionTypesFuck[i2].value
            &&
            i == index
          )
          ||
          (
            !fuckingAlreadyUsed.includes(attributeOptionTypesFuck[i2].value)
            &&
            !fuck.includes(attributeOptionTypesFuck[i2])
          )
        ){
          //console.log('fuck! '+attributeOptionTypesFuck[i2].value);
          fuck.push(attributeOptionTypesFuck[i2]);
        }
      }
    }
    //console.log('fuck index: '+index);
    if(
      index < 0
      &&
      empty
    ){ //none set yet
      //console.log('this should unfuck the index');
      fuck = attributeOptionTypesFuck;
    }
    
    fuck.sort((a,b) => (a.label > b.label) ? 1 : ((b.label > a.label) ? -1 : 0))
    return fuck;
  }
  getAttributes() {
    //console.log('getAttributes');
    const data = {
      action: 'get_attribute_settings',
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      //console.log('getAttributes');
      //console.log(json);
      this.setState({
        productAttributes:json,
      });
    }); 
  }
  addAttribute() {
    console.log('addAttribute');
    const data = {
      action: 'add_attribute',
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      console.log(json);
      this.getAttributes();
    });
  }
  deleteAttribute(attribute_key){
    console.log('deleteAttribute: '+attribute_key);
    const data = {
      action: 'delete_attribute',
      attribute_key:attribute_key,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      console.log(json);
      this.getAttributes();
      this.getMetrics();
      this.getProducts();
    });    
  }
  changeConfigurables = (value,attributeKey,fieldKey) => {
    //console.log('changeConfigurables v:'+value+' g: '+group+' ak: '+attributeKey+' fk: '+fieldKey);
    //console.log('changeConfigurables v:'+value+' ak: '+attributeKey+' fk:'+fieldKey);
    //console.log(fieldKey);
    let productAttributesCopy = this.state.productAttributes;
    for (var group in productAttributesCopy){
      console.log('group: '+group);
      for (let i = 0; i < productAttributesCopy[group].length; i++) {
        if(attributeKey == productAttributesCopy[group][i].attribute_key) {
          //console.log('i: '+i+' = '+productAttributesCopy[group][i].attribute_key);
          //console.log('old: '+productAttributesCopy[group][i].fields[fieldKey].value);
          productAttributesCopy[group][i].fields[fieldKey].value = value;
          productAttributesCopy[group][i].saveable = "1";
          //console.log('new: '+productAttributesCopy[group][i].fields[fieldKey].value);
          this.setState({productAttributes:productAttributesCopy});
        }
      }
    
      //if (target.hasOwnProperty(k)) {
      //     alert("Key is " + k + ", value is " + target[k]);
      //}
    }
    //console.log(productAttributesCopy);
  }
  changeConfigurableTitle = (value,attributeKey) => {
    console.log('changeConfigurableTitle v:'+value+' ak: '+attributeKey);
    //console.log('changeConfigurables v:'+value+' ak: '+attributeKey+' fk:'+fieldKey);
    //console.log(fieldKey);

    let productAttributesCopy = this.state.productAttributes;
    for (var group in productAttributesCopy){
      console.log('group: '+group);
      for (let i = 0; i < productAttributesCopy[group].length; i++) {
        if(attributeKey == productAttributesCopy[group][i].attribute_key) {
          //console.log('i: '+i+' = '+productAttributesCopy[group][i].attribute_key);
          //console.log('old: '+productAttributesCopy[group][i].fields[fieldKey].value);
          productAttributesCopy[group][i].name = value;
          productAttributesCopy[group][i].saveable = "1";
          //console.log('new: '+productAttributesCopy[group][i].fields[fieldKey].value);
          this.setState({productAttributes:productAttributesCopy});
        }
      }
    
      //if (target.hasOwnProperty(k)) {
      //     alert("Key is " + k + ", value is " + target[k]);
      //}
    }
    //console.log(productAttributesCopy);
  }
  saveConfigurables = (attributeKey) => {
    console.log('saveConfigurables: '+attributeKey);
    let productAttributesCopy = this.state.productAttributes;
    for (var group in productAttributesCopy){
      //console.log('group: '+group);
      for (let i = 0; i < productAttributesCopy[group].length; i++) {
        if(attributeKey == productAttributesCopy[group][i].attribute_key) {
          //console.log('i: '+i+' = '+productAttributesCopy[group][i].attribute_key);
          //console.log('old: '+productAttributesCopy[group][i].fields[fieldKey].value);
          const fieldsToSend = productAttributesCopy[group][i].fields;
          const name = productAttributesCopy[group][i].name;
          console.log(fieldsToSend);
          console.log(name);
          productAttributesCopy[group][i].saveable = "0";
          //console.log('new: '+productAttributesCopy[group][i].fields[fieldKey].value);
          const data = {
            action: 'update_attribute_settings',
            attribute_key:attributeKey,
            fields:fieldsToSend,
            name:name,
            store_url: storeUrl
          }  
          fetch('/ajax.php', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
          })
          .then(response => response.json())
          .then((json) =>{
            console.log(json);
            this.setState({productAttributes:productAttributesCopy});
          });           
        }
      }  
    }  
  }
  attributeStatus = (status,attributeKey) => {
    console.log('attributeStatus s: '+status+' ak: '+attributeKey);
    let productAttributesCopy = this.state.productAttributes;
    for (var group in productAttributesCopy){
      //console.log('group: '+group);
      for (let i = 0; i < productAttributesCopy[group].length; i++) {
        if(attributeKey == productAttributesCopy[group][i].attribute_key) {
          productAttributesCopy[group][i].status = status;
          const data = {
            action: 'update_attribute_status',
            attribute_key:attributeKey,
            status:status,
            store_url: storeUrl
          }  
          fetch('/ajax.php', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
          })
          .then(response => response.json())
          .then((json) =>{
            console.log(json);
            this.setState({productAttributes:productAttributesCopy});
          });
        }
      }
    }    
  }
  editBoost = (value,productId,index) => {
    console.log('editBoost pid: '+productId+' i: '+index+' v: '+value);
    let productsCopy = this.state.products;
    productsCopy[index].saveable = true;
    productsCopy[index].boost = value;
    this.setState({
      products:productsCopy
    });
  }
  saveBoost = (productId,index) => {
    console.log('saveBoost pid: '+productId+' i: '+index);
    const data = {
      action: 'save_boost',
      product:productId,
      value:this.state.products[index].boost,
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      console.log(json);
      let productsCopy = this.state.products;
      productsCopy[index].saveable = false;
      this.setState({
        products:productsCopy
      });
      this.setState({products:productsCopy}, () => {
        console.log('reload with new boost');
        this.getMetricsCollectionProducts();
      });
    });
  }
  showOnboardingModal(display) {
    console.log('showOnboardingModal: '+parseInt(display));
    if(display){
      this.setState({showOnboardingModal:true});
    } else {
      this.setState({showOnboardingModal:false});
    }
  }
  doOnboardingModalClick(section){
    console.log('doOnboardingModalClick: '+section);
    this.showOnboardingModal(false);
    if(section == 'metrics'){
      this.setState({activeTab:1});
    }
    if(section == 'collections'){
      this.setState({activeTab:0});
    }
    if(section == 'status'){
      //this.setState({activeTab:1});
      this.statusShowModal(true);
    }
  }
  updateOnboardingModal(){
    console.log('updateOnboardingModal');
    const data = {
      action: 'update_onboarding_modal',
      store_url: storeUrl
    }  
    fetch('/ajax.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then((json) =>{
      console.log(json);
      this.setState({
        onboarding_flow:json
      });
    });    
  }



  render() {

    const activatorViewOptions = (
      <Button onClick={() => this.toggleViewOptions()} disclosure>
        View Options
      </Button>
    );
    return (
      <AppProvider i18n={enTranslations}>
        <Frame>
          <Modal
              //activator={activator}
              open={((this.state.showOnboardingModal && this.state.init.show_plans == false)? true:false)}
              onClose={()=>{this.showOnboardingModal(false)}}
              //title={"Confirm Status Change"}
              //large
          > 
            <div className='onboarding-modal-content'>
              <div className='onboarding-modal-half content'>
                <div className='onboarding-welcome'>
                  <h4>Welcome to Dynasort!</h4>
                  <p>Let us help you get started</p>
                </div>
                <div className={'onboarding-modal-item'}>
                  <span className={this.state.onboarding_flow.onboarding_steps.metrics == 1 ? 'completed':''}></span>
                  <h5>Setup a metric set</h5>
                  {(this.state.onboarding_flow.onboarding_steps.metrics == 1 ? <strong>Completed</strong>:<Button plain monochrome onClick={() => {this.doOnboardingModalClick('metrics')}}>View metric Sets</Button>)}
                </div>
                <div className={'onboarding-modal-item'}>
                <span className={this.state.onboarding_flow.onboarding_steps.collections == 1 ? 'completed':''}></span>
                  <h5>Activate a collection</h5>
                  {(this.state.onboarding_flow.onboarding_steps.collections == 1 ? <strong>Completed</strong>:<Button plain monochrome onClick={() => {this.doOnboardingModalClick('collections')}}>View Collections</Button>)}
                </div>
                <div className={'onboarding-modal-item'}>
                <span className={this.state.onboarding_flow.onboarding_steps.status == 1 ? 'completed':''}></span>
                  <h5>Activate Dynasort</h5>
                  {(this.state.onboarding_flow.onboarding_steps.status == 1 ? <strong>Completed</strong>:<Button plain monochrome onClick={() => {this.doOnboardingModalClick('status')}}>Enable Dynasort</Button>)}
                </div>
              </div>  
              <div className='onboarding-modal-half image'>
              </div>
            </div>             
          </Modal>
          <div className={"save-bar "+((this.state.saveBar.show)? 'show':'hide')}>
          </div>
          {
            ((this.state.saveBar.show)? 
              <ContextualSaveBar
                message="Unsaved changes"
                saveAction={{
                  onAction: () => {this.doSaveAction()},
                  loading: false,
                  disabled: false,
                }}
                discardAction={{
                  onAction: () => (this.doDiscardAction()),
                }}
                alignContentFlush
                fullWidth
              />
            :'')
          }
            
          <div className={"interface "+(!hasRunInit? 'loading':'not-loading')}>
            <div className={"tabbed-navigation "+((this.state.init.show_tabs && this.state.init.show_plans == false)? 'show':'hide')}>
              <Tabs 
                tabs={this.state.tabs}
                selected={this.state.activeTab}
                onSelect={this.handleNavTabChange}
              ></Tabs>
              <div class={'getting-started '+(this.state.onboarding_flow.onboarding_steps.complete ? 'hide':'show')} onClick={() => this.showOnboardingModal(true)}>Getting Started</div>
              <div class="nav-status" onClick={() => this.statusShowModal(true)}>
                <span className='status-text'>Status:</span>
                <Badge
                  status={(this.state.status == "On"? "success":"")}
                >{this.state.status}</Badge>
              </div>
              <Modal
                  //activator={activator}
                  open={(this.state.statusModalOpen? true:false)}
                  onClose={()=>{this.statusShowModal(false)}}
                  title={"Confirm Status Change"}
                  small
                > 
                <div className='modal-content'>
                  <p>Turning Dynasort status {(this.state.status == "On"? "off":"on")} will {(this.state.status == "On"? "disable":"enable")} all collections sorting.</p>
                  <div className={"settings-save-container"}>
                    <Button primary onClick={() => { this.toggleStatus()}}>Turn {(this.state.status == "On"? "Off":"On")}</Button>
                    <Button onClick={() => { this.statusShowModal(false)}}>Cancel</Button>
                  </div>   
                </div>             
              </Modal>
            </div>
            <Layout>
              <div className={"iec-tabbed-content-container collection-content-container"+(!hasRunInit? ' loading ':' not-loading')}>
                <div className={"onboarding-status "+((this.state.showOnboarding) ? 'show':'hide')}>
                  <div className={"cache-status "+((this.state.showCacheStatus && this.state.init.show_plans == false) ? 'show':'hide')}>
                    <Layout.Section>
                      <Page>
                        <Banner
                          title="Caching Store Data"
                          status="info"
                        >
                          <p>Dynasort is busy caching your shop's data, this will only take a few moments.</p>
                          <ul>
                            <li><span class="cache-label">Products Cached</span><span class="cache-status">{this.state.cacheStatus.products_cached}<span>/</span>{this.state.cacheStatus.products_total}</span></li>
                            <li><span class="cache-label">Orders Cached</span><span class="cache-status">{this.state.cacheStatus.orders_cached}<span>/</span>{this.state.cacheStatus.orders_total}</span></li>
                            <li><span class="cache-label">Collections Cached</span><span class="cache-status">{this.state.cacheStatus.collections_cached}<span>/</span>{this.state.cacheStatus.collections_total}</span></li>
                          </ul>
                        </Banner>
                      </Page>
                    </Layout.Section>
                  </div>
                </div>
                <div className={"iec-tabbed-content "+((this.state.activeTab == 0) ? ' show ':' hide ')}>
                  <Layout.Section>
                    <Page
                      title={'Collections'}
                    >
                      <div className="top-card-padding">
                        <Card>
                          <Card.Section>
                            <Tabs 
                              tabs={this.state.collectionsTabs} 
                              selected={this.state.activeCollectionsTab} 
                              onSelect={this.handleCollectionsNavChange}>
                            </Tabs> 
                            <div className='collection-count-status'>
                              {this.state.collectionsResourceItemEnabled }/{this.state.init.permissions.collections} Enabled
                              <div className="inline-tooltip-container">
                                  <Tooltip content={this.state.init.current_plan + " Plan allows for "+this.state.init.permissions.collections+" enabled collections"}>
                                    <Icon source={QuestionMarkMajor} color="base" />
                                  </Tooltip>
                                </div>
                            </div>
                          </Card.Section>   
                          {/*     
                          <Card.Section>
                            <Autocomplete
                                textField={(<Autocomplete.TextField
                                  onChange={this.changeCollectionsFilterValue}
                                  //label="Filter collections"
                                  value={this.state.collectionsFilterValue}
                                  prefix={<Icon source={SearchMinor} color="base" />}
                                  placeholder="Filter collections"
                                />)}
                                //selected={this.state.addUrlOptions[0]}
                                selected={''}
                                options={this.state.collectionsOptions}
                                onSelect={(value,label,pageType) => {
                                  console.log('onSelect');
                                  console.log('add obj: '+value);
                                  //console.log(label);
                                  //console.log(pageType);
                                  //this.addUrl(value);
                                }
                              }
                            />
                          </Card.Section> 
                          */}
                          <Card.Section>
                            <ResourceList
                              resourceName={{singular: 'collection', plural: 'collections'}}
                              items={this.getCollectionResourceItems(this.state.collectionsResourceItemsPage || []) || []}
                              totalItemsCount={this.state.collectionsResourceItems.length}
                              filterControl={(
                                <div className="collections-header-container">
                                  <Filters
                                    queryValue={this.state.collectionFilterQueryValue}
                                    filters={this.state.collectionsFilters}
                                    //appliedFilters={appliedFilters}
                                    onQueryChange={(value) => {this.collectionFilterChangeQueryValue(value)}}
                                    onQueryClear={() => {this.collectionFilterChangeQueryValue('')}}
                                    //onClearAll={() => console.log('Todo: implement onClearAll')}
                                  >
                                    <div className="sort-popover-container" style={{paddingLeft: '8px'}}>
                                      
                                      <Button onClick={() => {this.togglePopover('collections')}}><Icon source={SortMinor} color="base" />Sort</Button>
                                      <div className={"sort-popover "+(this.state.popoverFilters.collections.show? 'show':'hide')}>
                                        <ChoiceList
                                          //title="Company name"
                                          choices={[
                                            {label: 'Title A-Z', value: 'name-asc'},
                                            {label: 'Title Z-A', value: 'name-desc'},
                                            {label: 'Date (Newest first)', value: 'date-asc'},
                                            {label: 'Date (Oldest first)', value: 'date-desc'},
                                            {label: 'Products (Most first)', value: 'count-asc'},
                                            {label: 'Products (Least first)', value: 'count-desc'},
                                          ]}
                                          selected={this.state.popoverFilters.collections.value}
                                          onChange={(value) => {this.changePopover(value,'collections')}}
                                        />
                                        <div className='hr' />
                                        <ChoiceList
                                          //title="Company name"
                                          choices={[
                                            {label: 'All', value: 'all'},
                                            {label: 'Active', value: 'active'},
                                            {label: 'Inactive', value: 'inactive'},
                                          ]}
                                          selected={this.state.popoverFilters.collectionsActive.value}
                                          onChange={(value) => {this.changePopover(value,'collectionsActive')}}
                                        />
                                      </div>
                                    </div>
                                  </Filters>
                                  <div className="resource-list-headings">
                                    <div className="resource-list-heading-item rlhi-0">
                                      <Checkbox 
                                        checked={this.state.collectionsAllCheckboxSelected}
                                        //checked={() => {this.isCollectionsAllChecked()}}
                                        onChange={() => {this.collectionsAllCheckboxToggle(!this.state.collectionsAllCheckboxSelected)}}
                                      />
                                    </div>
                                    <div className="resource-list-heading-item rlhi-1">
                                      <h3>Title</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-2">
                                      <h3>Products</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-3">
                                      <h3>Metrics</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-4">
                                      <h3>Status</h3>
                                    </div>
                                    <div class={"resource-list-button-group "+(this.state.collectionsSelectedItems.length > 0 ? '':' hide ')+(this.state.collectionsResourceItems.length == this.state.collectionsSelectedItems.length ? ' all-selected ':' not-all-selected ' )}>
                                      <ButtonGroup segmented>                            
                                        <Button onClick={() => {this.uncheckAllCollectionsResourceItems()}}>{this.state.collectionsSelectedItems.length} Selected</Button>
                                        <Button 
                                          onClick={() => {this.collectionsBulkToggle(true)}}
                                          disabled={((this.state.collectionsResourceItemEnabled + this.state.collectionsSelectedItems.length) > this.state.init.permissions.collections ? true:false)}
                                          //disabled={true}
                                        >Enable Collections</Button>
                                        <Button onClick={() => {this.collectionsBulkToggle(false)}}>Disable Collections</Button>
                                        <Button onClick={() => {this.collectionsBulkEdit(true)}}>Edit Details</Button>
                                      </ButtonGroup>
                                      <Button plain onClick={() => this.collectionsToggleCheckAll(true)}>Select All {this.state.collectionsResourceItems.length} Collections</Button>
                                      <span>All {this.state.collectionsResourceItems.length} Collections Selected</span>
                                      <Button plain onClick={() => this.collectionsToggleCheckAll(false)}>Undo</Button>
                                      {/*
                                      <span className='resource-list-num-selected'>
                                      {this.state.collectionsSelectedItems.length} Selected
                                      </span>
                                      */}
                                    </div>
                                  </div>
                                </div>

                              )}
                              /*
                              promotedBulkActions={[
                                {
                                  content: 'Enable collections',
                                  onAction: () => console.log('Todo: implement bulk collection enable'),
                                },
                                {
                                  content: 'Disable collections',
                                  onAction: () => console.log('Todo: implement bulk collection disable'),
                                },
                              ]}
                              */
                              //selectedItems={selectedItems}
                              //onSelectionChange={this.setCollectionsSelectedItems}
                              //selectedItems={this.state.collectionsSelectedItems}
                              renderItem={(item,id,index) => {
                                const {
                                  name, 
                                  handle,
                                  url,
                                  productCount,
                                  metricName,
                                  lastSorted,
                                  enabled,
                                  checked,
                                  //shortcutActions,
                                } = item;
                                let collectionShortcutActions = [];
                                if(enabled == "0"){
                                  if(this.state.collectionsResourceItemEnabled >= this.state.init.permissions.collections){
                                    //nothing, maxed out
                                  } else {
                                    collectionShortcutActions.push({content:'Enable',onAction:(e)=>{this.setCollectionStatus(id,index,"1")}})
                                  }
                                } else {
                                  collectionShortcutActions.push({content:'Disable',onAction:(e)=>{this.setCollectionStatus(id,index,"0")}})
                                }
                                collectionShortcutActions.push({content:'Edit details',onAction:(e) => this.collectionDetailsModal(id,index,true)})
                                return (
                                  <ResourceItem
                                    id={id}
                                    //url={url}
                                    //media={media}
                                    accessibilityLabel={`View details for ${name}`}
                                    shortcutActions={collectionShortcutActions}
                                    persistActions
                                    //className={"url-resource-item "+((enable) ? 'url-resource-item-disabled':'')}
                                  >
                                    <div className="resource-item-col collection-resource-item-col collection-resource-item-col-0">
                                      <Checkbox 
                                        checked={checked}
                                        onChange={() => {console.log(item);console.log(index);this.selectCollectionItem(item,index,checked)}}
                                      />
                                    </div>
                                    <div className="resource-item-col collection-resource-item-col collection-resource-item-col-1">
                                      <h3>
                                        <TextStyle variation="strong">{name}</TextStyle>
                                      </h3>
                                      <div class="resource-item-col-bottom">
                                        <Link monochrome url={storeUrl+'/admin/collections/'+id}>{handle}</Link>
                                      </div>
                                    </div>
                                    <div className="resource-item-col collection-resource-item-col collection-resource-item-col-2">
                                      <h3>
                                        <TextStyle variation="strong">{productCount} Products</TextStyle>
                                      </h3>
                                      <div class="resource-item-col-bottom">
                                        <Link monochrome url={'#'}>View sorting</Link>
                                      </div>
                                    </div>
                                    <div className="resource-item-col collection-resource-item-col collection-resource-item-col-3">
                                      <h3>
                                        <TextStyle variation="strong">{metricName}</TextStyle>
                                      </h3>
                                      <div class="resource-item-col-bottom">
                                        <span>{lastSorted}</span>
                                      </div>
                                    </div>
                                    <div className="resource-item-col collection-resource-item-col collection-resource-item-col-4">
                                      {enabled == "1"? <Badge status="success">On</Badge>:<Badge>Off</Badge>}
                                    </div>
                                  </ResourceItem>
                                );
                              }}
                            />
                            <div className='pagination-container'>
                              <Pagination
                                hasNext={
                                  (
                                    (this.state.collectionsResourceItemsPage < (this.state.collectionsResourceItemsPages - 1))
                                    &&
                                    (this.state.collectionsResourceItemsPages > 1)
                                  )
                                  ? true:false}
                                hasPrevious={
                                  (
                                    (this.state.collectionsResourceItemsPage > 0)
                                    &&
                                    (this.state.collectionsResourceItemsPages > 1)
                                  )
                                  ? true:false}
                                onNext={() => {
                                  console.log('page: '+this.state.collectionsResourceItemsPage + ' Pages: '+this.state.collectionsResourceItemsPages );
                                  this.collectionResourcePage(1);
                                }}
                                onPrevious={() => {
                                  console.log('page: '+this.state.collectionsResourceItemsPage + ' Pages: '+this.state.collectionsResourceItemsPages );
                                  this.collectionResourcePage(-1);
                                }}
                              />
                            </div>
                          </Card.Section>                
                        </Card>
                      </div>
                    </Page>
                  </Layout.Section>
                  <Modal
                    //activator={activator}
                    open={this.state.collectionBeingEditedModal}
                    onClose={()=>{this.collectionDetailsModal(0,0,false)}}
                    title={"Change metrics for \""+this.state.collectionBeingEdited.name+"\""}
                  >
                    <div className='modal-content'>
                      <p>
                        Select which metric set you'd like to apply to this collection.
                      </p>
                      <FormLayout>
                        <Select 
                          label="Metrics Selected"
                          options={this.state.metricsResourceItems.map(function(item, i){
                            return {label:item.name,value:item.id}
                          })}
                          value={this.state.collectionBeingEdited.metricId}
                          onChange={(value)=>{this.metricsChangeCollection(value,this.state.collectionBeingEdited,'metricId')}}
                        />
                        <Select 
                          label="Revert To (When Off)"
                          options={revertToSelectOptions}
                          value={this.state.collectionBeingEdited.revertSorting}
                          onChange={(value,item,i)=>{this.metricsChangeCollection(value,this.state.collectionBeingEdited,'revertSorting')}}
                        />
                      </FormLayout>
                    </div>
                  </Modal>
                  <Modal
                    //activator={activator}
                    open={this.state.collectionBeingEditedModalBulk}
                    onClose={()=>{this.collectionsBulkEdit(false)}}
                    title={"Change metrics for "+this.state.collectionsSelectedItems.length+" Collections"}
                  >
                    <div className='modal-content'>
                      <p>
                        Select which metric set you'd like to apply to these collections.
                      </p>
                      <FormLayout>
                        <Select 
                          label="Metrics Selected"
                          options={this.state.collectionsBulkEditMetricSetOptions}
                          value={this.state.collectionsBulkEditMetricSetValue}
                          //onChange={(value)=>{this.metricsChangeCollection(value,this.state.collectionBeingEdited,'metricId')}}
                          onChange={(value)=>{this.changeCollectionsEditBulkMetrics(value)}}
                        />
                        <Select 
                          label="Revert To (When Off)"
                          options={this.state.collectionsBulkEditRevertOptions}
                          //value={this.state.collectionBeingEdited.revertSorting}
                          value={this.state.collectionsBulkEditRevertValue}
                          //onChange={(value,item,i)=>{this.metricsChangeCollection(value,this.state.collectionBeingEdited,'revertSorting')}}
                          onChange={(value)=>{this.changeCollectionsEditBulkRevert(value)}}
                        />
                      </FormLayout>
                      <div className={"settings-save-container "+((this.state.collectionsBulkEditShowSave) ? 'show':'hide')}>
                        <Button primary loading={this.state.collectionsBulkEditSaveLoading} disabled={this.state.collectionsBulkEditSaveLoading} onClick={() => { this.saveCollectionsEditBulk()}}>Save</Button>
                        <Button disabled={this.state.collectionsBulkEditSaveLoading} onClick={() => { this.discardCollectionsEditBulk()}}>Discard</Button>
                      </div>
                    </div>
                  </Modal>
                </div>
                <div className={"iec-tabbed-content "+((this.state.activeTab == 1) ? 'show':'hide')}>
                  <Layout.Section>
                      <div className={'tab-parent-page '+(this.state.metrics.createMetricsDisplay ? 'hide':'show')}>
                      <Page
                        title={'Metrics'}
                        primaryAction={
                          <Button
                            primary
                            onClick={()=>{this.displayEditMetrics(true,true)}}
                            disabled={(this.state.metricsResourceItemsCount >= this.state.init.permissions.metrics)}
                          >
                            Create Metrics
                          </Button>
                        }
                      >
                        <div className="top-card-padding metrics-tab">
                          <Card>
                            <Card.Section>
                              <Tabs 
                                tabs={this.state.metricsTabs} 
                                selected={this.state.activeMetricsTab} 
                                onSelect={this.handleMetricsNavChange}>
                              </Tabs> 
                            </Card.Section> 
                            <Card.Section>
                            <ResourceList
                                resourceName={{singular: 'metric', plural: 'metrics'}}
                                items={this.state.metricsResourceItems || []}
                                //shortcutActions={shortcutActions}
                                //persistActions
                                filterControl={(
                                  <div className="metric-header-container">
                                    <Filters
                                      queryValue={this.state.metricsFilterQueryValue}
                                      filters={[]}
                                      //appliedFilters={appliedFilters}
                                      onQueryChange={(value) => {this.metricsFilterChangeQueryValue(value)}}
                                      onQueryClear={(value) => {this.metricsFilterChangeQueryValue('')}}
                                      //onClearAll={() => console.log('Todo: implement onClearAll')}
                                    >
                                    <div className="sort-popover-container" style={{paddingLeft: '8px'}}>
                                      
                                      <Button onClick={() => {this.togglePopover('metrics')}}><Icon source={SortMinor} color="base" />Sort</Button>
                                      <div className={"sort-popover "+(this.state.popoverFilters.metrics.show? 'show':'hide')}>
                                        <ChoiceList
                                          //title="Company name"
                                          choices={[
                                            {label: 'Title A-Z', value: 'name-asc'},
                                            {label: 'Title Z-A', value: 'name-desc'},
                                            {label: 'Date (Newest first)', value: 'date-asc'},
                                            {label: 'Date (Oldest first)', value: 'date-desc'},
                                          ]}
                                          selected={this.state.popoverFilters.metrics.value}
                                          onChange={(value) => {this.changePopover(value,'metrics')}}
                                        />
                                      </div>
                                    </div>
                                    </Filters>
                                    <div className="resource-list-headings">
                                      <div className="resource-list-heading-item rlhi-1">
                                        <h3>Title</h3>
                                      </div>
                                      <div className="resource-list-heading-item rlhi-2">
                                        <h3>Attributes</h3>
                                      </div>
                                      <div className="resource-list-heading-item rlhi-3">
                                        <h3>Collections</h3>
                                      </div>
                                      <div className="resource-list-heading-item rlhi-4">
                                        <h3>Boost</h3>
                                      </div>
                                      <div className="resource-list-heading-item rlhi-5">
                                        <h3>Default</h3>
                                      </div>
                                    </div>
                                  </div>
                                )}
                                onSelectionChange={this.setCollectionsSelectedItems}
                                renderItem={(item,id,index) => {
                                  const {
                                    name, 
                                    attributes,
                                    collections,
                                    boost,
                                    is_default,
                                    enabled,
                                    attribute_name,
                                    //shortcutActions,
                                  } = item;
                                  let metricShortcutActions = [{content:'Edit',onAction:(e)=>{this.editMetrics(id,index)}}];


                                  return (
                                    <ResourceItem
                                      id={id}
                                      //url={url}
                                      //media={media}
                                      accessibilityLabel={`View details for ${name}`}
                                      shortcutActions={metricShortcutActions}
                                      persistActions
                                      //className={"url-resource-item "+((enable) ? 'url-resource-item-disabled':'')}
                                    >
                                      <div className="resource-item-col collection-resource-item-col collection-resource-item-col-1">
                                        <h3>
                                          <TextStyle variation="strong">{name}</TextStyle>
                                        </h3>
                                      </div>
                                      <div className="resource-item-col collection-resource-item-col collection-resource-item-col-2">
                                        <ul className="metric-attribute-list">
                                        {attributes.map(function(item, i){
                                          if(i < 3){
                                            //return <li key={i}><small>{item.select.value} ({item.value.charAt(0).toUpperCase() + item.value.replace('-',' ').slice(1)})</small></li>
                                            return <li key={i}>
                                              <small>{item.attribute_name} ({ item.value.length > 0 ? item.value: ''})</small>
                                            </li>
                                          } else {
                                            return;
                                          }
                                        })}
                                        {attributes.length > 3 ? <li className='metrics-and-more'><small>...and {attributes.length - 3} more</small></li>:''}
                                        </ul>
                                      </div>
                                      <div className="resource-item-col collection-resource-item-col collection-resource-item-col-3">
                                        <h3>
                                          <TextStyle variation="strong">Applied to {collections} collections</TextStyle>
                                        </h3>
                                      </div>
                                      <div className="resource-item-col collection-resource-item-col collection-resource-item-col-4">
                                        {boost == "1"? <Badge status="success">On</Badge>:<Badge>Off</Badge>}
                                      </div>
                                      <div className="resource-item-col collection-resource-item-col collection-resource-item-col-4">
                                        {is_default == "1"? <Badge status="success">Default</Badge>:''}
                                      </div>
                                    </ResourceItem>
                                  );
                                }}
                              />
                              <div className='pagination-container'>
                                <Pagination
                                  //hasPrevious
                                  onPrevious={() => {
                                    console.log('Previous');
                                  }}
                                  //hasNext
                                  onNext={() => {
                                    console.log('Next');
                                  }}
                                />
                              </div>
                            </Card.Section>                         
                          </Card>
                        </div>
                      </Page>
                    </div>
                    <div className={'create-page '+(this.state.metrics.createMetricsDisplay ? 'show':'hide')}>
                      <Page
                        title={this.state.metricsBeingEdited.name == '' ? 'Create Metrics':this.state.metricsBeingEdited.name}
                        breadcrumbs={(this.state.saveBar.show ? []:[{content: 'Metrics', onAction:()=>{this.displayEditMetrics(false,true)}}])}
                      >
                        <div className="top-card-padding">
                          <div className='metrics-top-actions'>
                            <Button
                            plain
                            monochrome
                            removeUnderline
                            onClick={() => this.duplicateMetrics(this.state.metricsBeingEdited.id)}
                            >
                              Duplicate
                            </Button>
                            <Button
                            plain
                            monochrome
                            removeUnderline
                            onClick={() => this.viewProductScores(this.state.metricsBeingEdited.id)}
                            >
                              View Product Scores
                            </Button>
                            {/*
                            <Pagination
                              onPrevious={() => {
                                console.log('Previous');
                              }}
                              //hasNext
                              onNext={() => {
                                console.log('Next');
                              }}
                              hasNext
                            ></Pagination>
                            */}
                          </div>
                          <Grid>
                            <Grid.Cell columnSpan={{xs: 12, sm: 12, md: 8, lg: 8, xl: 8}}>
                              <Card sectioned>
                                <Card.Section>
                                  <p>
                                    <TextField
                                      label="Title"
                                      value={this.state.metricsBeingEdited.name}
                                      //(isNew,index=false,key,value)
                                      onChange={(value) => { this.editMetricsObject(true,false,'name',value);}}
                                      autoComplete="off"
                                      //labelHidden
                                    />
                                  </p>
                                  <div className={'edit-metrics-card-heading'}>
                                    <h4>
                                      Attributes
                                      <div className="inline-tooltip-container">
                                        <Tooltip content={'Assign Attributes and their ranking weight for this metrics set'}>
                                          <Icon source={QuestionMarkMajor} color="base" />
                                        </Tooltip>
                                      </div>
                                    </h4>
                                  </div>
                                  <div>
                                  {
                                    this.state.metricsBeingEdited.attributes.map((item, i) => {
                                      return <div className='metric-attribute-row'>
                                              <Select 
                                                label="Type"
                                                //options={attributeOptionTypes}
                                                options={this.getAttributeOptionTypes(i)}
                                                value={this.state.metricsBeingEdited.attributes[i].select.value}
                                                onChange={(value) => { this.editMetricsAttributes(i,'select',value)}}
                                                labelHidden
                                              />  
                                              <TextField
                                                label="Value"
                                                value={this.state.metricsBeingEdited.attributes[i].value}
                                                onChange={(value) => { this.editMetricsAttributes(i,'value',value)}}
                                                autoComplete="off"
                                                labelHidden
                                                type={'number'}
                                                step={1}
                                              />
                                              <Button
                                                onClick={() => {this.removeMetricAttribute(i)}}
                                              ><Icon
                                              source={DeleteMajor}
                                              color="base" 
                                              /></Button>
                                            </div>
                                    })
                                  }
                                  </div>
                                  <Button disabled={
                                    (
                                      (
                                        this.getAttributeOptionTypes(-1).length < 1
                                      ) 
                                      && 
                                      (
                                        this.state.metricsBeingEdited.attributes > 0
                                      )
                                    )
                                    ||
                                    (
                                      this.getAttributeOptionTypes(-1).length == 0 
                                    )
                                  } onClick={()=>{this.addMetricsAttributeRow();}}>Add {(this.state.metricsBeingEdited.attributes.length > 0? 'another':'')} attribute</Button>
                                </Card.Section>
                                <Card.Section>
                                  <p>
                                    <Checkbox 
                                    label={'Apply Product Boost values to these metrics'}
                                    checked={(this.state.metricsBeingEdited.boost == "1" ? true:false)}
                                    onChange={() => {this.editMetricsObject(true,false,'boost',(this.state.metricsBeingEdited.boost == "0"? "1":"0"))}}
                                    />
                                    <div className='inline-tooltip-container'>
                                      <Tooltip content={'Select whether this metrics set boosts products as defined in the Products tab'} className={'inline-tooltip'}>
                                        <Icon source={QuestionMarkMajor} color="base" />
                                      </Tooltip>
                                    </div>
                                  </p>
                                </Card.Section>
                              </Card>
                              <Card
                              title="Metrics Preview">
                                <div className={'metrics-preview-products'}>
                                  <ResourceList
                                    
                                    resourceName={{singular: 'metric', plural: 'metrics'}}
                                    items={this.state.metricsPreviewProducts || []}
                                    emptyState={!this.state.metricsPreviewProducts.length? <EmptyState
                                      heading="Save Metrics to Preview Products Ordering"
                                    ><p>Once metrics are saved above, product ordering will display here.</p></EmptyState>:undefined}
                                    //onSelectionChange={this.setCollectionsSelectedItems}
                                    renderItem={(item) => {
                                      const {
                                        id, 
                                        position,
                                        title, 
                                        image,
                                        value
                                      } = item;

                                      return (
                                        <ResourceItem
                                          id={id}
                                          //url={url}
                                          //media={media}
                                          accessibilityLabel={`View details for ${title}`}
                                          //shortcutActions={shortcutActions}
                                          //persistActions
                                          //className={"url-resource-item "+((enable) ? 'url-resource-item-disabled':'')}
                                        >
                                          <div className="metric-product-item-col">
                                            {position}.
                                          </div>
                                          <div className="metric-product-item-col">
                                            <img src={image} alt={title} />
                                          </div>
                                          <div className="metric-product-item-col">
                                            {title}
                                          </div>
                                          <div className="metric-product-item-col">
                                            {value}
                                          </div>
                                        </ResourceItem>
                                      );
                                    }}
                                  />    
                                </div>       
                              </Card>
                            </Grid.Cell>
                            <Grid.Cell columnSpan={{xs: 12, sm: 12, md: 4, lg: 4, xl: 4}}>
                              <Card title="Settings" sectioned>
                                <Card.Section>
                                  <Checkbox 
                                  //label="Set as Default Metric" 
                                  label={'Set as Default Metric'}
                                  checked={parseInt(this.state.metricsBeingEdited.is_default)}
                                  onChange={() => {this.editMetricsObject(true,false,'is_default',(this.state.metricsBeingEdited.is_default == "0" ? "1":"0"))}}
                                  disabled={(this.state.metricsDefaultId == this.state.metricsBeingEdited.id)?true:false}
                                  />
                                </Card.Section>
                                <Card.Section>
                                  <Select 
                                    label="Sold Out Items"
                                    options={soldOutOptions}
                                    value={this.state.metricsBeingEdited.soldOutValue}
                                    onChange={(value) => this.editMetricsObject(true,false,'soldOutValue',value)}
                                  />
                                </Card.Section>
                                <Card.Section>
                                <Select 
                                    label="Tie Breaker"
                                    options={tieBreaker}
                                    value={this.state.metricsBeingEdited.tieBreakerValue}
                                    onChange={(value) => this.editMetricsObject(true,false,'tieBreakerValue',value)}
                                  />          
                                </Card.Section>
                              </Card>
                              <Card
                              title="Collections"
                              className="">
                                <div className='collections-side-card'>
                                  <TextField 
                                    prefix={<Icon source={SearchMinor} />}
                                    placeholder="Search for collections"
                                    autoCompleteRequired="off"
                                    label="Search for collections"
                                    labelHidden={true}
                                    onChange={(value) => this.sidebarCollectionsChange(value)}
                                    value={this.state.sidebarCollectionsValue}
                                  />
                                  <ul>
                                    {this.state.metricsSidebarCollections.map(function(item, i){
                                      return <li className={("collections-side-card-item-"+i)}>{ item }</li>
                                    })}
                                    {/*
                                    metricsSidebarCollections
                                    <li>Really long collection title that we'll surely encounter one day</li>
                                    <li>Super Collection</li>
                                    <li>Super Duper Collection</li>
                                    <li>Raddest Collection</li>
                                    <li>Stellar Collection</li>
                                    */}
                                  </ul>
                                </div>
                              </Card>
                            </Grid.Cell>
                          </Grid>
                        </div>
                      </Page>
                    </div>
      
                  </Layout.Section>
                </div>
                <div className={"iec-tabbed-content "+((this.state.activeTab == 2) ? 'show':'hide')}>
                  <Layout.Section>
                    <Page
                      title={'Products'}
                    >
                      <div className='header-selection-form'>
                        <FormLayout>
                          <Select 
                            label="Metrics"
                            options={this.state.productMetricsOptions}
                            value={this.state.productsMetricsSelected}
                            onChange={(value)=>{this.productsMetricsChanged(value)}}
                            labelInline={true}
                          />
                          <Select 
                            label="Collections"
                            options={this.state.productsCollectionsOptions}
                            value={this.state.productsCollectionsSelected}
                            onChange={(value)=>{this.changeProductsCollectionsChanged(value)}}
                            labelInline={true}
                          />
                          <div className='box-right'>
                            {/*
                            <Button
                              onClick={()=>{console.log('print')}}
                              external
                              monochrome
                              plain
                              removeUnderline
                            >
                              Print
                            </Button>
                            */}
                            <Button
                              //onClick={()=>{this.downloadProducts}}
                              external
                              monochrome
                              plain
                              removeUnderline
                              disabled={(this.state.init.permissions.exports == false ? true:false)}
                              url={(downloadProductsUrl+'?shop='+storeUrl+'&token='+this.state.init.plan_token+'&metrics='+this.state.productsMetricsSelected+'&collection='+this.state.productsCollectionsSelected)}
                            >
                              Download
                            </Button>
                          </div>
                        </FormLayout>
                      </div>
                      <IndexTableCustomHeadings
                        filters={this.state.filtersProduct}
                        products={this.state.products}
                        attributes={this.state.metricsCollectionProductsAttributes}
                        boost={this.state.metricsCollectionProductsBoost}
                        metrics={this.state.metricsResourceItems[this.state.productsMetricsSelected]}
                        change={(value,productId,index) => {this.editBoost(value,productId,index)}}
                        save={(productId,index) => {this.saveBoost(productId,index)}}
                        showProductCount={this.state.showProductCount}
                        showProductIndex={this.state.showProductIndex}
                        loadMore={() => {this.loadMoreProducts()}}
                        permissions={this.state.init.permissions}
                      />
                      
                    </Page>
                  </Layout.Section>
                </div>
                <div className={"iec-tabbed-content "+((this.state.activeTab == 3) ? 'show':'hide')}>
                  {
                  //check vars available
                  this.state.productAttributes == null
                  ? ''
                  :<Layout.Section>
                    <Page
                      title={'Attributes'}
                    >
                      <div className="top-card-padding product-data-attributes">
                        <Card>
                          <Heading element="h4">Product Data Attributes</Heading>
                          <ResourceList
                              resourceName={{singular: 'attribute', plural: 'attributes'}}
                              items={this.state.productAttributes['data'] || []}
                              filterControl={(
                                <div className="attributes-header-container">
                                  <div className="resource-list-headings">
                                    <div className="resource-list-heading-item rlhi-1">
                                      <h3>Name</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-2">
                                      <h3>Status</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-3">
                                      <h3>Configurables</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-4">
                                      <h3>Info</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-5"></div>
                                  </div>
                                </div>
                              )}
                              renderItem={(item) => {
                                return (
                                  <ResourceItem
                                    id={'id'}
                                    //url={url}
                                    //media={media}
                                    accessibilityLabel={`View details for ${item.name}`}
                                    shortcutActions={(item.status == "1" ? [{content:'Deactivate',onAction:(e)=>{this.attributeStatus("0",item.attribute_key)}}]:[{content:'Activate',onAction:(e)=>{this.attributeStatus("1",item.attribute_key)}}])}
                                    persistActions
                                    //className={"url-resource-item "+((enable) ? 'url-resource-item-disabled':'')}
                                  >
                                      <Configurables 
                                        configurables={item}
                                        change={(value,attributeKey,fieldKey) => {this.changeConfigurables(value,attributeKey,fieldKey)}}
                                        changeTitle={(value,attributeKey) => {this.changeConfigurableTitle(value,attributeKey)}}
                                        save={(attributeKey) => {this.saveConfigurables(attributeKey)}}
                                        section={'standard_attributes'}
                                        permissions={this.state.init.permissions}
                                        group='data'
                                        metaData={this.state.metaData}
                                      />                                  
                                  </ResourceItem>
                                );
                              }}
                          />
                        </Card>
                        <Card>
                          <Heading element="h4">Custom Attributes</Heading>
                          <div className={'custom-attributes '+(this.state.init.permissions.custom_attributes ? 'yep':'custom-attributes-disabled')}>
                            <ResourceList
                                resourceName={{singular: 'attribute', plural: 'attributes'}}
                                items={this.state.productAttributes['custom'] || []}
                                filterControl={(
                                  <div className="attributes-header-container">
                                    <div className="resource-list-headings">
                                      <div className="resource-list-heading-item rlhi-1">
                                        <h3>Name</h3>
                                      </div>
                                      <div className="resource-list-heading-item rlhi-2">
                                        <h3>Status</h3>
                                      </div>
                                      <div className="resource-list-heading-item rlhi-3">
                                        <h3>Configurables</h3>
                                      </div>
                                      <div className="resource-list-heading-item rlhi-4">
                                        <h3>Info</h3>
                                      </div>
                                      <div className="resource-list-heading-item rlhi-5"></div>
                                    </div>
                                  </div>
                                )}
                                renderItem={(item) => {
                                  return (
                                    <ResourceItem
                                      id={'id'}
                                      //url={url}
                                      //media={media}
                                      accessibilityLabel={`View details for ${item.name}`}
                                      shortcutActions={
                                        (
                                          (this.state.init.permissions.custom_attributes) ?
                                            item.status == "1" ? [
                                              {content:'Deactivate',onAction:(e)=>{this.attributeStatus("0",item.attribute_key)}},
                                              {content:'Delete',onAction:(e)=>{this.deleteAttribute(item.attribute_key)}},
                                              ]
                                              :
                                              [
                                                {content:'Activate',onAction:(e)=>{this.attributeStatus("1",item.attribute_key)}},
                                                {content:'Delete',onAction:(e)=>{this.deleteAttribute(item.attribute_key)}},
                                              ]
                                          :
                                            []
    
                                        )
                                      }
                                      persistActions
                                      //className={"url-resource-item "+((enable) ? 'url-resource-item-disabled':'')}
                                    >

                                        <Configurables 
                                          configurables={item}
                                          change={(value,attributeKey,fieldKey) => {this.changeConfigurables(value,attributeKey,fieldKey)}}
                                          changeTitle={(value,attributeKey) => {this.changeConfigurableTitle(value,attributeKey)}}
                                          save={(attributeKey) => {this.saveConfigurables(attributeKey)}}
                                          section={'custom_attributes'}
                                          permissions={this.state.init.permissions}
                                          group='custom'
                                          metaData={this.state.metaData}
                                        />                                    
                                    </ResourceItem>
                                  );
                                }}
                            />
                            <div className='add-attribute-container'>
                              <Button
                                onClick={() => {this.addAttribute()}}
                              >
                                Add another attribute
                              </Button>
                            </div>
                          </div>
                        </Card>
                        {/* //hidden for review/dev
                        <Card>
                          <Heading element="h4">Partner Integrated Attributes</Heading>
                          <ResourceList
                              resourceName={{singular: 'attribute', plural: 'attributes'}}
                              items={this.state.productAttributes['partner'] || []}
                              filterControl={(
                                <div className="attributes-header-container">
                                  <div className="resource-list-headings">
                                    <div className="resource-list-heading-item rlhi-1">
                                      <h3>Name</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-2">
                                      <h3>Status</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-3">
                                      <h3>Configurables</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-4">
                                      <h3>Info</h3>
                                    </div>
                                    <div className="resource-list-heading-item rlhi-5"></div>
                                  </div>
                                </div>
                              )}
                              renderItem={(item) => {
                                return (
                                  <ResourceItem
                                    id={'id'}
                                    //url={url}
                                    //media={media}
                                    accessibilityLabel={`View details for ${item.name}`}
                                    shortcutActions={(item.status == "1" ? [{content:'Deactivate',onAction:(e)=>{this.attributeStatus("0",item.attribute_key)}}]:[{content:'Activate',onAction:(e)=>{this.attributeStatus("1",item.attribute_key)}}])}
                                    persistActions
                                    //className={"url-resource-item "+((enable) ? 'url-resource-item-disabled':'')}
                                  >
                                    <div className="resource-item-col attributes-resource-item-col attributes-resource-item-col-1">
                                      <h3>
                                        {(item.image != '' ? <img class="attribute-partner-image" src={item.image} alt={(item.name + " Image")} />:'')}
                                        <TextStyle variation="strong">{item.name}</TextStyle>
                                      </h3>
                                    </div>
                                    <div className="resource-item-col attributes-resource-item-col attributes-resource-item-col-2">
                                      {item.status == "1"? <Badge status="success">Active</Badge>:<Badge>Inactive</Badge>}
                                    </div>
                                    <div className="resource-item-col attributes-resource-item-col attributes-resource-item-col-3">
                                      <Configurables 
                                        configurables={item}
                                        change={(value,attributeKey,fieldKey) => {this.changeConfigurables(value,attributeKey,fieldKey)}}
                                        save={(attributeKey) => {this.saveConfigurables(attributeKey)}}
                                        section={'partner_attributes'}
                                        permissions={this.state.init.permissions}
                                      />
                                    </div>                                    
                                    <div className="resource-item-col attributes-resource-item-col attributes-resource-item-col-4">
                                      <Tooltip content={item.tooltip}>
                                        <p><Icon source={CircleInformationMajor} color="base" /></p>
                                      </Tooltip>
                                    </div>                                    
                                  </ResourceItem>
                                );
                              }}
                          />
                        </Card>
                        */}
                      </div>                    
                    </Page>
                  </Layout.Section>
                  }
                </div>
                <div className={"iec-tabbed-content top-padding "+((this.state.activeTab == 4) ? 'show':'hide')}>
                  {
                  //check vars available
                  //this.state.productAttributes == null
                  this.state.settings.processing_interval == null
                  ||
                  this.state.settings.days_of_the_week == null
                  ||
                  this.state.settings.hours_of_the_day == null
                  ||
                  this.state.settings.email_shop_owner == null
                  ||
                  this.state.settings.additional_emails == null
                  ||
                  this.state.settings.notify_collections_sorted == null
                  ||
                  this.state.settings.notify_order_changed == null
                  ? ''
                  :
                  <Page>
                    <Layout.AnnotatedSection
                      title="Processing Schedule"
                      description="This is how often the app will process your
                      collections to apply your sorting metrics.
                      Premium plans have more options on timing.
                      To see these options please check your plan."
                    >
                      <Card>
                        <FormLayout>
                          <Select
                            label="Processing Schedule"
                            options={this.state.settings.processing_interval.options}
                            onChange={(value) => {this.changeSettingsSelect(value,'processing_interval')}}
                            value={this.state.settings.processing_interval.value}
                          />
                          <Select
                            label="Days of the Week"
                            options={this.state.settings.days_of_the_week.options}
                            onChange={(value) => {this.changeSettingsSelect(value,'days_of_the_week')}}
                            value={this.state.settings.days_of_the_week.value}
                          />
                          <Select
                            label="Hours of the Day to Run"
                            options={this.state.settings.hours_of_the_day.options}
                            onChange={(value) => {this.changeSettingsSelect(value,'hours_of_the_day')}}
                            value={this.state.settings.hours_of_the_day.value}
                          />
                          <div className={"settings-save-container "+((this.state.showProcessingSave) ? 'show':'hide')}>
                            <Button primary loading={this.state.settings.processingSaveLoading} disabled={this.state.settings.processingSaveLoading} onClick={() => { this.saveProcessingSettings()}}>Save</Button>
                            <Button disabled={this.state.settings.processingSaveLoading} onClick={() => { this.discardProcessingSettings()}}>Discard</Button>
                          </div>
                        </FormLayout>
                      </Card>
                    </Layout.AnnotatedSection>
                      {/* //hidden for review and dev
                    <Layout.AnnotatedSection
                      title="Notifications"
                      description={"Configure when the app sends you e-mail notifications and to what address."}
                    >
                      <Card>
                        <Heading element="h4">E-mail Addresses</Heading>
                        <FormLayout>
                          <p>Deliver notifications to the following e-mail addresses:</p>
                          <p><Checkbox 
                            checked={(this.state.settings.email_shop_owner.value == "true" ? true:false)}
                            label={'Shop owner ('+this.state.init.shop_email+')'} 
                            onChange={() => {this.changeSettingsCheckbox('email_shop_owner',(this.state.settings.email_shop_owner.value == "false"? "true":"false"))}}
                          /></p>
                          <TextField 
                            label="Additional E-mail Addresses"
                            helpText="Split multiple addresses by commas"
                            value={this.state.settings.additional_emails.value}
                            onChange={(value) => this.changeSettingsAdditionalEmails(value)}
                            autoComplete={'off'}
                            error={this.state.errors.additional_emails}
                          ></TextField>
                        </FormLayout>
                        <Heading element="h4">Events</Heading>
                        <p>Send e-mails on the following events:</p>
                        <FormLayout>
                        <table className="settings-table">
                            <thead>
                              <tr>
                                <th>Event</th>
                                <th>Per Process</th>
                                <th>Daily Digest</th>
                                <th>None</th>
                              </tr>
                            </thead>
                            <tbody>
                              <tr>
                                <td>Collections sorted</td>                               
                                <td><Checkbox 
                                      onChange={() => {this.changeSettingsCheckbox('notify_collections_sorted','per_process')}} 
                                      label="Collections Sorted Per Process" 
                                      labelHidden={true} 
                                      checked={(this.state.settings.notify_collections_sorted.value == 'per_process' ? true:false)} 
                                /></td>
                                <td><Checkbox 
                                      onChange={() => {this.changeSettingsCheckbox('notify_collections_sorted','daily_digest')}} 
                                      label="Collections Sorted Daily Digest" 
                                      labelHidden={true} 
                                      checked={(this.state.settings.notify_collections_sorted.value == 'daily_digest' ? true:false)} 
                                /></td>
                                <td><Checkbox 
                                      onChange={() => {this.changeSettingsCheckbox('notify_collections_sorted','')}} 
                                      label="Collections Sorted None" 
                                      labelHidden={true} 
                                      checked={(this.state.settings.notify_collections_sorted.value == '' ? true:false)} 
                                /></td>
                                </tr>
                              <tr>
                                <td>Sorting Order Changed</td>
                                <td><Checkbox 
                                      onChange={() => {this.changeSettingsCheckbox('notify_order_changed','per_process')}} 
                                      label="Order Changed Per Process" 
                                      labelHidden={true} 
                                      checked={(this.state.settings.notify_order_changed.value == 'per_process' ? true:false)} 
                                /></td>
                                <td><Checkbox 
                                      onChange={() => {this.changeSettingsCheckbox('notify_order_changed','daily_digest')}} 
                                      label="Order Changed Daily Digest" 
                                      labelHidden={true} 
                                      checked={(this.state.settings.notify_order_changed.value == 'daily_digest' ? true:false)} 
                                /></td>
                                <td><Checkbox 
                                      onChange={() => {this.changeSettingsCheckbox('notify_order_changed','')}} 
                                      label="Order Changed None" 
                                      labelHidden={true} 
                                      checked={(this.state.settings.notify_order_changed.value == '' ? true:false)} 
                                /></td>
                              </tr>
                            </tbody>
                          </table>
                        </FormLayout>
                        <div className={"settings-save-container "+((this.state.showNotificationsSave) ? 'show':'hide')}>
                          <Button primary loading={this.state.notificationsSaveLoading} disabled={this.state.settings.notificationsSaveLoading} onClick={() => { this.saveNotificationsSettings()}}>Save</Button>
                          <Button disabled={this.state.settings.notificationsSaveLoading} onClick={() => { this.discardNotificationsSettings()}}>Discard</Button>
                        </div>
                      </Card>
                    </Layout.AnnotatedSection>
                      */}
                  </Page>
                  }
                </div>
                <div className={"iec-tabbed-content "+((this.state.activeTab == 5) ? 'show':'hide')}>
                  <Layout.Section>
                    <Page
                      title={'Plans'}
                    >
                      <Plans 
                        plans={this.state.init.plans}
                        storeUrl={storeUrl}
                        planUrl={planUrl}
                        token={this.state.init.plan_token}
                        boxHeight={280}
                      />
                    </Page>
                  </Layout.Section>
                </div>
              </div>
            </Layout>
          </div>
          <div className={"loading-skeleton "+(!hasRunInit? '':'hide')}>
            <SkeletonPage>
              <Layout>
                <Layout.Section>
                  <Card sectioned>
                    <SkeletonBodyText />
                  </Card>
                  <Card sectioned>
                    <TextContainer>
                      <SkeletonDisplayText size="small" />
                      <SkeletonBodyText />
                    </TextContainer>
                  </Card>
                  <Card sectioned>
                    <TextContainer>
                      <SkeletonDisplayText size="small" />
                      <SkeletonBodyText />
                    </TextContainer>
                  </Card>
                </Layout.Section>
              </Layout>
            </SkeletonPage>
          </div>
        </Frame>
      </AppProvider>
        
    );
  }
}

export default App;
