/* Admin Dashboard — YOUN-56 — только для суперадмина */

const API_URL_ADMIN = "https://younalyse-api-646149995822.europe-west1.run.app";

const AdminDashboardScreen = ({ userId }) => {
  const [activeTab, setActiveTab] = React.useState("pl");
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState("");
  const [excludeSuperadmin, setExcludeSuperadmin] = React.useState(false);
  const [productFilter, setProductFilter] = React.useState("all"); // all | ru | en
  const [manualCosts, setManualCosts] = React.useState({
    anthropic: "",
    gcp: "",
    supabase: "",
  });

  const load = (exclude = excludeSuperadmin, pf = productFilter) => {
    setLoading(true);
    setError("");
    const params = new URLSearchParams({
      user_id: userId,
      exclude_superadmin: exclude,
    });
    if (pf !== "all") params.set("product_mode", pf);
    fetch(`${API_URL_ADMIN}/api/admin/dashboard?${params}`)
      .then((r) => {
        if (!r.ok) throw new Error(`${r.status}`);
        return r.json();
      })
      .then((json) => {
        setData(json);
        setLoading(false);
      })
      .catch((e) => {
        setError(`Ошибка загрузки: ${e.message}`);
        setLoading(false);
      });
  };

  React.useEffect(() => {
    load();
  }, [userId]);

  const handleToggleExclude = (val) => {
    setExcludeSuperadmin(val);
    load(val, productFilter);
  };

  const handleProductFilter = (val) => {
    setProductFilter(val);
    load(excludeSuperadmin, val);
  };

  // Итоговые расходы с учётом ручного ввода
  const totalCosts = React.useMemo(() => {
    if (!data) return 0;
    const auto =
      (data.costs_estimated?.wordstat_usd || 0) +
      (data.costs_estimated?.searchapi_usd || 0);
    const manual =
      (parseFloat(manualCosts.anthropic) || 0) +
      (parseFloat(manualCosts.gcp) || 0) +
      (parseFloat(manualCosts.supabase) || 0);
    return round2(auto + manual);
  }, [data, manualCosts]);

  const mrr = data?.mrr?.mrr_eur || 0;
  const grossMargin = mrr > 0 ? round2(((mrr - totalCosts) / mrr) * 100) : 0;
  const marginColor =
    grossMargin >= 70
      ? "var(--good)"
      : grossMargin >= 50
        ? "var(--warn)"
        : "var(--bad)";

  if (loading)
    return (
      <div
        className="page"
        style={{
          textAlign: "center",
          padding: "80px 0",
          color: "var(--fg-faint)",
        }}
      >
        Загружаем дашборд…
      </div>
    );

  if (error)
    return (
      <div className="page">
        <div
          style={{
            padding: "20px",
            background: "rgba(220,38,38,0.08)",
            borderRadius: "var(--radius)",
            color: "var(--bad)",
            fontSize: 13,
          }}
        >
          {error}
        </div>
      </div>
    );

  const quota = data.youtube_quota;
  const quotaColor =
    quota.signal === "green"
      ? "var(--good)"
      : quota.signal === "yellow"
        ? "var(--warn)"
        : "var(--bad)";
  const sa = data.superadmin_usage;

  return (
    <div className="page" style={{ maxWidth: 1100 }}>
      {/* ── Хедер ── */}
      <div
        className="page-header"
        style={{
          display: "flex",
          alignItems: "flex-end",
          justifyContent: "space-between",
        }}
      >
        <div>
          <h2>Admin</h2>
          <p
            style={{
              fontFamily: "var(--mono)",
              fontSize: 11,
              color: "var(--fg-faint)",
            }}
          >
            Superadmin · обновлено{" "}
            {data.generated_at
              ? new Date(data.generated_at).toLocaleTimeString("ru")
              : "—"}
          </p>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          {activeTab === "pl" && (
            <>
              <div className="segmented">
                {["all", "ru", "en"].map((v) => (
                  <button
                    key={v}
                    className={productFilter === v ? "active" : ""}
                    onClick={() => handleProductFilter(v)}
                    style={{ textTransform: "uppercase", fontSize: 11 }}
                  >
                    {v === "all" ? "All" : v === "ru" ? "🇷🇺 RU" : "🌍 EN"}
                  </button>
                ))}
              </div>
              <label
                className="check"
                style={{ fontSize: 13, cursor: "pointer" }}
              >
                <input
                  type="checkbox"
                  checked={excludeSuperadmin}
                  onChange={(e) => handleToggleExclude(e.target.checked)}
                />
                <span className="box" />
                <span className="lbl">Исключить суперадминов</span>
              </label>
            </>
          )}
          <button className="btn" onClick={() => load()}>
            ↻ Обновить
          </button>
        </div>
      </div>

      {/* ── Вкладки ── */}
      <div className="segmented" style={{ marginBottom: 24 }}>
        <button
          className={activeTab === "pl" ? "active" : ""}
          onClick={() => setActiveTab("pl")}
        >
          P&L Dashboard
        </button>
        <button
          className={activeTab === "users" ? "active" : ""}
          onClick={() => setActiveTab("users")}
        >
          Пользователи
        </button>
        <button
          className={activeTab === "promos" ? "active" : ""}
          onClick={() => setActiveTab("promos")}
        >
          Промокоды
        </button>
      </div>

      {activeTab === "users" && <UsersTab userId={userId} />}
      {activeTab === "promos" && <PromosTab userId={userId} />}

      {activeTab === "pl" && (
        <>
          {/* ── Алерты ── */}
          {data.alerts?.length > 0 && (
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                gap: 8,
                marginBottom: 24,
              }}
            >
              {data.alerts.map((a, i) => (
                <div
                  key={i}
                  style={{
                    padding: "10px 16px",
                    borderRadius: "var(--radius)",
                    fontSize: 13,
                    fontWeight: 500,
                    background:
                      a.level === "red"
                        ? "rgba(220,38,38,0.08)"
                        : "rgba(217,119,6,0.08)",
                    color: a.level === "red" ? "var(--bad)" : "var(--warn)",
                    border: `1px solid ${a.level === "red" ? "var(--bad)" : "var(--warn)"}`,
                  }}
                >
                  {a.level === "red" ? "🔴" : "🟡"} {a.text}
                </div>
              ))}
            </div>
          )}

          {/* ── Топ KPI ── */}
          <div
            className="kpi-grid"
            style={{ gridTemplateColumns: "repeat(4,1fr)", marginBottom: 24 }}
          >
            <div className="kpi">
              <div className="label">
                MRR{excludeSuperadmin ? " (без SA)" : ""}
              </div>
              <div className="value">€{mrr.toFixed(2)}</div>
              <div className="delta">{data.mrr?.total_paid || 0} платных</div>
            </div>
            <div className="kpi">
              <div className="label">Расходы (оценка)</div>
              <div className="value">${totalCosts}</div>
              <div
                style={{ fontSize: 11, color: "var(--fg-faint)", marginTop: 2 }}
              >
                API + ручной ввод
              </div>
            </div>
            <div className="kpi">
              <div className="label">Gross Margin</div>
              <div className="value" style={{ color: marginColor }}>
                {mrr > 0 ? `${grossMargin}%` : "—"}
              </div>
            </div>
            <div className="kpi">
              <div className="label">
                Пользователи{excludeSuperadmin ? " (без SA)" : ""}
              </div>
              <div className="value">{data.users?.total_users || 0}</div>
              <div className="delta">
                {data.users?.trial_users || 0} на триале
              </div>
            </div>
          </div>

          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 16,
              marginBottom: 16,
            }}
          >
            {/* ── Тиры ── */}
            <div className="card">
              <div className="card-header">
                <h3>Подписки по тирам</h3>
                {excludeSuperadmin && (
                  <span className="chip">без суперадминов</span>
                )}
              </div>
              <div className="card-body">
                {Object.entries(data.mrr?.tier_counts || {}).length === 0 ? (
                  <div style={{ color: "var(--fg-faint)", fontSize: 13 }}>
                    Нет платных подписок
                  </div>
                ) : (
                  <table className="data" style={{ fontSize: 13 }}>
                    <thead>
                      <tr>
                        <th>Тир</th>
                        <th className="num">Кол-во</th>
                        <th className="num">MRR</th>
                      </tr>
                    </thead>
                    <tbody>
                      {[
                        { id: "start", label: "🌱 Старт", price: 14.95 },
                        { id: "pro", label: "🚀 Про", price: 34.95 },
                        { id: "producer", label: "🎬 Продюсер", price: 79.95 },
                        { id: "studio", label: "🏢 Студия", price: 199.95 },
                      ].map(({ id, label, price }) => {
                        const count = data.mrr?.tier_counts?.[id] || 0;
                        if (count === 0) return null;
                        return (
                          <tr key={id}>
                            <td>{label}</td>
                            <td className="num">{count}</td>
                            <td className="num">
                              €{(count * price).toFixed(2)}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                )}
              </div>
            </div>

            {/* ── Раны ── */}
            <div className="card">
              <div className="card-header">
                <h3>Раны{excludeSuperadmin ? " (без SA)" : ""}</h3>
              </div>
              <div className="card-body">
                <div
                  className="kpi-grid"
                  style={{ gridTemplateColumns: "repeat(3,1fr)" }}
                >
                  <div className="kpi">
                    <div className="label">Этот месяц</div>
                    <div className="value" style={{ fontSize: 20 }}>
                      {data.runs?.this_month || 0}
                    </div>
                  </div>
                  <div className="kpi">
                    <div className="label">Завершено</div>
                    <div className="value" style={{ fontSize: 20 }}>
                      {data.runs?.completed_this_month || 0}
                    </div>
                  </div>
                  <div className="kpi">
                    <div className="label">Всего</div>
                    <div className="value" style={{ fontSize: 20 }}>
                      {data.runs?.total || 0}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* ── YouTube API квота ── */}
            <div className="card">
              <div className="card-header">
                <h3>YouTube API quota</h3>
                <span
                  style={{ fontSize: 12, fontWeight: 600, color: quotaColor }}
                >
                  {quota.signal === "green"
                    ? "🟢"
                    : quota.signal === "yellow"
                      ? "🟡"
                      : "🔴"}{" "}
                  {quota.pct}%
                </span>
              </div>
              <div className="card-body">
                <div style={{ marginBottom: 12 }}>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      fontSize: 12,
                      marginBottom: 4,
                    }}
                  >
                    <span style={{ color: "var(--fg-muted)" }}>
                      Использовано сегодня
                    </span>
                    <span
                      style={{ fontFamily: "var(--mono)", fontWeight: 600 }}
                    >
                      {quota.total_used.toLocaleString()} /{" "}
                      {quota.total_limit.toLocaleString()}
                    </span>
                  </div>
                  <div
                    style={{
                      height: 6,
                      borderRadius: 3,
                      background: "var(--bg-sunk)",
                      overflow: "hidden",
                    }}
                  >
                    <div
                      style={{
                        height: "100%",
                        borderRadius: 3,
                        background: quotaColor,
                        width: `${Math.min(100, quota.pct)}%`,
                        transition: "width 0.3s",
                      }}
                    />
                  </div>
                </div>
                {quota.keys?.map((k, i) => (
                  <div
                    key={i}
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      fontSize: 12,
                      padding: "4px 0",
                      borderBottom: "1px solid var(--border)",
                    }}
                  >
                    <span
                      style={{
                        color: "var(--fg-muted)",
                        fontFamily: "var(--mono)",
                      }}
                    >
                      {k.project}
                    </span>
                    <span style={{ fontFamily: "var(--mono)" }}>
                      {k.used.toLocaleString()} / {k.limit.toLocaleString()}
                    </span>
                  </div>
                ))}
              </div>
            </div>

            {/* ── Keywords & Cache ── */}
            <div className="card">
              <div className="card-header">
                <h3>Keywords & Cache{excludeSuperadmin ? " (без SA)" : ""}</h3>
              </div>
              <div className="card-body">
                <div
                  className="kpi-grid"
                  style={{
                    gridTemplateColumns: "repeat(2,1fr)",
                    marginBottom: 16,
                  }}
                >
                  <div className="kpi">
                    <div className="label">Wordstat / мес</div>
                    <div className="value" style={{ fontSize: 18 }}>
                      {data.keywords?.wordstat_this_month || 0}
                    </div>
                    <div className="delta">
                      ${data.costs_estimated?.wordstat_usd || 0}
                    </div>
                  </div>
                  <div className="kpi">
                    <div className="label">SearchAPI / мес</div>
                    <div className="value" style={{ fontSize: 18 }}>
                      {data.keywords?.searchapi_this_month || 0}
                    </div>
                    <div className="delta">
                      ${data.costs_estimated?.searchapi_usd || 0}
                    </div>
                  </div>
                </div>
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    fontSize: 13,
                    padding: "6px 0",
                    borderTop: "1px solid var(--border)",
                  }}
                >
                  <span style={{ color: "var(--fg-muted)" }}>SERP в кэше</span>
                  <span style={{ fontFamily: "var(--mono)", fontWeight: 500 }}>
                    {data.cache?.serp_cached_keywords || 0} ключей
                  </span>
                </div>
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    fontSize: 13,
                    padding: "6px 0",
                    borderTop: "1px solid var(--border)",
                  }}
                >
                  <span style={{ color: "var(--fg-muted)" }}>
                    Wordstat в кэше
                  </span>
                  <span style={{ fontFamily: "var(--mono)", fontWeight: 500 }}>
                    {data.cache?.wordstat_cached_keywords || 0} ключей
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* ── Расходы суперадминов ── */}
          <div className="card" style={{ marginBottom: 16 }}>
            <div className="card-header">
              <h3>Расходы суперадминов (этот месяц)</h3>
              <span className="help">
                не включены в MRR — чистые затраты на тестирование
              </span>
            </div>
            <div className="card-body">
              <div
                className="kpi-grid"
                style={{ gridTemplateColumns: "repeat(4,1fr)" }}
              >
                <div className="kpi">
                  <div className="label">Ранов</div>
                  <div className="value" style={{ fontSize: 20 }}>
                    {sa?.runs_this_month || 0}
                  </div>
                </div>
                <div className="kpi">
                  <div className="label">Wordstat</div>
                  <div className="value" style={{ fontSize: 20 }}>
                    {sa?.wordstat_this_month || 0}
                  </div>
                </div>
                <div className="kpi">
                  <div className="label">SearchAPI</div>
                  <div className="value" style={{ fontSize: 20 }}>
                    {sa?.searchapi_this_month || 0}
                  </div>
                </div>
                <div className="kpi">
                  <div className="label">Оценка расходов</div>
                  <div
                    className="value"
                    style={{ fontSize: 20, color: "var(--bad)" }}
                  >
                    ${sa?.estimated_cost_usd || 0}
                  </div>
                  <div
                    style={{
                      fontSize: 11,
                      color: "var(--fg-faint)",
                      marginTop: 2,
                    }}
                  >
                    Keywords API
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* ── Ручной ввод расходов ── */}
          <div className="card">
            <div className="card-header">
              <h3>Расходы — ручной ввод (USD/мес)</h3>
              <span className="help">{data.costs_estimated?.note}</span>
            </div>
            <div className="card-body">
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(3,1fr)",
                  gap: 16,
                }}
              >
                {[
                  {
                    key: "anthropic",
                    label: "Anthropic Claude API",
                    hint: "console.anthropic.com → Usage",
                  },
                  {
                    key: "gcp",
                    label: "GCP Cloud Run",
                    hint: "console.cloud.google.com → Billing",
                  },
                  {
                    key: "supabase",
                    label: "Supabase",
                    hint: "supabase.com → Dashboard → Billing",
                  },
                ].map(({ key, label, hint }) => (
                  <div className="field" key={key}>
                    <label>{label}</label>
                    <div
                      style={{ display: "flex", alignItems: "center", gap: 8 }}
                    >
                      <span style={{ color: "var(--fg-faint)", fontSize: 13 }}>
                        $
                      </span>
                      <input
                        className="input"
                        type="number"
                        min="0"
                        step="0.01"
                        placeholder="0.00"
                        value={manualCosts[key]}
                        onChange={(e) =>
                          setManualCosts((prev) => ({
                            ...prev,
                            [key]: e.target.value,
                          }))
                        }
                        style={{ width: "100%" }}
                      />
                    </div>
                    <span className="help">{hint}</span>
                  </div>
                ))}
              </div>
              {totalCosts > 0 && mrr > 0 && (
                <div
                  style={{
                    marginTop: 16,
                    padding: "12px 16px",
                    borderRadius: "var(--radius)",
                    background: "var(--bg-elev)",
                    border: "1px solid var(--border)",
                    display: "flex",
                    gap: 32,
                  }}
                >
                  <div>
                    <div
                      style={{
                        fontSize: 11,
                        color: "var(--fg-faint)",
                        marginBottom: 2,
                      }}
                    >
                      ИТОГО РАСХОДЫ
                    </div>
                    <div style={{ fontWeight: 600, fontFamily: "var(--mono)" }}>
                      ${totalCosts}/мес
                    </div>
                  </div>
                  <div>
                    <div
                      style={{
                        fontSize: 11,
                        color: "var(--fg-faint)",
                        marginBottom: 2,
                      }}
                    >
                      GROSS MARGIN
                    </div>
                    <div
                      style={{
                        fontWeight: 700,
                        color: marginColor,
                        fontFamily: "var(--mono)",
                      }}
                    >
                      {grossMargin}%
                    </div>
                  </div>
                  <div>
                    <div
                      style={{
                        fontSize: 11,
                        color: "var(--fg-faint)",
                        marginBottom: 2,
                      }}
                    >
                      GROSS PROFIT
                    </div>
                    <div style={{ fontWeight: 600, fontFamily: "var(--mono)" }}>
                      €{round2(mrr - totalCosts)}/мес
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
};

function round2(n) {
  return Math.round(n * 100) / 100;
}

const TIER_LABELS = {
  trial: "Trial",
  start: "🌱 Старт",
  pro: "🚀 Про",
  producer: "🎬 Продюсер",
  studio: "🏢 Студия",
  superadmin: "⚡ Superadmin",
};

const UsersTab = ({ userId }) => {
  const [users, setUsers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [search, setSearch] = React.useState("");
  const [editing, setEditing] = React.useState(null);
  const [editTier, setEditTier] = React.useState("");
  const [editDate, setEditDate] = React.useState("");
  const [saving, setSaving] = React.useState(false);
  const [saved, setSaved] = React.useState(null);

  const load = () => {
    setLoading(true);
    fetch(`${API_URL_ADMIN}/api/admin/users?user_id=${userId}`)
      .then((r) => r.json())
      .then((d) => {
        setUsers(d.users || []);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  };

  React.useEffect(() => {
    load();
  }, [userId]);

  const startEdit = (u) => {
    setEditing(u.id);
    setEditTier(u.subscription_tier || "trial");
    setEditDate(u.trial_ends_at ? u.trial_ends_at.slice(0, 10) : "");
  };

  const cancelEdit = () => {
    setEditing(null);
    setEditTier("");
    setEditDate("");
  };

  const saveEdit = async (u) => {
    setSaving(true);
    try {
      const resp = await fetch(`${API_URL_ADMIN}/api/admin/grant-trial`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          admin_user_id: userId,
          target_user_id: u.id,
          subscription_tier: editTier,
          trial_ends_at: editDate ? new Date(editDate).toISOString() : null,
        }),
      });
      if (resp.ok) {
        setSaved(u.id);
        setTimeout(() => setSaved(null), 2000);
        cancelEdit();
        load();
      }
    } finally {
      setSaving(false);
    }
  };

  const filtered = users.filter((u) => {
    if (!search) return true;
    const q = search.toLowerCase();
    return (
      u.email?.toLowerCase().includes(q) ||
      u.full_name?.toLowerCase().includes(q)
    );
  });

  return (
    <div>
      <div className="table-toolbar" style={{ marginBottom: 12 }}>
        <Search
          value={search}
          onChange={setSearch}
          placeholder="Поиск по email или имени…"
        />
        <div style={{ flex: 1 }} />
        <span className="help">{filtered.length} пользователей</span>
        <button className="btn sm" onClick={load}>
          ↻
        </button>
      </div>
      {loading ? (
        <div
          style={{
            padding: "32px 0",
            textAlign: "center",
            color: "var(--fg-faint)",
            fontSize: 13,
          }}
        >
          Загружаем…
        </div>
      ) : (
        <div className="table-scroll">
          <table className="data" style={{ fontSize: 13 }}>
            <thead>
              <tr>
                <th>Email</th>
                <th>Имя</th>
                <th>Тир</th>
                <th>До</th>
                <th>Продукт</th>
                <th className="num">Ранов/мес</th>
                <th>Регистрация</th>
                <th style={{ width: 200 }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((u) => (
                <tr key={u.id}>
                  <td style={{ fontFamily: "var(--mono)", fontSize: 12 }}>
                    {u.email}
                  </td>
                  <td>{u.full_name || "—"}</td>
                  <td>
                    {editing === u.id ? (
                      <select
                        className="select"
                        value={editTier}
                        onChange={(e) => setEditTier(e.target.value)}
                        style={{ height: 28, fontSize: 12 }}
                      >
                        {Object.entries(TIER_LABELS)
                          .filter(([k]) => k !== "superadmin")
                          .map(([k, v]) => (
                            <option key={k} value={k}>
                              {v}
                            </option>
                          ))}
                      </select>
                    ) : (
                      <span
                        className={"chip" + (u.is_superadmin ? " accent" : "")}
                      >
                        {TIER_LABELS[u.subscription_tier] ||
                          u.subscription_tier}
                      </span>
                    )}
                  </td>
                  <td>
                    {editing === u.id ? (
                      <input
                        type="date"
                        className="input"
                        value={editDate}
                        onChange={(e) => setEditDate(e.target.value)}
                        style={{ height: 28, fontSize: 12, padding: "0 8px" }}
                      />
                    ) : (
                      <span style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                        {u.trial_ends_at
                          ? new Date(u.trial_ends_at).toLocaleDateString("ru")
                          : "—"}
                      </span>
                    )}
                  </td>
                  <td>
                    <span
                      className={
                        "chip" + (u.product_mode === "en" ? " accent" : "")
                      }
                    >
                      {u.product_mode === "en" ? "🌍 EN" : "🇷🇺 RU"}
                    </span>
                  </td>
                  <td className="num">{u.runs_this_month ?? 0}</td>
                  <td style={{ fontSize: 12, color: "var(--fg-faint)" }}>
                    {u.created_at
                      ? new Date(u.created_at).toLocaleDateString("ru")
                      : "—"}
                  </td>
                  <td>
                    {u.is_superadmin ? (
                      <span style={{ fontSize: 11, color: "var(--fg-faint)" }}>
                        superadmin
                      </span>
                    ) : editing === u.id ? (
                      <div style={{ display: "flex", gap: 6 }}>
                        <button
                          className="btn primary sm"
                          disabled={saving}
                          onClick={() => saveEdit(u)}
                        >
                          {saving ? (
                            <Icon name="spinner" size={12} />
                          ) : (
                            "Сохранить"
                          )}
                        </button>
                        <button className="btn sm" onClick={cancelEdit}>
                          Отмена
                        </button>
                      </div>
                    ) : (
                      <button className="btn sm" onClick={() => startEdit(u)}>
                        {saved === u.id ? "✓ Сохранено" : "Изменить"}
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

// ── PromosTab ──────────────────────────────────────────────────────────────
const PromosTab = ({ userId }) => {
  const [promos, setPromos] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showForm, setShowForm] = React.useState(false);
  const [form, setForm] = React.useState({
    code: "",
    type: "trial_days",
    days: 30,
    tier: "pro",
    pct: 20,
    months: 3,
    max_uses: "",
    expires_at: "",
  });
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState("");

  const load = () => {
    setLoading(true);
    fetch(`${API_URL_ADMIN}/api/admin/promos?user_id=${userId}`)
      .then((r) => r.json())
      .then((d) => {
        setPromos(d.promos || []);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  };

  React.useEffect(() => {
    load();
  }, [userId]);

  const handleCreate = async () => {
    if (!form.code.trim()) {
      setError("Введите код");
      return;
    }
    setError("");
    setSaving(true);

    let value = {};
    if (form.type === "trial_days") value = { days: parseInt(form.days) };
    else if (form.type === "tier_period")
      value = { tier: form.tier, days: parseInt(form.days) };
    else if (form.type === "discount")
      value = { pct: parseInt(form.pct), months: parseInt(form.months) };

    try {
      const resp = await fetch(`${API_URL_ADMIN}/api/admin/promos`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          admin_user_id: userId,
          code: form.code,
          type: form.type,
          value,
          max_uses: form.max_uses ? parseInt(form.max_uses) : null,
          expires_at: form.expires_at
            ? new Date(form.expires_at).toISOString()
            : null,
        }),
      });
      const data = await resp.json();
      if (!resp.ok) {
        setError(data.detail || "Ошибка");
        return;
      }
      setShowForm(false);
      setForm({
        code: "",
        type: "trial_days",
        days: 30,
        tier: "pro",
        pct: 20,
        months: 3,
        max_uses: "",
        expires_at: "",
      });
      load();
    } catch {
      setError("Ошибка сети");
    } finally {
      setSaving(false);
    }
  };

  const toggleActive = async (p) => {
    await fetch(`${API_URL_ADMIN}/api/admin/promos/${p.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ admin_user_id: userId, is_active: !p.is_active }),
    });
    load();
  };

  const bonusLabel = (p) => {
    const v = p.value || {};
    if (p.type === "trial_days") return `Триал ${v.days} дней`;
    if (p.type === "tier_period") return `Тир ${v.tier} на ${v.days} дней`;
    if (p.type === "discount") return `Скидка ${v.pct}% на ${v.months} мес.`;
    return "—";
  };

  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          marginBottom: 16,
        }}
      >
        <div style={{ fontSize: 13, color: "var(--fg-muted)" }}>
          {promos.length} промокодов
        </div>
        <button
          className="btn primary sm"
          onClick={() => setShowForm((v) => !v)}
        >
          {showForm ? "Отмена" : "+ Создать промокод"}
        </button>
      </div>

      {/* Форма создания */}
      {showForm && (
        <div
          style={{
            padding: 16,
            borderRadius: "var(--radius)",
            background: "var(--bg-elev)",
            border: "1px solid var(--border)",
            marginBottom: 20,
          }}
        >
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr 1fr",
              gap: 12,
              marginBottom: 12,
            }}
          >
            <div>
              <label
                style={{
                  fontSize: 11,
                  color: "var(--fg-faint)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                КОД
              </label>
              <input
                className="input"
                value={form.code}
                onChange={(e) =>
                  setForm((f) => ({ ...f, code: e.target.value.toUpperCase() }))
                }
                placeholder="BLOGGER123"
                style={{ fontSize: 13 }}
              />
            </div>
            <div>
              <label
                style={{
                  fontSize: 11,
                  color: "var(--fg-faint)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                ТИП
              </label>
              <select
                className="select"
                value={form.type}
                onChange={(e) =>
                  setForm((f) => ({ ...f, type: e.target.value }))
                }
                style={{ height: 32, fontSize: 13 }}
              >
                <option value="trial_days">Триал N дней</option>
                <option value="tier_period">Тир на N дней</option>
                <option value="discount">Скидка %</option>
              </select>
            </div>
            {form.type === "trial_days" && (
              <div>
                <label
                  style={{
                    fontSize: 11,
                    color: "var(--fg-faint)",
                    display: "block",
                    marginBottom: 4,
                  }}
                >
                  ДНЕЙ
                </label>
                <input
                  className="input"
                  type="number"
                  value={form.days}
                  onChange={(e) =>
                    setForm((f) => ({ ...f, days: e.target.value }))
                  }
                  style={{ fontSize: 13 }}
                />
              </div>
            )}
            {form.type === "tier_period" && (
              <>
                <div>
                  <label
                    style={{
                      fontSize: 11,
                      color: "var(--fg-faint)",
                      display: "block",
                      marginBottom: 4,
                    }}
                  >
                    ТИР
                  </label>
                  <select
                    className="select"
                    value={form.tier}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, tier: e.target.value }))
                    }
                    style={{ height: 32, fontSize: 13 }}
                  >
                    <option value="start">🌱 Старт</option>
                    <option value="pro">🚀 Про</option>
                    <option value="producer">🎬 Продюсер</option>
                    <option value="studio">🏢 Студия</option>
                  </select>
                </div>
                <div>
                  <label
                    style={{
                      fontSize: 11,
                      color: "var(--fg-faint)",
                      display: "block",
                      marginBottom: 4,
                    }}
                  >
                    ДНЕЙ
                  </label>
                  <input
                    className="input"
                    type="number"
                    value={form.days}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, days: e.target.value }))
                    }
                    style={{ fontSize: 13 }}
                  />
                </div>
              </>
            )}
            {form.type === "discount" && (
              <>
                <div>
                  <label
                    style={{
                      fontSize: 11,
                      color: "var(--fg-faint)",
                      display: "block",
                      marginBottom: 4,
                    }}
                  >
                    СКИДКА %
                  </label>
                  <input
                    className="input"
                    type="number"
                    value={form.pct}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, pct: e.target.value }))
                    }
                    style={{ fontSize: 13 }}
                  />
                </div>
                <div>
                  <label
                    style={{
                      fontSize: 11,
                      color: "var(--fg-faint)",
                      display: "block",
                      marginBottom: 4,
                    }}
                  >
                    МЕСЯЦЕВ
                  </label>
                  <input
                    className="input"
                    type="number"
                    value={form.months}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, months: e.target.value }))
                    }
                    style={{ fontSize: 13 }}
                  />
                </div>
              </>
            )}
          </div>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 12,
              marginBottom: 12,
            }}
          >
            <div>
              <label
                style={{
                  fontSize: 11,
                  color: "var(--fg-faint)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                МАКС. ИСПОЛЬЗОВАНИЙ (пусто = ∞)
              </label>
              <input
                className="input"
                type="number"
                value={form.max_uses}
                onChange={(e) =>
                  setForm((f) => ({ ...f, max_uses: e.target.value }))
                }
                placeholder="∞"
                style={{ fontSize: 13 }}
              />
            </div>
            <div>
              <label
                style={{
                  fontSize: 11,
                  color: "var(--fg-faint)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                СРОК ДЕЙСТВИЯ КОДА
              </label>
              <input
                className="input"
                type="date"
                value={form.expires_at}
                onChange={(e) =>
                  setForm((f) => ({ ...f, expires_at: e.target.value }))
                }
                style={{ fontSize: 13 }}
              />
            </div>
          </div>
          {error && (
            <div style={{ fontSize: 13, color: "var(--bad)", marginBottom: 8 }}>
              {error}
            </div>
          )}
          <button
            className="btn primary"
            onClick={handleCreate}
            disabled={saving}
          >
            {saving ? (
              <>
                <Icon name="spinner" size={13} /> Создаём…
              </>
            ) : (
              "Создать"
            )}
          </button>
        </div>
      )}

      {/* Таблица промокодов */}
      {loading ? (
        <div
          style={{
            padding: "32px 0",
            textAlign: "center",
            color: "var(--fg-faint)",
            fontSize: 13,
          }}
        >
          Загружаем…
        </div>
      ) : promos.length === 0 ? (
        <div
          style={{
            padding: "48px 0",
            textAlign: "center",
            color: "var(--fg-faint)",
          }}
        >
          <div style={{ fontSize: 32, marginBottom: 12 }}>🎟</div>
          <div style={{ fontSize: 14 }}>Промокодов пока нет</div>
        </div>
      ) : (
        <div className="table-scroll">
          <table className="data" style={{ fontSize: 13 }}>
            <thead>
              <tr>
                <th>Код</th>
                <th>Бонус</th>
                <th className="num">Использований</th>
                <th className="num">Лимит</th>
                <th>Истекает</th>
                <th>Статус</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {promos.map((p) => (
                <tr key={p.id}>
                  <td
                    style={{
                      fontFamily: "var(--mono)",
                      fontWeight: 600,
                      fontSize: 12,
                    }}
                  >
                    {p.code}
                  </td>
                  <td>{bonusLabel(p)}</td>
                  <td className="num">{p.uses_count || 0}</td>
                  <td className="num">{p.max_uses ?? "∞"}</td>
                  <td style={{ fontSize: 12, color: "var(--fg-faint)" }}>
                    {p.expires_at
                      ? new Date(p.expires_at).toLocaleDateString("ru")
                      : "—"}
                  </td>
                  <td>
                    <span className={"status " + (p.is_active ? "ok" : "err")}>
                      {p.is_active ? "активен" : "отключён"}
                    </span>
                  </td>
                  <td>
                    <button
                      className={"btn sm " + (p.is_active ? "danger" : "")}
                      onClick={() => toggleActive(p)}
                    >
                      {p.is_active ? "Отключить" : "Включить"}
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { AdminDashboardScreen });
