import{Chart as e,BarController as t,BarElement as i,Tooltip as c,CategoryScale as a,LinearScale as r,Title as s,Filler as n}from"chart.js";import{LitElement as o,html as l,css as m}from"lit";import{classMap as d}from"lit/directives/class-map.js";import{createRef as p,ref as h}from"lit/directives/ref.js";import{iconCleverGrafana as g,iconCleverInfo as u,iconCleverRam as y}from"./assets/cc-clever.icons.js";import{iconRemixCloseLine as b,iconRemixCpuLine as v,iconRemixAlertFill as f}from"./assets/cc-remix.icons.js";import{ResizeController as _}from"./controllers/resize-controller.js";import{isStringEmpty as $}from"./lib/utils.js";import{accessibilityStyles as k}from"./styles/accessibility.js";import{tileStyles as x}from"./styles/info-tiles.js";import{skeletonStyles as C}from"./styles/skeleton.js";import{i18n as w}from"./translation.js";import"./cc-button.js";import"./cc-icon.js";import"./cc-link.js";e.register(t,i,c,a,r,s,n);const S="#bbb",j=Array.from(new Array(24)).map(((e,t)=>({skeleton:!0,value:0,timestamp:Date.now()-864e5+3600*t})));class z extends o{static get properties(){return{grafanaLinkState:{type:Object,attribute:"grafana-link-state"},metricsLink:{type:String,attribute:"metrics-link"},metricsState:{type:Object,attribute:"metrics-state"},_docsPanelVisible:{type:Boolean,state:!0}}}constructor(){super(),this.metricsLink=null,this.metricsState={type:"loading"},this.grafanaLinkState={type:"loading"},this._docsPanelVisible=!1,this._cpuCtxRef=p(),this._memCtxRef=p(),new _(this,{callback:()=>this.updateComplete.then((()=>{this._cpuChart?.resize(),this._memChart?.resize()}))})}_createChart(t){return new e(t,{type:"bar",options:{responsive:!1,maintainAspectRatio:!1,radius:0,interaction:{intersect:!1},scales:{x:{display:!1,stacked:!0},y:{display:!1,beginAtZero:!0}},plugins:{legend:{display:!1},tooltip:{enabled:!1}}}})}_getChartData(e,t){const i=e.map((e=>e.timestamp)),c=e.map((e=>e.value)),a=Array.from(new Array(24)).map((e=>100));return{labels:i,datasets:[{fill:"origin",data:c,backgroundColor:e.map((({value:e})=>t?S:this._getColorChart(e)))},{fill:"origin",data:a}]}}_getColorChart(e){return e>80?"rgb(190, 52, 97)":e>20?"rgb(78, 100, 234)":"rgb(100, 146, 234)"}_getColorLegend(e){return e>80?"var(--cc-color-text-danger)":e>20?"var(--cc-color-text-primary-strong)":"var(--cc-color-text-primary)"}_getCurrentPanel(){return this._docsPanelVisible?"docs":"error"===this.metricsState.type?"error":"empty"===this.metricsState.type?"empty":"loading"===this.metricsState.type||"loaded"===this.metricsState.type?"chart":void 0}_onToggleDocs(){this._docsPanelVisible=!this._docsPanelVisible}firstUpdated(){this._cpuChart=this._createChart(this._cpuCtxRef.value),this._memChart=this._createChart(this._memCtxRef.value)}updated(e){e.has("metricsState")&&(this._cpuChart.data="loaded"===this.metricsState.type?this._getChartData(this.metricsState.metricsData.cpuMetrics,!1):this._getChartData(j,!0),this._cpuChart.update(),this._cpuChart.resize(),this._memChart.data="loaded"===this.metricsState.type?this._getChartData(this.metricsState.metricsData.memMetrics,!1):this._getChartData(j,!0),this._memChart.update(),this._memChart.resize())}render(){const e="loading"===this.metricsState.type,t="loaded"===this.metricsState.type?this.metricsState.metricsData.cpuMetrics.slice(-1)[0]?.value:0,i="loaded"===this.metricsState.type?this.metricsState.metricsData.memMetrics.slice(-1)[0]?.value:0,c="loaded"===this.metricsState.type?this._getColorLegend(t):S,a="loaded"===this.metricsState.type?this._getColorLegend(i):S,r=[];"loaded"===this.grafanaLinkState.type&&r.push(l`
        <cc-link
          href="${this.grafanaLinkState.link}"
          ?skeleton="${e}"
          a11y-desc="${w("cc-tile-metrics.link-to-grafana")}"
        >
          ${w("cc-tile-metrics.grafana")}
        </cc-link>
      `),$(this.metricsLink)||r.push(l`
        <cc-link href="${this.metricsLink}" a11y-desc="${w("cc-tile-metrics.link-to-metrics")}">
          ${w("cc-tile-metrics.metrics-link")}
        </cc-link>
      `);const s=this._getCurrentPanel();return l`
      <div class="tile_title">
        ${w("cc-tile-metrics.title")}
        <div class="docs-buttons">
          ${"loaded"===this.grafanaLinkState.type?l`
                <cc-link
                  href="${this.grafanaLinkState.link}"
                  a11y-desc="${w("cc-tile-metrics.link-to-grafana")}"
                  disable-external-link-icon
                >
                  <cc-icon
                    class="icon--grafana"
                    .icon=${g}
                    a11y-name="${w("cc-tile-metrics.link-to-grafana")}"
                  ></cc-icon>
                </cc-link>
              `:""}
          <cc-button
            class="docs-toggle ${d({"icon--close":this._docsPanelVisible,"icon--info":!this._docsPanelVisible})}"
            .icon=${this._docsPanelVisible?b:u}
            hide-text
            @cc-click=${this._onToggleDocs}
          >
            ${this._docsPanelVisible?w("cc-tile-metrics.close-btn"):w("cc-tile-metrics.about-btn")}
          </cc-button>
        </div>
      </div>
      <div class="tile_body ${d({"tile--hidden":"chart"!==s})}">
        <div class="category" aria-hidden="true">
          <cc-icon size="lg" class="icon--cpu" .icon=${v}></cc-icon>
          <div class="chart-container-wrapper chart-cpu">
            <div class="chart-container ${d({skeleton:e})}">
              <canvas id="cpu_chart" ${h(this._cpuCtxRef)}></canvas>
            </div>
          </div>
          <div
            class="current-percentage percent-cpu ${d({skeleton:e,"skeleton-data-value":e})}"
            style="color: ${c}"
          >
            ${w("cc-tile-metrics.percent",{percent:t/100})}
          </div>
          <div class="legend-cpu">${w("cc-tile-metrics.legend.cpu")}</div>
        </div>
        <div class="category" aria-hidden="true">
          <cc-icon size="lg" class="icon--mem" .icon=${y}></cc-icon>
          <div class="chart-container-wrapper chart-mem">
            <div class="chart-container ${d({skeleton:e})}">
              <canvas id="mem_chart" ${h(this._memCtxRef)}></canvas>
            </div>
          </div>
          <div
            class="current-percentage percent-mem ${d({skeleton:e,"skeleton-data-value":e})}"
            style="color: ${a}"
          >
            ${w("cc-tile-metrics.percent",{percent:i/100})}
          </div>
          <div class="legend-mem">${w("cc-tile-metrics.legend.mem")}</div>
        </div>
        ${"loaded"===this.metricsState.type?this._renderAccessibleTable(this.metricsState.metricsData):""}
      </div>

      <div class="tile_message ${d({"tile--hidden":"empty"!==s})}">
        ${w("cc-tile-metrics.empty")}
      </div>

      <div class="tile_message ${d({"tile--hidden":"error"!==s})}">
        <div class="error-message">
          <cc-icon
            .icon="${f}"
            a11y-name="${w("cc-tile-metrics.error.icon-a11y-name")}"
            class="icon-warning"
          ></cc-icon>
          <p>${w("cc-tile-metrics.error")}</p>
        </div>
      </div>

      <div class="tile_docs ${d({"tile--hidden":"docs"!==s})}">
        ${w("cc-tile-metrics.docs.msg")}
        ${r.length>0?l`<div class="docs-links">
              <p>${w("cc-tile-metrics.docs.more-metrics")}</p>
              <ul>
                ${r.map((e=>l`<li>${e}</li>`))}
              </ul>
            </div>`:""}
      </div>
    `}_renderAccessibleTable({cpuMetrics:e,memMetrics:t}){return l`
      <table class="visually-hidden">
        <caption>
          ${w("cc-tile-metrics.title")}
        </caption>
        <thead>
          <tr>
            <th lang="en">${w("cc-tile-metrics.a11y.table-header.timestamp")}</th>
            <th>${w("cc-tile-metrics.a11y.table-header.cpu")}</th>
            <th>${w("cc-tile-metrics.a11y.table-header.mem")}</th>
          </tr>
        </thead>
        <tbody>
          ${e.map(((e,i)=>{const c=t[i];return l`
              <tr>
                <th>${w("cc-tile-metrics.timestamp-format",{timestamp:e.timestamp})}</th>
                <td>${w("cc-tile-metrics.percent",{percent:e.value/100})}</td>
                <td>${w("cc-tile-metrics.percent",{percent:c.value/100})}</td>
              </tr>
            `}))}
        </tbody>
      </table>
    `}static get styles(){return[k,C,x,m`
        /* region header */
        .tile_title {
          align-items: center;
          display: flex;
          justify-content: space-between;
        }

        .tile_title cc-link {
          align-items: center;
          /* TODO: Change variable when we have proper border token */
          border: 1px solid var(--cc-color-bg-strong);
          border-radius: var(--cc-border-radius-small, 0.15em);
          box-shadow: rgb(255 255 255 / 0%) 0 0 0 0;
          box-sizing: border-box;
          display: flex;
          height: 1.75em;
          justify-content: center;
          transition: box-shadow 75ms ease-in-out 0s;
          width: 1.75em;
        }

        .tile_title cc-link:hover {
          box-shadow: rgb(0 0 0 / 40%) 0 1px 3px;
        }

        .docs-buttons {
          align-items: center;
          display: flex;
          font-size: 0.8em;
          gap: 0.5em;
        }

        /* endregion */

        /* region chart */

        .chart-container-wrapper {
          grid-area: chart-wrapper;
          height: 100%;
          position: relative;
          width: 100%;
        }

        .chart-cpu {
          grid-area: chart-cpu;
        }

        .chart-mem {
          grid-area: chart-mem;
        }

        .chart-container {
          /* We need this because: https://github.com/chartjs/Chart.js/issues/4156 */
          height: 100%;
          margin: auto;
          min-width: 0;
          position: absolute;
          width: 100%;
        }

        /* endregion */

        /* region tile-body */

        .tile_body {
          align-items: center;
          gap: 0 1em;
          grid-template-areas:
            'icon-cpu chart-cpu percent-cpu'
            '. legend-cpu .'
            'icon-mem chart-mem percent-mem'
            '. legend-mem .';
          grid-template-columns: min-content 1fr min-content;
          grid-template-rows: 1fr max-content 1fr max-content;
          min-height: 8.75em;
          position: relative;
        }

        .percent-cpu {
          grid-area: percent-cpu;
        }

        .percent-mem {
          grid-area: percent-mem;
        }

        .skeleton-data-value {
          background-color: #bbb;
        }

        /*
    body, message and docs are placed in the same area (on top of each other)
    this way, we can just hide the docs
    and let the tile take at least the height of the docs text content
   */

        .tile_body,
        .tile_message,
        .tile_docs {
          grid-area: 2 / 1 / 3 / 2;
        }

        /* See above why we hide instead of display:none */

        .tile--hidden {
          visibility: hidden;
        }

        .category {
          display: contents;
        }

        .current-percentage {
          justify-self: end;
        }

        .legend-cpu,
        .legend-mem {
          align-self: center;
          color: var(--cc-color-text-weak);
          font-size: 0.75em;
          font-style: italic;
          justify-self: center;
          margin-top: 0.5em;
        }

        .legend-cpu {
          grid-area: legend-cpu;
          margin-bottom: 1.25em;
        }

        .legend-mem {
          grid-area: legend-mem;
        }

        .tile_docs {
          align-content: center;
          display: grid;
        }

        p {
          margin: 0;
        }

        .tile_docs ul {
          display: flex;
          gap: 0.5em;
          list-style: none;
          margin: 0;
          padding: 0;
        }

        .docs-links {
          align-items: flex-end;
          display: flex;
          gap: 0.5em;
          margin-top: 0.5em;
        }

        /* endregion */

        /* region icons */

        .icon--close {
          --cc-icon-size: 1.4em;
        }

        .icon--info {
          --cc-icon-color: var(--color-blue-60);
          --cc-icon-size: 1.25em;
        }

        .icon--grafana {
          --cc-icon-size: 1.25em;
        }

        .icon--cpu {
          grid-area: icon-cpu;

          --cc-icon-color: var(--cc-color-text-weak);
        }

        .icon--mem {
          grid-area: icon-mem;

          --cc-icon-color: var(--cc-color-text-weak);
        }

        /* endregion */

        /* region error */

        .error-message {
          display: grid;
          gap: 0.75em;
          grid-template-columns: min-content 1fr;
          text-align: left;
        }

        .error-message p {
          margin: 0;
        }

        .icon-warning {
          align-self: center;
          color: var(--cc-color-text-warning);

          --cc-icon-size: 1.25em;
        }

        /* endregion */
      `]}}window.customElements.define("cc-tile-metrics",z);export{z as CcTileMetrics};
//# sourceMappingURL=cc-tile-metrics.js.map
