// components.jsx — shared primitives (Button, Field, Card, etc.) + Sidebar + Topbar

function Button({ variant = "secondary", size = "md", icon, iconRight, children, className = "", ...rest }) {
  const sizeClass = size === "lg" ? "btn-lg" : size === "sm" ? "btn-sm" : "";
  return (
    <button className={`btn btn-${variant} ${sizeClass} ${className}`} {...rest}>
      {icon && <Icon name={icon} size={size === "lg" ? 16 : 14}/>}
      {children}
      {iconRight && <Icon name={iconRight} size={size === "lg" ? 16 : 14}/>}
    </button>
  );
}

function IconButton({ icon, size = "md", variant = "ghost", ...rest }) {
  const sizeClass = size === "lg" ? "btn-lg" : size === "sm" ? "btn-sm" : "";
  return (
    <button className={`btn btn-${variant} btn-icon ${sizeClass}`} {...rest}>
      <Icon name={icon} size={size === "lg" ? 16 : 14}/>
    </button>
  );
}

function Field({ label, hint, icon, error, children, ...rest }) {
  return (
    <div>
      {label && <label className="label">{label}</label>}
      <div className="field" style={error ? { borderColor: "var(--danger)" } : undefined}>
        {icon && <Icon name={icon} size={15} style={{ color: "var(--fg-faint)", marginRight: 8 }}/>}
        {children || <input {...rest}/>}
      </div>
      {hint && !error && <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 6 }}>{hint}</div>}
      {error && <div style={{ fontSize: 12, color: "var(--danger)", marginTop: 6 }}>{error}</div>}
    </div>
  );
}

function Badge({ variant = "default", icon, children }) {
  return (
    <span className={`badge ${variant !== "default" ? `badge-${variant}` : ""}`}>
      {icon && <Icon name={icon} size={11}/>}
      {children}
    </span>
  );
}

function Kbd({ children }) { return <kbd className="kbd">{children}</kbd>; }

function Section({ title, eyebrow, sub, align = "left", children }) {
  return (
    <div className="col gap-3" style={{ alignItems: align === "center" ? "center" : "flex-start", textAlign: align }}>
      {eyebrow && <span className="eyebrow">{eyebrow}</span>}
      {title && <h2 style={{ fontSize: "clamp(28px, 3vw, 40px)", lineHeight: 1.1, letterSpacing: "-0.025em" }}>{title}</h2>}
      {sub && <p style={{ color: "var(--fg-muted)", fontSize: 16, maxWidth: 640, lineHeight: 1.55 }}>{sub}</p>}
      {children}
    </div>
  );
}

// ─────── Sidebar (app shell) ───────

function Sidebar({ route, navigate, onLogout, open, onClose, scriptCount }) {
  const { t } = useI18n();
  const item = (key, icon, label, count) => (
    <div
      className={`sb-item ${route === key ? "active" : ""}`}
      onClick={() => { navigate(key); if (onClose) onClose(); }}
    >
      <Icon name={icon} size={16} className="sb-icon"/>
      <span>{label}</span>
      {count && <span className="sb-count">{count}</span>}
    </div>
  );
  return (
    <aside className={`sidebar scroll ${open ? "open" : ""}`}>
      <div className="sb-brand">
        <Logo/>
      </div>

      <div className="sb-section">{t("sidebar.atelier")}</div>
      {item("app.scripts", "scripts", t("sidebar.scripts"))}
      {item("app.history", "history", t("sidebar.history"), scriptCount > 0 ? String(scriptCount) : null)}

      <div className="sb-section">{t("sidebar.community")}</div>
      {item("app.community", "users", t("sidebar.explore"))}
      {item("app.favorites", "star", t("sidebar.favorites"))}

      <div className="sb-section">{t("sidebar.suite")}</div>
      <a
        href="https://fmblueprint.app"
        target="_blank"
        rel="noopener noreferrer"
        className="sb-item"
        style={{ textDecoration: "none" }}
      >
        <Icon name="bookOpen" size={16} className="sb-icon"/>
        <span>FMBluePrint</span>
        <Icon name="externalLink" size={11} style={{ marginLeft: "auto", color: "var(--fg-faint)" }}/>
      </a>

      <div className="sb-section">{t("sidebar.account")}</div>
      {item("app.profile", "user", t("sidebar.profile"))}
      {item("app.settings","settings", t("sidebar.settings"))}

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

      <div style={{ borderTop: "1px solid var(--border)", paddingTop: 12, marginTop: 12 }}>
        <div
          className="sb-item"
          style={{ background: "var(--bg-elevated)", border: "1px solid var(--border)" }}
          onClick={() => navigate("market.home")}
        >
          <Icon name="puzzle" size={16} className="sb-icon" style={{ color: "var(--accent)" }}/>
          <div className="col" style={{ gap: 0, lineHeight: 1.2 }}>
            <span style={{ fontSize: 12, fontWeight: 600 }}>{t("sidebar.extension")}</span>
            <span style={{ fontSize: 11, color: "var(--fg-faint)" }}>{t("sidebar.extension.sub")}</span>
          </div>
        </div>
        <a
          href="/downloads/FMAutoScriptPlugin.zip"
          download
          className="sb-item"
          style={{ background: "var(--bg-elevated)", border: "1px solid var(--border)", marginTop: 4, textDecoration: "none" }}
        >
          <Icon name="shield" size={16} className="sb-icon" style={{ color: "var(--accent)" }}/>
          <div className="col" style={{ gap: 0, lineHeight: 1.2 }}>
            <span style={{ fontSize: 12, fontWeight: 600 }}>{t("sidebar.plugin")}</span>
            <span style={{ fontSize: 11, color: "var(--fg-faint)" }}>{t("sidebar.plugin.sub")}</span>
          </div>
          <Icon name="download" size={12} style={{ marginLeft: "auto", color: "var(--fg-faint)" }}/>
        </a>
        <div className="sb-item" onClick={() => { onLogout(); if (onClose) onClose(); }} style={{ marginTop: 4 }}>
          <Icon name="logout" size={16} className="sb-icon"/>
          <span>{t("sidebar.logout")}</span>
        </div>
      </div>
    </aside>
  );
}

function Topbar({ title, subtitle, actions, breadcrumb, onMenuToggle }) {
  return (
    <header className="topbar">
      {onMenuToggle && (
        <button className="mobile-menu-btn" onClick={onMenuToggle}>
          <Icon name="menu" size={20}/>
        </button>
      )}
      <div className="row gap-3" style={{ flex: 1, minWidth: 0 }}>
        {breadcrumb && (
          <div className="row gap-2" style={{ color: "var(--fg-muted)", fontSize: 13 }}>
            {breadcrumb.map((b, i) => (
              <React.Fragment key={i}>
                {i > 0 && <Icon name="chevronRight" size={12} style={{ color: "var(--fg-faint)" }}/>}
                <span style={{ color: i === breadcrumb.length - 1 ? "var(--fg)" : "var(--fg-muted)", fontWeight: i === breadcrumb.length - 1 ? 500 : 400 }}>
                  {b}
                </span>
              </React.Fragment>
            ))}
          </div>
        )}
        {title && (
          <div className="col" style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 600, fontSize: 14 }}>{title}</div>
            {subtitle && <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>{subtitle}</div>}
          </div>
        )}
      </div>
      <div className="row gap-2">
        {actions}
      </div>
    </header>
  );
}

// Companion bar (used in app pages)
const COMPANION_CMD = "curl -fsSL https://www.fmautoscript.app/downloads/FMAutoScriptCompanion -o /tmp/FMAutoScriptCompanion && chmod +x /tmp/FMAutoScriptCompanion && /tmp/FMAutoScriptCompanion";

function CompanionBar({ connected, onInstall }) {
  const { t } = useI18n();
  const [copied, setCopied] = React.useState(false);
  const copy = async () => {
    try { await navigator.clipboard.writeText(COMPANION_CMD); setCopied(true); setTimeout(() => setCopied(false), 2000); }
    catch (e) { /* ignore */ }
  };

  if (connected) {
    return (
      <div className="companion-bar ok">
        <span className="dot"/>
        <span style={{ color: "var(--success)", fontWeight: 500 }}>{t("companion.connected")}</span>
        <span style={{ color: "var(--fg-muted)" }}>{t("companion.ready")}</span>
        <span style={{ flex: 1 }}/>
        <span className="mono" style={{ fontSize: 11, color: "var(--fg-faint)" }}>localhost:27184</span>
      </div>
    );
  }

  return (
    <div style={{ background: "var(--surface)", borderBottom: "1px solid var(--border)", padding: "10px 16px" }}>
      <div className="row gap-2" style={{ marginBottom: 8 }}>
        <span style={{ width: 7, height: 7, borderRadius: 999, background: "var(--danger)", boxShadow: "0 0 0 3px color-mix(in oklch, var(--danger) 30%, transparent)", flexShrink: 0 }}/>
        <span style={{ fontSize: 12.5, fontWeight: 500 }}>{t("companion.disconnected")}</span>
        <span style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>{t("companion.instructions")}</span>
      </div>
      <div className="row gap-2" style={{
        background: "var(--code-bg)",
        color: "var(--code-fg)",
        borderRadius: "var(--radius-sm)",
        padding: "6px 6px 6px 12px",
        fontFamily: "var(--font-mono)",
        fontSize: 12,
        border: "1px solid oklch(0.25 0.01 270)",
      }}>
        <code style={{ flex: 1, overflow: "auto", whiteSpace: "nowrap", userSelect: "all" }}>
          <span style={{ color: "oklch(0.78 0.13 145)" }}>$</span> {COMPANION_CMD}
        </code>
        <button
          onClick={copy}
          className="row gap-1"
          style={{
            padding: "4px 10px",
            background: copied ? "var(--success)" : "oklch(0.25 0.01 270)",
            color: copied ? "white" : "var(--code-fg)",
            border: "1px solid " + (copied ? "var(--success)" : "oklch(0.32 0.01 270)"),
            borderRadius: "var(--radius-xs)",
            fontSize: 11.5,
            fontWeight: 500,
            cursor: "pointer",
            flexShrink: 0,
            transition: "all 0.15s",
          }}
        >
          <Icon name={copied ? "check" : "copy"} size={12}/>
          {copied ? t("companion.copied") : t("companion.copy")}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { Button, IconButton, Field, Badge, Kbd, Section, Sidebar, Topbar, CompanionBar });
