/* Icons + small UI primitives + sidebar + topbar */

const Icon = ({ name, size = 16, ...rest }) => {
  const s = { width: size, height: size, strokeWidth: 1.6, ...rest.style };
  const common = {
    width: size,
    height: size,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth: 1.6,
    strokeLinecap: "round",
    strokeLinejoin: "round",
    ...rest,
    style: s,
  };
  switch (name) {
    case "play":
      return (
        <svg {...common}>
          <polygon
            points="6 4 20 12 6 20 6 4"
            fill="currentColor"
            stroke="none"
          />
        </svg>
      );
    case "plus":
      return (
        <svg {...common}>
          <path d="M12 5v14M5 12h14" />
        </svg>
      );
    case "list":
      return (
        <svg {...common}>
          <path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01" />
        </svg>
      );
    case "settings":
      return (
        <svg {...common}>
          <circle cx="12" cy="12" r="3" />
          <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
        </svg>
      );
    case "search":
      return (
        <svg {...common}>
          <circle cx="11" cy="11" r="7" />
          <path d="m20 20-3.5-3.5" />
        </svg>
      );
    case "arrow-left":
      return (
        <svg {...common}>
          <path d="M19 12H5M12 19l-7-7 7-7" />
        </svg>
      );
    case "arrow-right":
      return (
        <svg {...common}>
          <path d="M5 12h14M12 5l7 7-7 7" />
        </svg>
      );
    case "x":
      return (
        <svg {...common}>
          <path d="M18 6 6 18M6 6l12 12" />
        </svg>
      );
    case "check":
      return (
        <svg {...common}>
          <path d="M20 6 9 17l-5-5" />
        </svg>
      );
    case "download":
      return (
        <svg {...common}>
          <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3" />
        </svg>
      );
    case "trash":
      return (
        <svg {...common}>
          <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
        </svg>
      );
    case "youtube":
      return (
        <svg {...common}>
          <path d="M22.54 6.42a2.78 2.78 0 0 0-1.94-2C18.88 4 12 4 12 4s-6.88 0-8.6.46a2.78 2.78 0 0 0-1.94 2A29 29 0 0 0 1 11.75a29 29 0 0 0 .46 5.33A2.78 2.78 0 0 0 3.4 19c1.72.46 8.6.46 8.6.46s6.88 0 8.6-.46a2.78 2.78 0 0 0 1.94-2 29 29 0 0 0 .46-5.25 29 29 0 0 0-.46-5.33z" />
          <polygon
            points="9.75 15.02 15.5 11.75 9.75 8.48 9.75 15.02"
            fill="currentColor"
            stroke="none"
          />
        </svg>
      );
    case "sparkle":
      return (
        <svg {...common}>
          <path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1" />
        </svg>
      );
    case "menu":
      return (
        <svg {...common}>
          <path d="M3 6h18M3 12h18M3 18h18" />
        </svg>
      );
    case "chevron-down":
      return (
        <svg {...common}>
          <path d="m6 9 6 6 6-6" />
        </svg>
      );
    case "chevron-up":
      return (
        <svg {...common}>
          <path d="m18 15-6-6-6 6" />
        </svg>
      );
    case "chevron-right":
      return (
        <svg {...common}>
          <path d="m9 18 6-6-6-6" />
        </svg>
      );
    case "chevron-left":
      return (
        <svg {...common}>
          <path d="m15 18-6-6 6-6" />
        </svg>
      );
    case "eye":
      return (
        <svg {...common}>
          <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" />
          <circle cx="12" cy="12" r="3" />
        </svg>
      );
    case "thumbs-up":
      return (
        <svg {...common}>
          <path d="M7 10v12M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H7" />
        </svg>
      );
    case "comment":
      return (
        <svg {...common}>
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
        </svg>
      );
    case "calendar":
      return (
        <svg {...common}>
          <rect x="3" y="4" width="18" height="18" rx="2" />
          <path d="M16 2v4M8 2v4M3 10h18" />
        </svg>
      );
    case "filter":
      return (
        <svg {...common}>
          <path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z" />
        </svg>
      );
    case "sort":
      return (
        <svg {...common}>
          <path d="M3 6h18M6 12h12M9 18h6" />
        </svg>
      );
    case "logout":
      return (
        <svg {...common}>
          <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" />
        </svg>
      );
    case "sun":
      return (
        <svg {...common}>
          <circle cx="12" cy="12" r="4" />
          <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
        </svg>
      );
    case "moon":
      return (
        <svg {...common}>
          <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
        </svg>
      );
    case "spinner":
      return (
        <svg {...common} style={{ ...s, animation: "spin 1s linear infinite" }}>
          <path d="M21 12a9 9 0 1 1-6.22-8.56" />
        </svg>
      );
    default:
      return (
        <svg {...common}>
          <circle cx="12" cy="12" r="9" />
        </svg>
      );
  }
};

const Logo = ({ collapsed, onClick }) => {
  const isRU = window.PRODUCT_MODE === "ru";
  const isEN = window.PRODUCT_MODE === "en";
  return (
    <div
      className="sidebar-brand"
      onClick={onClick}
      style={{ cursor: "pointer" }}
    >
      {!collapsed && isRU && (
        <span
          style={{
            fontFamily: "'Playfair Display', serif",
            fontWeight: 900,
            fontStyle: "italic",
            fontSize: 22,
            letterSpacing: "-0.01em",
            color: "var(--fg)",
            lineHeight: 1,
          }}
        >
          ЮНА
        </span>
      )}
      {!collapsed && isEN && (
        <span
          style={{
            fontFamily: "'DM Serif Display', serif",
            fontWeight: 400,
            fontStyle: "normal",
            fontSize: 22,
            letterSpacing: "-0.02em",
            color: "var(--fg)",
            lineHeight: 1,
          }}
        >
          Younalyse
        </span>
      )}
      {!collapsed && !isRU && !isEN && (
        <span
          style={{
            fontFamily: "'DM Serif Display', 'Playfair Display', serif",
            fontWeight: 400,
            fontSize: 22,
            letterSpacing: "-0.02em",
            color: "var(--fg)",
            lineHeight: 1,
          }}
        >
          {window.T?.productName || "Youna"}
        </span>
      )}
      {collapsed && (
        <span
          style={{
            fontFamily: isRU
              ? "'Playfair Display', serif"
              : "'DM Serif Display', serif",
            fontWeight: isRU ? 900 : 400,
            fontStyle: isRU ? "italic" : "normal",
            fontSize: 18,
            color: "var(--fg)",
          }}
        >
          {isRU ? "Ю" : "Y"}
        </span>
      )}
    </div>
  );
};

const Sidebar = ({
  page,
  setPage,
  collapsed,
  onLogout,
  onLogoClick,
  userProfile,
  onThemeToggle,
  isDark,
}) => {
  const T = window.T || {};
  const items = [
    { id: "analysis", name: T.navNewAnalysis || "New Analysis", icon: "plus" },
    { id: "results", name: T.navResults || "Results", icon: "list" },
    { id: "keywords", name: T.navKeywords || "Keywords", icon: "search" },
    { id: "analytics", name: T.navAnalytics || "Analytics", icon: "sparkle" },
    { id: "compare", name: T.navCompare || "Compare", icon: "sort" },
    { id: "comments", name: T.navComments || "Comments", icon: "comment" },
    {
      id: "transcripts",
      name: T.navTranscripts || "Transcripts",
      icon: "list",
    },
    { id: "tags", name: T.navTags || "Теги", icon: "tag" },
    { id: "plans", name: T.navPlans || "Plans", icon: "sparkle" },
    { id: "settings", name: T.navSettings || "Settings", icon: "settings" },
    ...(userProfile?.is_superadmin
      ? [{ id: "admin", name: T.navAdmin || "Admin", icon: "sparkle" }]
      : []),
  ];
  return (
    <aside className={"sidebar" + (collapsed ? " collapsed" : "")}>
      <Logo collapsed={collapsed} onClick={onLogoClick} />
      <nav className="sidebar-nav">
        {items.map((it) => (
          <button
            key={it.id}
            className={"nav-item" + (page === it.id ? " active" : "")}
            onClick={() => setPage(it.id)}
            title={it.name}
          >
            <Icon name={it.icon} className="nav-ico" />
            {!collapsed && <span>{it.name}</span>}
          </button>
        ))}
      </nav>

      {/* ── Theme toggle ── */}
      {onThemeToggle && (
        <div style={{ padding: "8px 12px 4px" }}>
          {collapsed ? (
            <button
              className="btn ghost sm"
              onClick={onThemeToggle}
              title={isDark ? "Light mode" : "Dark mode"}
              style={{ width: "100%", justifyContent: "center" }}
            >
              <Icon name={isDark ? "sun" : "moon"} size={14} />
            </button>
          ) : (
            <div style={{ display: "flex", gap: 4 }}>
              <button
                className={"btn ghost sm" + (!isDark ? " active" : "")}
                onClick={() => !isDark || onThemeToggle()}
                title="Светлая"
                style={{
                  flex: 1,
                  justifyContent: "center",
                  background: !isDark ? "var(--bg-hover)" : "transparent",
                }}
              >
                <Icon name="sun" size={14} />
              </button>
              <button
                className={"btn ghost sm" + (isDark ? " active" : "")}
                onClick={() => isDark || onThemeToggle()}
                title="Тёмная"
                style={{
                  flex: 1,
                  justifyContent: "center",
                  background: isDark ? "var(--bg-hover)" : "transparent",
                }}
              >
                <Icon name="moon" size={14} />
              </button>
            </div>
          )}
        </div>
      )}

      {/* ── Footer: user info + logout ── */}
      <div className="sidebar-footer">
        <span className="avatar">
          {userProfile?.full_name?.[0]?.toUpperCase() ||
            userProfile?.email?.[0]?.toUpperCase() ||
            "?"}
        </span>
        {!collapsed && (
          <>
            <div className="user-meta">
              <div className="name">
                {userProfile?.full_name ||
                  userProfile?.email?.split("@")[0] ||
                  "—"}
              </div>
              <div className="email">{userProfile?.email || ""}</div>
            </div>
            <button
              className="btn ghost sm"
              onClick={onLogout}
              title="Sign out"
              style={{ padding: "0 6px", flexShrink: 0 }}
            >
              <Icon name="logout" size={15} />
            </button>
          </>
        )}
      </div>
    </aside>
  );
};

const Topbar = ({ title, subtitle, right }) => (
  <header className="topbar">
    <h1>{title}</h1>
    {subtitle && (
      <span
        className="subtitle"
        style={{ fontSize: 12, fontWeight: 400, color: "var(--fg-faint)" }}
      >
        {subtitle}
      </span>
    )}
    <div style={{ flex: 1 }} />
    {right}
  </header>
);

const Search = ({ value, onChange, placeholder }) => (
  <div className="search">
    <Icon name="search" size={14} />
    <input
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder || "Search…"}
    />
  </div>
);

const Check = ({ checked, onChange, label }) => (
  <label className="check">
    <input
      type="checkbox"
      checked={checked}
      onChange={(e) => onChange(e.target.checked)}
    />
    <span className="box"></span>
    <span className="lbl">{label}</span>
  </label>
);

const StatusPill = ({ status }) => {
  const map = { completed: "ok", running: "run", failed: "err" };
  return <span className={"status " + (map[status] || "")}>{status}</span>;
};

const MobileNav = ({ page, setPage }) => {
  const items = [
    { id: "analysis", name: "New", icon: "plus" },
    { id: "results", name: "Results", icon: "list" },
    { id: "settings", name: "Settings", icon: "settings" },
  ];
  return (
    <nav className="mobile-nav">
      {items.map((it) => (
        <button
          key={it.id}
          className={"mobile-nav-item" + (page === it.id ? " active" : "")}
          onClick={() => setPage(it.id)}
        >
          <Icon name={it.icon} size={22} />
          <span>{it.name}</span>
        </button>
      ))}
    </nav>
  );
};

// ── ForgotPasswordModal — через Supabase Auth ─────────────────────────────
const ForgotPasswordModal = ({ onClose }) => {
  const [email, setEmail] = React.useState("");
  const [sent, setSent] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");

  const handleSend = async () => {
    if (!email.trim()) return;
    setLoading(true);
    setError("");
    try {
      const { error } = await window.supabaseClient.auth.resetPasswordForEmail(
        email.trim(),
        {
          redirectTo: window.location.origin + "?reset=1",
        },
      );
      if (error) throw error;
      setSent(true);
    } catch (e) {
      setError(e.message || "Ошибка отправки");
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 200,
        background: "rgba(0,0,0,0.4)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        style={{
          background: "var(--bg)",
          border: "1px solid var(--border)",
          borderRadius: "var(--radius-lg)",
          padding: "28px 32px",
          width: 360,
          boxShadow: "var(--shadow-lg)",
        }}
      >
        {sent ? (
          <>
            <div
              style={{ fontSize: 32, marginBottom: 12, textAlign: "center" }}
            >
              📬
            </div>
            <h2
              style={{
                margin: "0 0 8px",
                fontSize: 18,
                fontWeight: 600,
                textAlign: "center",
              }}
            >
              {window.T?.productName === "Younalyse"
                ? "Email sent"
                : "Письмо отправлено"}
            </h2>
            <p
              style={{
                margin: "0 0 20px",
                color: "var(--fg-muted)",
                fontSize: 13,
                textAlign: "center",
                lineHeight: 1.5,
              }}
            >
              {window.T?.productName === "Younalyse"
                ? `Check ${email} — we sent you a reset link.`
                : `Проверьте ${email} — там будет ссылка для сброса пароля.`}
            </p>
            <button
              className="btn primary lg"
              style={{ width: "100%" }}
              onClick={onClose}
            >
              {window.T?.productName === "Younalyse" ? "Close" : "Закрыть"}
            </button>
          </>
        ) : (
          <>
            <h2 style={{ margin: "0 0 6px", fontSize: 18, fontWeight: 600 }}>
              {window.T?.productName === "Younalyse"
                ? "Reset password"
                : "Сброс пароля"}
            </h2>
            <p
              style={{
                margin: "0 0 20px",
                color: "var(--fg-muted)",
                fontSize: 13,
              }}
            >
              {window.T?.productName === "Younalyse"
                ? "Enter your email and we'll send you a reset link."
                : "Введите email — мы пришлём ссылку для создания нового пароля."}
            </p>
            <div className="field" style={{ marginBottom: 12 }}>
              <label>Email</label>
              <input
                className="input"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") handleSend();
                }}
                autoFocus
                placeholder="your@email.com"
              />
            </div>
            {error && (
              <div
                style={{
                  fontSize: 13,
                  color: "var(--bad)",
                  marginBottom: 12,
                  padding: "8px 12px",
                  background: "rgba(220,38,38,0.08)",
                  borderRadius: 6,
                }}
              >
                {error}
              </div>
            )}
            <div style={{ display: "flex", gap: 8 }}>
              <button className="btn" style={{ flex: 1 }} onClick={onClose}>
                {window.T?.cancel || "Cancel"}
              </button>
              <button
                className="btn primary"
                style={{ flex: 1 }}
                onClick={handleSend}
                disabled={loading || !email.trim()}
              >
                {loading ? (
                  <>
                    <Icon name="spinner" size={13} /> Отправляем…
                  </>
                ) : window.T?.productName === "Younalyse" ? (
                  "Send link"
                ) : (
                  "Отправить"
                )}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

Object.assign(window, {
  Icon,
  Logo,
  Sidebar,
  Topbar,
  Search,
  Check,
  StatusPill,
  MobileNav,
  ForgotPasswordModal,
});
