const {
  IconSearch, IconChevDown, IconClock, IconInfo, IconGripV, IconPlus,
  IconChevsLeft, IconChevsRight, IconChevLeft, IconChevRight, IconCaretRight,
  IconCT,
} = window.Icons;

const { NAMESPACES, AREA_DATA, AREA_X_LABELS, AREA_Y_LABELS, DASHBOARD_FIELDS } = window.Data;

// ─── Chart-type rail (left side)
const CHART_TYPES = [
  { id: "bar",     icon: IconCT.bar,     color: "accent" },
  { id: "area",    icon: IconCT.area,    color: "accent", active: true },
  { id: "stack",   icon: IconCT.stack,   color: "accent" },
  { id: "h-stack", icon: IconCT.stack,   color: "accent", rotate: true },
  { id: "line",    icon: IconCT.line,    color: "accent" },
  { id: "scatter", icon: IconCT.scatter, color: "accent" },
  { id: "bar-2",   icon: IconCT.bar,     color: "warn" },
  { id: "stack-2", icon: IconCT.stack,   color: "warn" },
  { id: "pie",     icon: IconCT.pie,     color: "ok" },
  { id: "donut",   icon: IconCT.donut,   color: "ok" },
  { id: "gauge",   icon: IconCT.gauge,   color: "ok" },
  { id: "funnel",  icon: IconCT.funnel,  color: "warn" },
  { id: "num",     icon: IconCT.num,     color: "muted" },
  { id: "table",   icon: IconCT.table,   color: "accent" },
  { id: "heatmap", icon: IconCT.heatmap, color: "warn" },
  { id: "sankey",  icon: IconCT.sankey,  color: "accent" },
  { id: "html",    icon: IconCT.text,    color: "muted" },
  { id: "md",      icon: IconCT.md,      color: "muted" },
  { id: "gauge-2", icon: IconCT.gauge,   color: "ok" },
  { id: "map",     icon: IconCT.map,     color: "err" },
];

const COLOR_MAP = {
  accent: "var(--accent-fg)",
  warn:   "var(--warn)",
  ok:     "var(--ok)",
  err:    "var(--err)",
  muted:  "var(--ink-2)",
};

function ChartRail() {
  return (
    <div style={{
      width: 78, flexShrink: 0,
      borderRight: "1px solid var(--border)",
      background: "var(--surface)",
      display: "grid", gridTemplateColumns: "1fr 1fr",
      alignContent: "start",
    }}>
      {CHART_TYPES.map((t, i) => {
        const Ico = t.icon;
        const isActive = t.active;
        return (
          <button key={t.id} style={{
            height: 42,
            border: "none",
            background: isActive ? "var(--accent-bg)" : "transparent",
            borderRight: i % 2 === 0 ? "1px solid var(--border)" : "none",
            borderBottom: "1px solid var(--border)",
            color: isActive ? "var(--accent-fg)" : COLOR_MAP[t.color],
            cursor: "pointer",
            display: "flex", alignItems: "center", justifyContent: "center",
            position: "relative",
          }}
          onMouseEnter={e => !isActive && (e.currentTarget.style.background = "var(--rail)")}
          onMouseLeave={e => !isActive && (e.currentTarget.style.background = "transparent")}>
            <Ico size={17} sw={1.5} />
          </button>
        );
      })}
    </div>
  );
}

// ─── Fields panel (Stream + Search + field list)
function FieldsPanel() {
  return (
    <div style={{
      width: 280, flexShrink: 0,
      borderRight: "1px solid var(--border)",
      background: "var(--surface)",
      display: "flex", flexDirection: "column", minHeight: 0,
      position: "relative",
    }}>
      {/* Accent indicator (mirrors the left blue bar in source) */}
      <div style={{
        position: "absolute", right: -2, top: 0, bottom: 0,
        width: 3, background: "var(--accent)",
      }}/>
      <div style={{
        padding: "10px 14px 8px",
        borderBottom: "1px solid var(--border)",
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>Fields</span>
        <div style={{
          width: 8, height: 8, borderRadius: "50%",
          background: "var(--accent)",
        }}/>
      </div>

      {/* Stream Type */}
      <div style={{
        padding: "8px 14px", background: "var(--rail)",
        borderBottom: "1px solid var(--border)",
      }}>
        <div style={{ fontSize: 9.5, color: "var(--muted)", fontWeight: 500, letterSpacing: ".03em", textTransform: "uppercase", whiteSpace: "nowrap" }}>
          Stream Type
        </div>
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          marginTop: 1, fontSize: 12.5, color: "var(--ink)",
        }}>
          <span>metrics</span><IconChevDown size={12} style={{ color: "var(--muted)" }}/>
        </div>
      </div>

      {/* Stream */}
      <div style={{
        padding: "8px 14px", background: "var(--rail)",
        borderBottom: "1px solid var(--border)",
      }}>
        <div style={{ fontSize: 9.5, color: "var(--muted)", fontWeight: 500, letterSpacing: ".03em", textTransform: "uppercase", whiteSpace: "nowrap" }}>
          Stream
        </div>
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          marginTop: 1, fontSize: 12.5, color: "var(--ink)",
        }}>
          <span className="mono" style={{ display: "flex", alignItems: "center", gap: 7 }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="1.8" strokeLinecap="round">
              <path d="M4 12a8 8 0 0 1 16 0"/><path d="m12 12 5-3"/>
            </svg>
            k8s_pod_memory_rss
          </span>
          <IconChevDown size={12} style={{ color: "var(--muted)" }}/>
        </div>
      </div>

      {/* Search bar */}
      <div style={{
        padding: "8px 14px",
        borderBottom: "2px solid var(--ink)",
        display: "flex", alignItems: "center", gap: 8,
      }}>
        <IconSearch size={13} style={{ color: "var(--muted)" }}/>
        <span style={{ color: "var(--muted-2)", fontSize: 12 }}>Search for a field</span>
      </div>

      {/* Field list */}
      <div style={{ flex: 1, overflowY: "auto" }}>
        {DASHBOARD_FIELDS.map((f, i) => (
          <div key={f.name} style={{
            display: "flex", alignItems: "center", gap: 10,
            padding: "5.5px 14px",
            fontSize: 12, color: "var(--ink-2)",
            cursor: "pointer",
          }}
          onMouseEnter={e => e.currentTarget.style.background = "var(--rail)"}
          onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
            <span style={{ fontSize: 9, color: "var(--muted)", fontWeight: 600, width: 14, textAlign: "center" }}>
              {f.type === "num" ? "#" : "Aa"}
            </span>
            <span>{f.name}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Stacked area chart (SVG-rendered, hand-tuned)
function StackedAreaChart() {
  const W = 760, H = 360;
  const padL = 56, padR = 24, padT = 14, padB = 24;
  const chartW = W - padL - padR;
  const chartH = H - padT - padB;
  const maxY = 139.70;
  const xs = AREA_DATA.length;

  // build cumulative stacks
  // For each x, compute cumulative sum top-down per series
  const stacks = NAMESPACES.map(() => []);
  AREA_DATA.forEach((row, xi) => {
    let acc = 0;
    NAMESPACES.forEach((n, ni) => {
      const v = row[n.key] || 0;
      stacks[ni].push({ x: xi, y0: acc, y1: acc + v });
      acc += v;
    });
  });

  function pt(xi, y) {
    const x = padL + (xi / (xs - 1)) * chartW;
    const py = padT + chartH - (y / maxY) * chartH;
    return [x, py];
  }

  function buildArea(stack) {
    let d = "";
    stack.forEach((s, i) => {
      const [x, y] = pt(s.x, s.y1);
      d += `${i === 0 ? "M" : "L"}${x.toFixed(1)} ${y.toFixed(1)} `;
    });
    for (let i = stack.length - 1; i >= 0; i--) {
      const s = stack[i];
      const [x, y] = pt(s.x, s.y0);
      d += `L${x.toFixed(1)} ${y.toFixed(1)} `;
    }
    d += "Z";
    return d;
  }

  return (
    <svg width="100%" height="100%" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
      {/* Y-axis labels + grid */}
      {AREA_Y_LABELS.map((y, i) => {
        const py = padT + chartH - (y.v / maxY) * chartH;
        return (
          <g key={i}>
            <line x1={padL} y1={py} x2={W - padR} y2={py} stroke="var(--border)" strokeWidth="0.5" strokeDasharray="2 2"/>
            <text x={padL - 6} y={py + 3} textAnchor="end" fontSize="9" fontFamily="JetBrains Mono" fill="var(--muted)">
              {y.label}
            </text>
          </g>
        );
      })}

      {/* Stacked areas */}
      {stacks.map((stk, ni) => (
        <path key={ni} d={buildArea(stk)}
              fill={NAMESPACES[ni].color}
              fillOpacity="0.78"
              stroke={NAMESPACES[ni].color}
              strokeWidth="0.5"
              strokeOpacity="1"/>
      ))}

      {/* X-axis labels */}
      {AREA_X_LABELS.map((label, i) => {
        const x = padL + (i / (AREA_X_LABELS.length - 1)) * chartW;
        return (
          <text key={label} x={x} y={H - 6} textAnchor="middle"
                fontSize="9" fontFamily="JetBrains Mono" fill="var(--muted)">
            {label}
          </text>
        );
      })}
    </svg>
  );
}

// ─── Legend (right side)
function Legend() {
  return (
    <div style={{
      width: 200, flexShrink: 0, paddingLeft: 8,
      display: "flex", flexDirection: "column", minHeight: 0,
    }}>
      <div style={{
        textAlign: "right", marginBottom: 8,
        fontSize: 11, color: "var(--ink-2)",
        display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 4,
      }}>
        <IconClock size={11} />
        <span>now</span>
      </div>
      <div style={{ flex: 1, overflowY: "auto", paddingRight: 2 }}>
        {NAMESPACES.map(n => (
          <div key={n.key} style={{
            display: "flex", alignItems: "center", gap: 8,
            padding: "2.5px 0",
            fontSize: 11, color: "var(--ink)",
          }}>
            <svg width="22" height="10" viewBox="0 0 22 10">
              <line x1="0" y1="5" x2="22" y2="5" stroke={n.color} strokeWidth="1.5"/>
              <circle cx="11" cy="5" r="3.4" fill="var(--surface)" stroke={n.color} strokeWidth="1.8"/>
            </svg>
            <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
              {n.name}
            </span>
          </div>
        ))}
      </div>
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: "4px 0", gap: 10, color: "var(--muted)",
      }}>
        <button className="icon-btn" style={{ width: 18, height: 18 }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="m12 5 7 8H5z"/></svg>
        </button>
        <span className="mono" style={{ fontSize: 11, color: "var(--ink-2)" }}>1/2</span>
        <button className="icon-btn" style={{ width: 18, height: 18 }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="m12 19-7-8h14z"/></svg>
        </button>
      </div>
    </div>
  );
}

// ─── Query bar (bottom)
function DashboardQueryBar() {
  return (
    <div style={{
      borderTop: "1px solid var(--border)",
      background: "var(--rail)",
      flexShrink: 0,
    }}>
      {/* Tab strip */}
      <div style={{
        height: 36, padding: "0 16px",
        display: "flex", alignItems: "center", gap: 18,
      }}>
        <button className="icon-btn" style={{ width: 22, height: 22 }}>
          <IconChevDown size={11}/>
        </button>
        <span className="tab-underline active">Query 1</span>
        <button className="icon-btn" style={{ width: 22, height: 22 }}>
          <IconPlus size={12}/>
        </button>
        <div style={{ flex: 1 }} />

        {/* Mode toggle */}
        <div className="switch" style={{ marginRight: 8 }} />

        <div style={{
          display: "flex", alignItems: "center", overflow: "hidden",
          background: "var(--surface)", border: "1px solid var(--border)",
          borderRadius: 6,
        }}>
          {["Auto","PromQL","Custom SQL"].map(m => {
            const active = m === "PromQL";
            return (
              <button key={m} style={{
                border: "none",
                padding: "5px 14px",
                fontSize: 11, fontWeight: active ? 600 : 500,
                background: active ? "var(--accent)" : "transparent",
                color: active ? "white" : "var(--ink-2)",
                cursor: "pointer",
              }}>{m}</button>
            );
          })}
        </div>
      </div>
      {/* Query text */}
      <div style={{
        background: "var(--surface)",
        padding: "10px 16px",
        borderTop: "1px solid var(--border)",
        fontSize: 12.5, lineHeight: 1.5,
      }} className="mono">
        <span style={{ color: "var(--muted)", marginRight: 14, userSelect: "none" }}>1</span>
        <span className="sql-fn">sum</span>
        <span style={{ color: "var(--ink)" }}>(k8s_pod_memory_usage</span>
        <span style={{ color: "var(--ink)" }}>{"{"}</span>
        <span style={{ color: "var(--ink)" }}>k8s_cluster=</span>
        <span className="sql-str">"$k8s_cluster"</span>
        <span style={{ color: "var(--ink)" }}>{"}"}</span>
        <span style={{ color: "var(--ink)" }}>) </span>
        <span className="sql-kw">by </span>
        <span style={{ color: "var(--ink)" }}>(k8s_namespace_name)</span>
      </div>
    </div>
  );
}

// ─── Top header: title + name + time + actions
function DashboardHeader() {
  return (
    <div style={{
      height: 56, flexShrink: 0,
      display: "flex", alignItems: "center", gap: 16,
      padding: "0 16px",
      borderBottom: "1px solid var(--border)",
      background: "var(--canvas)",
    }}>
      <div style={{ fontSize: 18, fontWeight: 600, color: "var(--ink)", letterSpacing: "-0.01em", whiteSpace: "nowrap" }}>
        Edit Panel
      </div>

      <div style={{
        background: "var(--surface)", border: "1px solid var(--border)",
        borderRadius: 6, padding: "5px 12px", minWidth: 200,
      }}>
        <div style={{ fontSize: 9.5, color: "var(--muted)", fontWeight: 500, letterSpacing: ".03em", textTransform: "uppercase", whiteSpace: "nowrap" }}>
          Name of Panel*
        </div>
        <div style={{ fontSize: 13, color: "var(--ink)", fontWeight: 500 }}>
          Memory usage
        </div>
      </div>

      <button className="btn" style={{ whiteSpace: "nowrap" }}>Dashboard Tutorial</button>
      <button className="icon-btn bordered" title="Info"><IconInfo size={14}/></button>

      <button className="btn" style={{ height: 32, whiteSpace: "nowrap" }}>
        <IconClock size={13}/>
        <span>Past 15 Minutes</span>
        <IconChevDown size={12}/>
      </button>

      <div style={{ flex: 1 }} />

      <button className="btn" style={{ color: "var(--err)", fontWeight: 600 }}>Discard</button>
      <button className="btn" style={{ fontWeight: 600 }}>Save</button>
      <button className="btn-primary" style={{ padding: "0 18px" }}>Apply</button>
    </div>
  );
}

// ─── Cluster selector (above chart)
function ClusterSelect() {
  return (
    <div style={{
      background: "var(--surface)", border: "1px solid var(--border)",
      borderRadius: 6, padding: "5px 12px", minWidth: 280, maxWidth: 360,
      marginBottom: 12,
    }}>
      <div style={{ fontSize: 9.5, color: "var(--muted)", fontWeight: 500, letterSpacing: ".03em", textTransform: "uppercase", whiteSpace: "nowrap" }}>
        k8s_cluster
      </div>
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        fontSize: 13, color: "var(--ink)",
      }}>
        <span>touchtunes-prod</span><IconChevDown size={12} style={{ color: "var(--muted)" }}/>
      </div>
    </div>
  );
}

function DashboardScreen() {
  return (
    <div style={{
      flex: 1, display: "flex", flexDirection: "column", minHeight: 0,
      background: "var(--surface)",
    }}>
      <DashboardHeader />
      <div style={{ flex: 1, display: "flex", minHeight: 0 }}>
        <ChartRail />
        <FieldsPanel />
        <div style={{
          flex: 1, display: "flex", flexDirection: "column", minHeight: 0,
          borderRight: "1px solid var(--border)",
        }}>
          <div style={{
            flex: 1, minHeight: 0,
            display: "flex", padding: "16px 16px 12px",
          }}>
            <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
              <ClusterSelect />
              <div style={{ flex: 1, minHeight: 200 }}>
                <StackedAreaChart />
              </div>
            </div>
            <Legend />
          </div>
          <DashboardQueryBar />
        </div>

        {/* Config rail */}
        <div style={{
          width: 26, borderLeft: "1px solid var(--border)",
          background: "var(--rail)",
          color: "var(--ink)",
          display: "flex", alignItems: "flex-start", justifyContent: "center",
          paddingTop: 24, fontSize: 12, fontWeight: 600,
          writingMode: "vertical-rl", textOrientation: "mixed",
        }}>
          <span style={{ letterSpacing: ".05em" }}>↔ Config</span>
        </div>
      </div>
    </div>
  );
}

window.DashboardScreen = DashboardScreen;
