/* global React, window */
// Sidebar + top header + section header (eyebrows, titles).

const { useState, useRef, useEffect } = React;
const { Icon, Pill } = window;

function Sidebar({ screen, onNavigate, activeBrand, brands, onSwitchBrand }) {
  const t = window.useT();
  // M3 (K-2): «Iteration history» is a first-class sidebar entry under
  // Analytics — so iteration output lives where the discovery workflow lives.
  // Round 2: Inspo removed; Overview / Pulse / Iteration history / Image Ads
  // / AI Playground / Brands are all linked.
  const items = [
    { id: "analytics", label: t("Analytics", "数据分析"), group: true, children: [
      { id: "overview", label: t("Overview", "总览"), screen: "overview" },
      { id: "radar", label: t("Radar", "Radar"), screen: "radar" },
      { id: "iterations", label: t("Iteration history", "迭代历史"), screen: "history" },
      { id: "pulse", label: t("Pulse", "Pulse 告警"), screen: "pulse" },
    ]},
    { id: "creation", label: t("Creation", "创意生成"), group: true, children: [
      { id: "image-ads", label: t("Image Ads", "图片广告"), screen: "image-ads" },
      { id: "playground", label: t("AI Playground · Raya", "AI 实验场 · Raya"), screen: "playground", isHot: true },
    ]},
    { id: "brands", label: t("Brands", "品牌列表"), group: false, screen: "brands" },
  ];
  const isActive = (childScreen) => childScreen && screen === childScreen;
  const go = (s) => { if (onNavigate) onNavigate(s); };

  return (
    <aside style={{
      background: "var(--bg-deep)",
      borderRight: "1px solid var(--rule)",
      display: "flex", flexDirection: "column",
      padding: "16px 0",
      position: "relative",
    }}>
      <div style={{ padding: "4px 20px 20px", display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{
          width: 28, height: 28, borderRadius: 4,
          background: "var(--ink)", color: "var(--bg)",
          display: "grid", placeItems: "center",
          fontFamily: "Source Serif 4, Georgia, serif", fontWeight: 600, fontSize: 20, fontStyle: "italic",
        }}>A</div>
        <div>
          <div className="serif" style={{ fontSize: 19, lineHeight: 1 }}>Atria</div>
          <div className="label" style={{ fontSize: 9, marginTop: 2 }}>{t("Ad copilot", "广告副驾")}</div>
        </div>
      </div>

      <div className="label" style={{ padding: "12px 20px 6px" }}>{t("Brand", "品牌")}</div>
      <div style={{ padding: "0 12px 8px" }}>
        <BrandSwitcher
          activeBrand={activeBrand}
          brands={brands}
          onSwitch={onSwitchBrand}
          onSeeAll={() => go("brands")}
        />
      </div>

      <nav style={{ padding: "12px 8px", flex: 1, overflow: "auto" }}>
        {items.map(it => (
          <div key={it.id} style={{ marginBottom: 4 }}>
            {!it.group && (
              <button
                onClick={it.screen ? () => go(it.screen) : undefined}
                style={navItemStyle(isActive(it.screen))}
              >
                {isActive(it.screen) && <span style={{
                  position: "absolute", left: 0, top: 6, bottom: 6, width: 2,
                  background: "var(--accent)",
                }} />}
                <span>{it.label}</span>
              </button>
            )}
            {it.group && (
              <>
                <div style={{ padding: "10px 12px 4px", fontSize: 11, color: "var(--ink-3)", fontWeight: 500 }}>{it.label}</div>
                {it.children.map(c => {
                  const active = isActive(c.screen);
                  const clickable = !!c.screen;
                  return (
                    <button key={c.id}
                      data-tour={`nav-${c.id}`}
                      onClick={clickable ? () => go(c.screen) : undefined}
                      style={navItemStyle(active)}>
                      {active && <span style={{
                        position: "absolute", left: 0, top: 6, bottom: 6, width: 2,
                        background: "var(--accent)",
                      }} />}
                      <span style={{ paddingLeft: 14, display: "inline-flex", alignItems: "center", gap: 6 }}>
                        {c.label}
                        {c.isNew && (
                          <span className="mono" style={{
                            fontSize: 8,
                            padding: "1px 4px",
                            background: "var(--accent)",
                            color: "var(--accent-ink)",
                            borderRadius: 2,
                            letterSpacing: ".06em",
                            fontWeight: 600,
                          }}>NEW</span>
                        )}
                        {c.isHot && (
                          <span className="mono" style={{
                            fontSize: 8,
                            padding: "1px 5px",
                            background: "linear-gradient(135deg, #E03A0C 0%, #F0741C 100%)",
                            color: "#fff",
                            borderRadius: 2,
                            letterSpacing: ".06em",
                            fontWeight: 700,
                            boxShadow: "0 0 0 2px rgba(224, 58, 12, 0.18)",
                            animation: "atria-hot-pulse 2.2s ease-in-out infinite",
                          }}>HOT</span>
                        )}
                      </span>
                    </button>
                  );
                })}
              </>
            )}
          </div>
        ))}
      </nav>

      <UserProfile />
    </aside>
  );
}

// ===== Brand switcher (top of sidebar) =====
function BrandSwitcher({ activeBrand, brands, onSwitch, onSeeAll }) {
  const t = window.useT();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, [open]);

  const list = brands || [];
  const current = activeBrand || list[0] || { name: "Lipsum Brand", logo: "L", primary: "var(--accent)" };

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        className="btn"
        style={{ width: "100%", justifyContent: "space-between", background: "var(--card)" }}
        onClick={() => setOpen(o => !o)}
      >
        <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{
            width: 18, height: 18,
            background: current.primary || "var(--accent)",
            color: "var(--accent-ink)",
            display: "grid", placeItems: "center",
            fontFamily: "Source Serif 4, Georgia, serif",
            fontWeight: 600, fontSize: 13, borderRadius: 3,
          }}>{current.logo}</span>
          <span style={{ fontWeight: 500 }}>{current.name}</span>
        </span>
        <Icon name="chevDown" size={14} />
      </button>
      {open && list.length > 0 && (
        <div className="popover" style={{
          position: "absolute",
          top: "calc(100% + 4px)", left: 0, right: 0,
          padding: 6,
          zIndex: 80,
        }}>
          <div className="label" style={{ padding: "6px 8px 4px" }}>{t("Switch brand", "切换品牌")}</div>
          {list.map(b => {
            const isActive = b.id === current.id;
            return (
              <button
                key={b.id}
                onClick={() => { if (!isActive) onSwitch && onSwitch(b); setOpen(false); }}
                style={{
                  width: "100%",
                  padding: "8px 10px",
                  background: isActive ? "var(--bg-deep)" : "transparent",
                  border: "0",
                  cursor: isActive ? "default" : "pointer",
                  display: "flex", alignItems: "center", gap: 8,
                  borderRadius: 3,
                  textAlign: "left",
                  fontSize: 13,
                  fontWeight: isActive ? 500 : 400,
                  color: "var(--ink)",
                }}
                onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = "var(--bg-deep)"; }}
                onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = "transparent"; }}
              >
                <span style={{
                  width: 18, height: 18,
                  background: b.primary, color: "#fff",
                  display: "grid", placeItems: "center",
                  fontFamily: "Source Serif 4, Georgia, serif",
                  fontWeight: 600, fontSize: 12, borderRadius: 3,
                }}>{b.logo}</span>
                <span style={{ flex: 1 }}>{b.name}</span>
                {isActive && <Icon name="check" size={12} />}
              </button>
            );
          })}
          <div style={{ borderTop: "1px solid var(--rule)", marginTop: 4, paddingTop: 4 }}>
            <button
              onClick={() => { setOpen(false); onSeeAll && onSeeAll(); }}
              style={{
                width: "100%",
                padding: "7px 10px",
                background: "transparent", border: "0",
                cursor: "pointer", borderRadius: 3,
                textAlign: "left",
                fontSize: 12, color: "var(--ink-3)",
              }}
            >{t("Manage all brands →", "管理全部品牌 →")}</button>
          </div>
        </div>
      )}
    </div>
  );
}

// ===== User profile + theme switcher (bottom of sidebar) =====
function UserProfile() {
  const t = window.useT();
  const [open, setOpen] = useState(false);
  const [theme, setTheme] = useState(() => {
    if (typeof document === "undefined") return "warm";
    return document.documentElement.dataset.theme || "warm";
  });
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, [open]);

  function pickTheme(t) {
    setTheme(t);
    document.documentElement.dataset.theme = t;
    try { localStorage.setItem("atria-theme", t); } catch {}
  }

  return (
    <div ref={ref} style={{ position: "relative", padding: "12px 14px 12px 20px", borderTop: "1px solid var(--rule)" }}>
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          width: "100%",
          display: "flex", alignItems: "center", gap: 8,
          padding: 0,
          fontSize: 11, color: "var(--ink-3)",
          background: "transparent", border: "0",
          cursor: "pointer",
        }}
      >
        <div style={{
          width: 22, height: 22, borderRadius: "50%",
          background: "var(--ink)", color: "var(--bg)",
          display: "grid", placeItems: "center",
          fontSize: 10,
        }}>YN</div>
        <div style={{ flex: 1, textAlign: "left" }}>
          <div style={{ color: "var(--ink)", fontSize: 12 }}>{t("You", "你")}</div>
          <div style={{ fontSize: 11 }}>{t("Marketer · Lipsum", "营销 · Lipsum")}</div>
        </div>
        <Icon name="chevDown" size={12} />
      </button>
      {open && (
        <div className="popover" style={{
          position: "absolute",
          bottom: "calc(100% - 4px)", left: 8, right: 8,
          padding: 10,
          zIndex: 80,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <div style={{
              width: 36, height: 36, borderRadius: "50%",
              background: "var(--ink)", color: "var(--bg)",
              display: "grid", placeItems: "center",
              fontSize: 14, fontWeight: 600,
            }}>YN</div>
            <div>
              <div className="t-h3" style={{ fontSize: 14 }}>Hayden Liu</div>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{t("Marketer · Lipsum Brand", "营销 · Lipsum 品牌")}</div>
            </div>
          </div>
          <div style={{ borderTop: "1px solid var(--rule)", paddingTop: 10, marginBottom: 10 }}>
            <div className="label" style={{ marginBottom: 6 }}>{t("Theme", "主题")}</div>
            <div style={{ display: "flex", gap: 4 }}>
              {[
                { id: "warm", label: t("Warm", "暖色") },
                { id: "slate", label: t("Slate", "石板") },
                { id: "editorial", label: t("Editorial", "刊体") },
              ].map(opt => (
                <button
                  key={opt.id}
                  onClick={() => pickTheme(opt.id)}
                  style={{
                    flex: 1,
                    padding: "6px 4px",
                    border: theme === opt.id ? "1.5px solid var(--accent)" : "1px solid var(--rule)",
                    background: theme === opt.id ? "var(--accent-tint)" : "var(--card)",
                    borderRadius: 4,
                    cursor: "pointer",
                    fontSize: 11,
                    fontWeight: theme === opt.id ? 600 : 500,
                    color: theme === opt.id ? "var(--accent)" : "var(--ink-2)",
                  }}
                >{opt.label}</button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function navItemStyle(active) {
  return {
    position: "relative",
    width: "100%",
    textAlign: "left",
    padding: "7px 12px",
    fontSize: 13,
    borderRadius: 4,
    color: active ? "var(--ink)" : "var(--ink-2)",
    background: active ? "var(--card)" : "transparent",
    fontWeight: active ? 500 : 400,
    boxShadow: active ? "0 1px 0 var(--rule)" : "none",
    transition: "background .12s",
  };
}

function LangToggle() {
  const { useLang, setLang, t } = window;
  const lang = useLang();
  return (
    <div
      role="group"
      aria-label="Language"
      style={{
        display: "inline-flex",
        border: "1px solid var(--rule-strong)",
        borderRadius: 4,
        overflow: "hidden",
        fontFamily: "IBM Plex Mono, monospace",
        fontSize: 11,
        background: "var(--card)",
      }}
    >
      {[
        { id: "en", label: "EN" },
        { id: "zh", label: "中" },
      ].map((opt, i) => (
        <button
          key={opt.id}
          onClick={() => setLang(opt.id)}
          style={{
            padding: "4px 9px",
            background: lang === opt.id ? "var(--ink)" : "transparent",
            color: lang === opt.id ? "var(--bg)" : "var(--ink-2)",
            borderLeft: i > 0 ? "1px solid var(--rule)" : "0",
            fontWeight: lang === opt.id ? 600 : 500,
            cursor: lang === opt.id ? "default" : "pointer",
            letterSpacing: ".05em",
          }}
          title={opt.id === "en" ? "English" : "中文"}
        >{opt.label}</button>
      ))}
    </div>
  );
}

function TopBar({ runningCount, onOpenTasks, onOpenRationale, onOpenOnboarding, screenLabel, screenOnClick, breadcrumb, breadcrumbOnClick }) {
  const t = window.useT();
  // Style for a clickable breadcrumb segment (becomes a button-like span)
  const segBase = { fontSize: 13, transition: "color .12s, border-color .12s" };
  const segStatic = { ...segBase, color: "var(--ink-3)" };
  const segActive = { ...segBase, color: "var(--ink-2)", cursor: "pointer", borderBottom: "1px solid transparent" };
  return (
    <header style={{
      display: "flex", alignItems: "center",
      borderBottom: "1px solid var(--rule)",
      padding: "0 18px",
      background: "var(--bg)",
      gap: 16,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <span className="label">Atria</span>
        <Icon name="chev" size={10} />
        {screenOnClick ? (
          <button
            onClick={screenOnClick}
            title={t("Back to this screen", "返回这一页")}
            style={{
              ...segActive,
              fontWeight: 500,
              color: "var(--ink-2)",
              background: "transparent", border: "0", padding: 0,
              borderBottom: "1px solid var(--rule)",
            }}
            onMouseEnter={e => { e.currentTarget.style.color = "var(--accent)"; e.currentTarget.style.borderColor = "var(--accent)"; }}
            onMouseLeave={e => { e.currentTarget.style.color = "var(--ink-2)"; e.currentTarget.style.borderColor = "var(--rule)"; }}
          >{screenLabel || t("Radar", "Radar")}</button>
        ) : (
          <span style={{ fontSize: 13, fontWeight: 500 }}>{screenLabel || t("Radar", "Radar")}</span>
        )}
        {breadcrumb && (
          <>
            <Icon name="chev" size={10} />
            {breadcrumbOnClick ? (
              <button
                onClick={breadcrumbOnClick}
                title={t("Back", "返回")}
                style={{
                  ...segActive,
                  background: "transparent", border: "0", padding: 0,
                  borderBottom: "1px solid var(--rule)",
                }}
                onMouseEnter={e => { e.currentTarget.style.color = "var(--accent)"; e.currentTarget.style.borderColor = "var(--accent)"; }}
                onMouseLeave={e => { e.currentTarget.style.color = "var(--ink-2)"; e.currentTarget.style.borderColor = "var(--rule)"; }}
              >{breadcrumb}</button>
            ) : (
              <span style={segStatic}>{breadcrumb}</span>
            )}
          </>
        )}
      </div>

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

      <LangToggle />

      {/* Re-openable onboarding tutorial. First-time visitors see it
          automatically (localStorage flag); the «Guide» button lets anyone
          re-trigger the 6-step walkthrough explaining what Radar shows
          and how to use it. */}
      {onOpenOnboarding && (
        <button
          data-tour="guide-btn"
          className="btn ghost sm"
          onClick={onOpenOnboarding}
          title={t(
            "Reopen the 6-step new-user guide — what Radar shows, how grading works, what to do on each row, and where things live",
            "重新打开 6 步新手引导 —— Radar 是什么、评级怎么打、每一行该怎么动、各个模块在哪"
          )}
        >
          <Icon name="help" size={14} />
          <span>{t("Guide", "新手引导")}</span>
        </button>
      )}

      <button className="btn ghost sm" onClick={onOpenRationale} title={t("Quick rationale drawer (the condensed version, opens inside the prototype)", "原型内嵌的精简版设计说明(从右侧滑出小抽屉)")}>
        <Icon name="info" size={14} />
        <span>{t("Design rationale", "设计思路")}</span>
      </button>

      {/* External link to the full docs site (problem framing, solution, flow,
          usage walkthrough, iteration log, future). Opens in a new tab so the
          prototype state isn't lost. Targets «_top» when «_blank» is unavailable
          (some iframe sandboxes). */}
      <a
        href="/"
        target="_blank"
        rel="noopener noreferrer"
        className="btn ghost sm"
        title={t("Open the full documentation site in a new tab — problem framing, solution, flow, usage, iteration log, future directions", "在新标签页打开完整的文档站 —— 问题诊断 / 解决方案 / 流程 / 用户走查 / 迭代日志 / 未来探索")}
        style={{ textDecoration: "none" }}
      >
        <Icon name="arrow" size={14} />
        <span>{t("Docs", "文档")}</span>
      </a>

      <button className="btn" onClick={onOpenTasks} style={{ position: "relative" }}>
        <Icon name="inbox" size={14} />
        <span>{t("Tasks", "任务")}</span>
        {runningCount > 0 && (
          <span style={{
            display: "inline-grid", placeItems: "center",
            minWidth: 18, height: 18, padding: "0 5px",
            borderRadius: 999,
            background: "var(--accent)", color: "var(--accent-ink)",
            fontSize: 10, fontFamily: "IBM Plex Mono, monospace", fontWeight: 600,
            marginLeft: 2,
          }}>{runningCount}</span>
        )}
      </button>
    </header>
  );
}

Object.assign(window, { Sidebar, TopBar, LangToggle });
