// Home → O2 Assistant
// Empty state → auto-typed first prompt → scripted assistant answer → inline interactive dashboard
const { useState: useStateH, useEffect: useEffectH, useRef: useRefH } = React;
const { IconSearch: IconSearchH, IconPlus: IconPlusH } = window.Icons;
const K8sHostDashboardH = window.K8sHostDashboard;

const CHAT_HISTORY = [
  "Build K8s Host Metrics Dashboard — CPU, Memory & Disk",
  "Investigate OTel Demo Cart Service Errors",
  "Check OTel Demo Health and Create Alert",
  "Build Nginx Log Dashboard With Request Rate",
  "Analyze Frontend Service Request Latency",
  "Visualize Purchase Success vs Failure Rate",
  "Investigate RCA for Incident 387",
];

// Scripted demo run — exactly mirrors the K8s dashboard build flow
const ASSISTANT_PROMPT = "build a dashboard for K8s host metrics — CPU, memory and disk per node.";
const ASSISTANT_STEPS = [
  { kind: "tool", label: "Loading skill", suffix: "k8s_dashboards" },
  { kind: "tool", label: "Listing metric streams", suffix: "(Found 24)" },
  { kind: "text", body: <>Found <span className="mono" style={{ background: "var(--rail)", padding: "1px 4px", borderRadius: 3 }}>k8s_metrics</span> stream. Fetching schema to build accurate PromQL.</> },
  { kind: "tool", label: "Fetched stream schema",   suffix: "29 fields" },
  { kind: "text", body: <>
    <div style={{ marginBottom: 6 }}>Schema retrieved. Building 4 panels:</div>
    <ul style={{ paddingLeft: 18, margin: 0, lineHeight: 1.85 }}>
      <li><strong>CPU Usage per Node</strong> — <span className="mono">sum by (host) (rate(container_cpu_usage_seconds_total[5m]))</span></li>
      <li><strong>CPU User &amp; System Modes</strong> — <span className="mono">rate(node_cpu_seconds_total[5m])</span></li>
      <li><strong>CPU Idle Rate</strong> — <span className="mono">rate(node_cpu_idle_seconds[5m])</span></li>
      <li><strong>CPU Snapshot per Node</strong> — <span className="mono">container_cpu_usage</span></li>
    </ul>
  </> },
  { kind: "tool", label: "Validating PromQL queries", suffix: "4/4 passed" },
  { kind: "tool", label: "Creating dashboard panel",  suffix: "CPU Usage per Node" },
  { kind: "tool", label: "Creating dashboard panel",  suffix: "User & System Modes" },
  { kind: "tool", label: "Creating dashboard panel",  suffix: "Idle Rate" },
  { kind: "tool", label: "Creating dashboard panel",  suffix: "Latest Snapshot" },
  { kind: "text", body: <>Dashboard <strong>K8s Host Metrics — CPU, Memory &amp; Disk per Node</strong> created. Opening below.</> },
  { kind: "dashboard" },
];

function AssistantLogo({ size = 64 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: "50%",
      background: "conic-gradient(from 0deg, #5C5DBC 0%, #2E9D63 25%, #E08E3C 50%, #DC4040 75%, #5C5DBC 100%)",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      boxShadow: "inset 0 0 0 5px var(--surface)",
    }}>
      <div style={{
        width: size * 0.42, height: size * 0.42, borderRadius: "50%",
        background: "var(--surface)",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        fontSize: size * 0.20, fontWeight: 700, color: "var(--ink)",
      }}>AI</div>
    </div>
  );
}

function HomeTabs({ tab, onTab }) {
  const Tab = ({ k, label }) => (
    <button onClick={() => onTab(k)} className={`tab-underline ${tab === k ? "active" : ""}`}
            style={{
              background: "none", border: "none", padding: "12px 0",
              cursor: "pointer", fontSize: 14, fontWeight: 600,
            }}>
      {label}
    </button>
  );
  return (
    <div style={{
      display: "flex", gap: 36, padding: "0 24px",
      borderBottom: "1px solid var(--border)",
      background: "var(--canvas)", flexShrink: 0,
    }}>
      <Tab k="assistant" label="O2 Assistant" />
      <Tab k="overview"  label="Overview" />
      <Tab k="usage"     label="Usage" />
    </div>
  );
}

function ChatSidebar({ activeIdx, onPick, onNew, started }) {
  return (
    <aside style={{
      width: 260, flexShrink: 0,
      borderRight: "1px solid var(--border)",
      background: "var(--surface)",
      display: "flex", flexDirection: "column", minHeight: 0,
    }}>
      <div style={{
        padding: "12px 16px 10px",
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <span style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)" }}>Chats</span>
        <button className="icon-btn" onClick={onNew} title="New chat"
                style={{ width: 26, height: 26, color: "var(--accent-fg)" }}>
          <IconPlusH size={14}/>
        </button>
      </div>
      <div style={{ padding: "0 12px 8px" }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 8,
          padding: "6px 10px",
          background: "var(--canvas)", border: "1px solid var(--border)", borderRadius: 6,
        }}>
          <IconSearchH size={12} style={{ color: "var(--muted)" }} />
          <input placeholder="Search" style={{
            border: "none", outline: "none", background: "transparent",
            fontSize: 12, color: "var(--ink)", flex: 1, fontFamily: "inherit",
          }}/>
        </div>
      </div>
      <div style={{ flex: 1, overflowY: "auto", padding: "4px 8px" }}>
        {!started ? (
          <div style={{
            textAlign: "center", padding: "24px 12px",
            fontSize: 12, color: "var(--muted-2)",
          }}>
            No chat history
          </div>
        ) : (
          CHAT_HISTORY.map((title, i) => (
            <div key={i} onClick={() => onPick(i)}
                 style={{
                   padding: "8px 10px", marginBottom: 2,
                   borderRadius: 4,
                   fontSize: 12, color: "var(--ink-2)",
                   background: activeIdx === i ? "var(--accent-bg)" : "transparent",
                   cursor: "pointer",
                   overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                 }}
                 onMouseEnter={e => { if (activeIdx !== i) e.currentTarget.style.background = "var(--rail)"; }}
                 onMouseLeave={e => { if (activeIdx !== i) e.currentTarget.style.background = "transparent"; }}>
              {title}
            </div>
          ))
        )}
      </div>
    </aside>
  );
}

function StepBubble({ step, done, inline = false }) {
  if (step.kind === "tool") {
    return (
      <div style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: "10px 14px", marginBottom: 10,
        background: done ? "rgba(46,157,99,.06)" : "var(--canvas)",
        border: "1px solid " + (done ? "rgba(46,157,99,.22)" : "var(--border)"),
        borderRadius: 6,
        fontSize: 13, color: "var(--ink)",
      }}>
        {done ? (
          <svg width="16" height="16" viewBox="0 0 24 24" fill="var(--ok)">
            <circle cx="12" cy="12" r="9" fill="rgba(46,157,99,.18)"/>
            <path d="M8 12.5l3 3 5-6" stroke="var(--ok)" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        ) : (
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--accent-fg)" strokeWidth="2.4"
               style={{ animation: "spin 1s linear infinite" }}>
            <path d="M21 12a9 9 0 1 1-3-6.7"/>
          </svg>
        )}
        <span>{step.label}</span>
        {step.suffix && (
          <span className="mono pill" style={{
            background: "var(--rail)", color: "var(--ink-2)",
            border: "1px solid var(--border)",
            padding: "2px 8px",
          }}>{step.suffix}</span>
        )}
      </div>
    );
  }
  if (step.kind === "dashboard") {
    const Dash = window.K8sHostDashboard;
    return (
      <div style={{ margin: "12px 0 8px" }}>
        {Dash ? <Dash inline={true}/> : <div style={{ padding: 20, color: "var(--muted)" }}>Loading dashboard…</div>}
        <div style={{ marginTop: 8, fontSize: 12 }}>
          <a style={{ color: "var(--accent-fg)", textDecoration: "underline", cursor: "pointer" }}>
            Open in Dashboards → K8s Host Metrics
          </a>
        </div>
      </div>
    );
  }
  return (
    <div style={{
      fontSize: 13, lineHeight: 1.65, color: "var(--ink)",
      padding: "4px 0 14px",
    }}>
      {step.body}
    </div>
  );
}

function HomeAssistant() {
  // started: has user (or auto-typer) sent a prompt yet?
  const [started, setStarted]   = useStateH(false);
  const [composer, setComposer] = useStateH("");
  const [submitted, setSubmitted] = useStateH("");
  const [shown, setShown]       = useStateH(0);
  const [activeIdx, setActiveIdx] = useStateH(null);
  const scrollRef = useRefH(null);
  const typedRef = useRefH(false);

  // ─── auto-typer kicks in 600ms after mount
  useEffectH(() => {
    if (typedRef.current) return;
    typedRef.current = true;
    let i = 0;
    const start = setTimeout(function tick() {
      i++;
      setComposer(ASSISTANT_PROMPT.slice(0, i));
      if (i < ASSISTANT_PROMPT.length) {
        setTimeout(tick, 14 + Math.random() * 18);
      } else {
        setTimeout(() => {
          setSubmitted(ASSISTANT_PROMPT);
          setComposer("");
          setStarted(true);
          setActiveIdx(0);
        }, 400);
      }
    }, 600);
    return () => clearTimeout(start);
  }, []);

  // ─── reveal scripted steps once started
  useEffectH(() => {
    if (!started) return;
    if (shown < ASSISTANT_STEPS.length) {
      const delay = ASSISTANT_STEPS[shown]?.kind === "dashboard" ? 300 : 280;
      const t = setTimeout(() => setShown(s => s + 1), delay);
      return () => clearTimeout(t);
    }
  }, [started, shown]);

  useEffectH(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [shown, submitted]);

  function newChat() {
    setStarted(false); setSubmitted(""); setShown(0); setComposer("");
    setActiveIdx(null); typedRef.current = false;
    // restart auto-typer
    setTimeout(() => { typedRef.current = false; }, 50);
  }

  function send() {
    if (!composer.trim()) return;
    setSubmitted(composer);
    setStarted(true);
    setShown(0);
    setComposer("");
    setActiveIdx(0);
  }

  return (
    <div style={{ flex: 1, display: "flex", minHeight: 0 }}>
      <ChatSidebar activeIdx={activeIdx} onPick={() => {}} onNew={newChat} started={started}/>

      <div style={{ flex: 1, display: "flex", flexDirection: "column", minHeight: 0, background: "var(--surface)" }}>
        <div ref={scrollRef} style={{ flex: 1, overflowY: "auto", padding: started ? "20px 32px 4px" : 0, position: "relative" }}>
          {!started ? (
            <div style={{
              position: "absolute", inset: 0,
              display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
              gap: 14, color: "var(--muted)",
            }}>
              <AssistantLogo size={68}/>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 19, fontWeight: 600, color: "var(--ink)" }}>O2 Assistant</span>
                <span className="mono pill" style={{
                  background: "var(--accent-bg)", color: "var(--accent-fg)",
                  border: "1px solid var(--accent-line)", padding: "2px 8px",
                }}>BETA</span>
              </div>
            </div>
          ) : (
            <>
              {/* User prompt bubble */}
              <div style={{
                display: "flex", alignItems: "flex-start", gap: 10,
                marginBottom: 22,
                padding: "12px 16px",
                background: "var(--accent-bg)",
                border: "1px solid var(--accent-line)",
                borderRadius: 8,
              }}>
                <div style={{
                  width: 26, height: 26, borderRadius: "50%",
                  background: "linear-gradient(135deg, #9C5DE0, #5C5DBC)",
                  flexShrink: 0,
                }}/>
                <div style={{ fontSize: 13, color: "var(--ink)", lineHeight: 1.5 }}>
                  {submitted}
                </div>
              </div>

              {/* Assistant steps */}
              {ASSISTANT_STEPS.slice(0, shown).map((s, i) => (
                <StepBubble key={i} step={s} done={i < shown - 1}/>
              ))}
              {shown < ASSISTANT_STEPS.length && (
                <div style={{
                  display: "flex", alignItems: "center", gap: 10,
                  padding: "10px 14px",
                  background: "var(--canvas)", border: "1px solid var(--border)",
                  borderRadius: 6,
                  fontSize: 13, color: "var(--muted)",
                }}>
                  <span style={{ display: "inline-flex", gap: 3 }}>
                    {[0, 1, 2].map(j => (
                      <span key={j} style={{
                        width: 5, height: 5, borderRadius: "50%",
                        background: "var(--muted)",
                        animation: `pulseDot 1.2s ease-in-out ${j * 0.15}s infinite`,
                      }}/>
                    ))}
                  </span>
                  Processing...
                </div>
              )}
            </>
          )}
        </div>

        {/* Composer */}
        <div style={{
          padding: "12px 24px 20px",
          background: "var(--surface)",
        }}>
          <div style={{
            display: "flex", alignItems: "flex-end", gap: 10,
            padding: "12px 16px",
            background: "var(--surface)", border: "1px solid var(--border-2)",
            borderRadius: 12,
            boxShadow: "var(--shadow-1)",
          }}>
            <textarea
              placeholder="Write your prompt"
              value={composer}
              onChange={e => setComposer(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
              rows={1}
              style={{
                border: "none", outline: "none", background: "transparent",
                fontSize: 13, color: "var(--ink)", flex: 1,
                fontFamily: "inherit", resize: "none",
                lineHeight: 1.5, padding: "2px 0",
              }}/>
            <button onClick={send} className="btn-primary" style={{ height: 32 }} disabled={!composer.trim()}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l14-7-7 14-2-5z"/></svg>
              Send
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function HomeOverview() {
  const kpis = [
    { label: "Ingestion / sec",  value: "112.7K", delta: "+4.2%", up: true },
    { label: "Active streams",   value: "39",     delta: "+2",    up: true },
    { label: "Storage used",     value: "2.4 TB", delta: "+3.1%", up: true },
    { label: "Open incidents",   value: "1",      delta: "+1",    up: true, crit: true },
    { label: "Active dashboards",value: "12",     delta: "0",     up: false },
    { label: "Pipelines",        value: "8",      delta: "+1",    up: true },
  ];
  return (
    <div style={{ flex: 1, overflowY: "auto", padding: 24, background: "var(--bg)" }}>
      <div style={{ fontSize: 14, color: "var(--muted)", marginBottom: 14 }}>Last 24 hours</div>
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))",
        gap: 14, marginBottom: 24,
      }}>
        {kpis.map((k, i) => (
          <div key={i} style={{
            padding: 16,
            background: "var(--surface)", border: "1px solid var(--border)",
            borderRadius: 8, boxShadow: "var(--shadow-1)",
          }}>
            <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 6 }}>{k.label}</div>
            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
              <span className="mono" style={{ fontSize: 22, fontWeight: 600, color: k.crit ? "var(--err)" : "var(--ink)" }}>
                {k.value}
              </span>
              <span className="mono pill" style={{
                background: k.up ? "rgba(46,157,99,.10)" : "var(--canvas)",
                color: k.up ? "var(--ok)" : "var(--muted)",
                border: "1px solid var(--border)",
              }}>{k.up ? "▲" : "▼"} {k.delta}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function HomeUsage() {
  return (
    <div style={{ flex: 1, overflowY: "auto", padding: 24, background: "var(--bg)" }}>
      <div style={{
        background: "var(--surface)", border: "1px solid var(--border)",
        borderRadius: 8, padding: 24, maxWidth: 720,
      }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)", marginBottom: 6 }}>Usage this month</div>
        <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 16 }}>Billed monthly · Enterprise edition</div>
        {[
          { label: "Logs ingested",   used: 18.4, cap: 50,   unit: "TB" },
          { label: "Metrics samples", used: 482,  cap: 1000, unit: "M" },
          { label: "Traces ingested", used: 6.2,  cap: 20,   unit: "TB" },
          { label: "Storage retained",used: 32,   cap: 100,  unit: "TB" },
        ].map((u, i) => {
          const pct = (u.used / u.cap) * 100;
          return (
            <div key={i} style={{ marginBottom: 16 }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                <span style={{ fontSize: 13, color: "var(--ink)", fontWeight: 500 }}>{u.label}</span>
                <span className="mono" style={{ fontSize: 12, color: "var(--ink-2)" }}>
                  {u.used} {u.unit} <span style={{ color: "var(--muted)" }}>/ {u.cap} {u.unit}</span>
                </span>
              </div>
              <div style={{ height: 8, background: "var(--rail)", borderRadius: 4, overflow: "hidden" }}>
                <div style={{
                  width: `${pct}%`, height: "100%",
                  background: pct > 80 ? "var(--err)" : pct > 60 ? "var(--warn)" : "var(--accent)",
                }}/>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function HomeScreen() {
  const [tab, setTab] = useStateH("assistant");
  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", minHeight: 0, background: "var(--bg)" }}>
      <HomeTabs tab={tab} onTab={setTab} />
      {tab === "assistant" && <HomeAssistant/>}
      {tab === "overview"  && <HomeOverview/>}
      {tab === "usage"     && <HomeUsage/>}
    </div>
  );
}

(function () {
  if (document.getElementById("home-anim")) return;
  const s = document.createElement("style");
  s.id = "home-anim";
  s.textContent = `
    @keyframes pulseDot { 0%,80%,100% { opacity: .3; transform: scale(.7); } 40% { opacity: 1; transform: scale(1); } }
  `;
  document.head.appendChild(s);
})();

window.HomeScreen = HomeScreen;
