/* Analytics screen — YouTube channel analytics via OAuth */

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

// ── Helpers ───────────────────────────────────────────────────────────────

const fmtSeconds = (s) => {
  const m = Math.floor(s / 60);
  const sec = Math.round(s % 60);
  return `${m}:${String(sec).padStart(2, "0")}`;
};

const fmtPct = (v) => `${(parseFloat(v) || 0).toFixed(1)}%`;

const getTrafficLabel = (key) => {
  const T = window.T || {};
  const map = {
    YT_SEARCH: T.trafficYTSearch || "YouTube Search",
    EXT_URL: T.trafficExternal || "External",
    SUBSCRIBER: T.trafficSubscribers || "Subscribers",
    RELATED_VIDEO: T.trafficSuggested || "Suggested Videos",
    PLAYLIST: T.trafficPlaylist || "Playlist",
    NOTIFICATION: T.trafficNotifications || "Notifications",
    YT_CHANNEL: T.trafficChannelPage || "Channel Page",
    NO_LINK_OTHER: T.trafficOther || "Other",
    ANNOTATION: T.trafficAnnotations || "Annotations",
    CAMPAIGN_CARD: T.trafficCampaign || "Campaign Card",
    END_SCREEN: T.trafficEndScreen || "End Screen",
    SHORTS: T.trafficShorts || "YouTube Shorts",
  };
  return map[key] || key;
};

// ── Subcomponents ─────────────────────────────────────────────────────────

const StatCard = ({ label, value, sub }) => (
  <div className="kpi">
    <div className="label">{label}</div>
    <div className="value" style={{ fontSize: 20 }}>
      {value}
    </div>
    {sub && (
      <div style={{ fontSize: 11, color: "var(--fg-faint)", marginTop: 2 }}>
        {sub}
      </div>
    )}
  </div>
);

const ConnectChannelCard = ({ userId }) => {
  const T = window.T || {};
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        padding: "80px 32px",
        textAlign: "center",
        border: "1px dashed var(--border-strong)",
        borderRadius: "var(--radius-lg)",
        background: "var(--bg-elev)",
      }}
    >
      <div style={{ fontSize: 48, marginBottom: 16 }}>📺</div>
      <div
        style={{
          fontSize: 18,
          fontWeight: 600,
          marginBottom: 8,
          letterSpacing: "-0.01em",
        }}
      >
        {T.analyticsConnectTitle || "Connect your YouTube channel"}
      </div>
      <div
        style={{
          fontSize: 14,
          color: "var(--fg-muted)",
          maxWidth: 400,
          lineHeight: 1.6,
          marginBottom: 24,
        }}
      >
        {T.analyticsConnectHint ||
          "Connect your channel via Google OAuth to see real analytics — views, watch time, retention, CTR, and traffic sources."}
      </div>
      <button
        className="btn primary lg"
        onClick={() => {
          window.location.href = `${API_URL_ANALYTICS}/auth/youtube?user_id=${userId}`;
        }}
      >
        <Icon name="youtube" size={16} />
        {T.analyticsConnectBtn || "Connect YouTube channel"}
      </button>
      <div style={{ fontSize: 12, color: "var(--fg-faint)", marginTop: 12 }}>
        {T.analyticsConnectNote ||
          "Requires YouTube Analytics read access · Data stays private"}
      </div>
    </div>
  );
};

// ── Daily Chart с tooltip ─────────────────────────────────────────────────

const DailyChart = ({ data }) => {
  const [tooltip, setTooltip] = React.useState(null); // { idx, x }

  if (!data?.rows?.length) return null;

  const views = data.rows.map((r) => r[1] || 0);
  const maxViews = Math.max(...views, 1);
  const labels = data.rows.map((r) => r[0]?.slice(5));

  return (
    <div style={{ position: "relative" }}>
      <div
        style={{
          display: "flex",
          alignItems: "flex-end",
          gap: 3,
          height: 100,
          padding: "8px 0 0",
        }}
      >
        {data.rows.map((row, i) => {
          const h = Math.max(4, (row[1] / maxViews) * 92);
          return (
            <div
              key={i}
              style={{
                flex: 1,
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                justifyContent: "flex-end",
                height: "100%",
                cursor: "default",
              }}
              onMouseEnter={() => setTooltip(i)}
              onMouseLeave={() => setTooltip(null)}
            >
              <div
                style={{
                  width: "100%",
                  height: h,
                  background: tooltip === i ? "var(--accent)" : "var(--accent)",
                  opacity: tooltip === i ? 1 : 0.65,
                  borderRadius: "2px 2px 0 0",
                  transition: "opacity 0.1s",
                }}
              />
            </div>
          );
        })}
      </div>
      {/* Tooltip под баром */}
      {tooltip !== null && (
        <div
          style={{
            marginTop: 6,
            fontSize: 12,
            color: "var(--fg-muted)",
            textAlign: "center",
            fontFamily: "var(--mono)",
          }}
        >
          {labels[tooltip]}:{" "}
          <strong style={{ color: "var(--fg)" }}>
            {window.fmtNum(data.rows[tooltip][1])}
          </strong>
        </div>
      )}
      {tooltip === null && <div style={{ height: 22 }} />}
      {/* X-axis labels: first, middle, last */}
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          marginTop: 2,
        }}
      >
        <span style={{ fontSize: 10, color: "var(--fg-faint)" }}>
          {labels[0]}
        </span>
        <span style={{ fontSize: 10, color: "var(--fg-faint)" }}>
          {labels[Math.floor(labels.length / 2)]}
        </span>
        <span style={{ fontSize: 10, color: "var(--fg-faint)" }}>
          {labels[labels.length - 1]}
        </span>
      </div>
    </div>
  );
};

// ── Traffic Sources ────────────────────────────────────────────────────────

const TrafficSourcesTable = ({ data }) => {
  const T = window.T || {};
  if (!data?.rows?.length)
    return (
      <div
        style={{ color: "var(--fg-faint)", fontSize: 13, padding: "16px 0" }}
      >
        {T.analyticsNoTraffic || "No traffic data available"}
      </div>
    );

  const total = data.rows.reduce((sum, r) => sum + (r[1] || 0), 0);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {data.rows.map((row, i) => {
        const source = getTrafficLabel(row[0]);
        const views = row[1] || 0;
        const pct = total > 0 ? (views / total) * 100 : 0;
        return (
          <div
            key={i}
            style={{ display: "flex", alignItems: "center", gap: 10 }}
          >
            <div style={{ flex: 1, fontSize: 13 }}>{source}</div>
            <div
              style={{
                width: 100,
                height: 5,
                borderRadius: 3,
                background: "var(--bg-sunk)",
                overflow: "hidden",
                flexShrink: 0,
              }}
            >
              <div
                style={{
                  width: `${pct}%`,
                  height: "100%",
                  background: "var(--accent)",
                  borderRadius: 3,
                }}
              />
            </div>
            <div
              style={{
                fontSize: 12,
                fontFamily: "var(--mono)",
                color: "var(--fg-muted)",
                minWidth: 44,
                textAlign: "right",
              }}
            >
              {window.fmtNum(views)}
            </div>
            <div
              style={{
                fontSize: 11,
                color: "var(--fg-faint)",
                fontFamily: "var(--mono)",
                minWidth: 32,
                textAlign: "right",
              }}
            >
              {pct.toFixed(0)}%
            </div>
          </div>
        );
      })}
    </div>
  );
};

// ── Audience Insights ──────────────────────────────────────────────────────

const AudienceInsights = ({ data }) => {
  const T = window.T || {};

  if (
    !data ||
    (!data.countries?.rows?.length &&
      !data.device_types?.rows?.length &&
      !data.viewer_types?.rows?.length &&
      !data.ctr &&
      !data.impressions)
  )
    return (
      <div
        style={{ color: "var(--fg-faint)", fontSize: 13, padding: "16px 0" }}
      >
        {T.analyticsNoAudience || "No audience data available"}
      </div>
    );

  const {
    countries,
    device_types,
    viewer_types,
    ctr,
    impressions,
    avg_view_duration,
    unique_viewers,
  } = data;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      {/* Топ стран */}
      {countries?.rows?.length > 0 && (
        <div>
          <div
            style={{
              fontSize: 12,
              fontWeight: 600,
              color: "var(--fg-muted)",
              marginBottom: 8,
              textTransform: "uppercase",
              letterSpacing: "0.05em",
            }}
          >
            {T.analyticsTopCountries || "Top countries"}
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {countries.rows.slice(0, 5).map((row, i) => {
              const total = countries.rows.reduce((s, r) => s + (r[1] || 0), 0);
              const pct = total > 0 ? (row[1] / total) * 100 : 0;
              return (
                <div
                  key={i}
                  style={{ display: "flex", alignItems: "center", gap: 8 }}
                >
                  <div style={{ flex: 1, fontSize: 13 }}>{row[0]}</div>
                  <div
                    style={{
                      width: 80,
                      height: 4,
                      borderRadius: 2,
                      background: "var(--bg-sunk)",
                      overflow: "hidden",
                      flexShrink: 0,
                    }}
                  >
                    <div
                      style={{
                        width: `${pct}%`,
                        height: "100%",
                        background: "var(--accent)",
                        borderRadius: 2,
                      }}
                    />
                  </div>
                  <div
                    style={{
                      fontSize: 11,
                      color: "var(--fg-faint)",
                      fontFamily: "var(--mono)",
                      minWidth: 32,
                      textAlign: "right",
                    }}
                  >
                    {pct.toFixed(0)}%
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Тип устройства */}
      {device_types?.rows?.length > 0 && (
        <div>
          <div
            style={{
              fontSize: 12,
              fontWeight: 600,
              color: "var(--fg-muted)",
              marginBottom: 8,
              textTransform: "uppercase",
              letterSpacing: "0.05em",
            }}
          >
            {T.analyticsDeviceTypes || "Device types"}
          </div>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {device_types.rows.map((row, i) => {
              const total = device_types.rows.reduce(
                (s, r) => s + (r[1] || 0),
                0,
              );
              const pct = total > 0 ? (row[1] / total) * 100 : 0;
              const icons = {
                MOBILE: "📱",
                DESKTOP: "💻",
                TV: "📺",
                TABLET: "📱",
                GAME_CONSOLE: "🎮",
              };
              const deviceLabels = {
                MOBILE: T.deviceMobile || "Mobile",
                DESKTOP: T.deviceDesktop || "Desktop",
                TV: T.deviceTV || "TV",
                TABLET: T.deviceTablet || "Tablet",
                GAME_CONSOLE: T.deviceConsole || "Console",
              };
              return (
                <div
                  key={i}
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    gap: 3,
                    minWidth: 60,
                  }}
                >
                  <span style={{ fontSize: 18 }}>{icons[row[0]] || "📺"}</span>
                  <span style={{ fontSize: 11, color: "var(--fg-muted)" }}>
                    {deviceLabels[row[0]] || row[0]}
                  </span>
                  <span style={{ fontSize: 13, fontWeight: 600 }}>
                    {pct.toFixed(0)}%
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Новые vs вернувшиеся */}
      {viewer_types?.rows?.length > 0 && (
        <div>
          <div
            style={{
              fontSize: 12,
              fontWeight: 600,
              color: "var(--fg-muted)",
              marginBottom: 8,
              textTransform: "uppercase",
              letterSpacing: "0.05em",
            }}
          >
            {T.analyticsViewerTypes || "New vs returning"}
          </div>
          <div style={{ display: "flex", gap: 12 }}>
            {viewer_types.rows.map((row, i) => {
              const total = viewer_types.rows.reduce(
                (s, r) => s + (r[1] || 0),
                0,
              );
              const pct = total > 0 ? (row[1] / total) * 100 : 0;
              // subscribedStatus: SUBSCRIBED = постоянные, NOT_SUBSCRIBED = новые
              // YouTube Analytics: SUBSCRIBED = постоянные, UNSUBSCRIBED = новые
              const isNew =
                row[0] === "UNSUBSCRIBED" ||
                row[0] === "NOT_SUBSCRIBED" ||
                row[0] === "NEW";
              const emoji = isNew ? "✨" : "🔄"; // SUBSCRIBED=returning, UNSUBSCRIBED=new
              const label = isNew
                ? T.analyticsNewViewers || "New"
                : T.analyticsReturning || "Returning";
              return (
                <div
                  key={i}
                  style={{
                    flex: 1,
                    padding: "10px 12px",
                    borderRadius: "var(--radius)",
                    background: "var(--bg-sunk)",
                    textAlign: "center",
                  }}
                >
                  <div style={{ fontSize: 18, marginBottom: 4 }}>{emoji}</div>
                  <div style={{ fontSize: 20, fontWeight: 700 }}>
                    {pct.toFixed(0)}%
                  </div>
                  <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>
                    {label}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
      {/* CTR */}
      {ctr !== undefined && ctr !== null && (
        <div>
          <div
            style={{
              fontSize: 12,
              fontWeight: 600,
              color: "var(--fg-muted)",
              marginBottom: 6,
              textTransform: "uppercase",
              letterSpacing: "0.05em",
            }}
          >
            {T.analyticsCTR || "Click-through rate (CTR)"}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div
              style={{
                fontSize: 28,
                fontWeight: 700,
                color:
                  ctr >= 4
                    ? "var(--good)"
                    : ctr >= 2
                      ? "var(--warn)"
                      : "var(--bad)",
              }}
            >
              {fmtPct(ctr)}
            </div>
            <div
              style={{
                fontSize: 11,
                color: "var(--fg-faint)",
                lineHeight: 1.4,
              }}
            >
              {impressions
                ? `${window.fmtNum(impressions)} ${T.analyticsImpressions || "impressions"}`
                : ""}
            </div>
          </div>
        </div>
      )}

      {/* Уникальные зрители */}
      {unique_viewers !== undefined && unique_viewers !== null && (
        <div>
          <div
            style={{
              fontSize: 12,
              fontWeight: 600,
              color: "var(--fg-muted)",
              marginBottom: 6,
              textTransform: "uppercase",
              letterSpacing: "0.05em",
            }}
          >
            {T.analyticsUniqueViewers || "Unique viewers"}
          </div>
          <div style={{ fontSize: 24, fontWeight: 700 }}>
            {window.fmtNum(unique_viewers)}
          </div>
        </div>
      )}
    </div>
  );
};

// ── Top Videos Table ───────────────────────────────────────────────────────

const TopVideosTable = ({ data, days }) => {
  const T = window.T || {};
  if (!data?.rows?.length) return null;

  const avgViews = React.useMemo(() => {
    const viewsList = data.rows.map((row) => {
      const hasTitle = typeof row[1] === "string" && isNaN(Number(row[1]));
      return hasTitle ? row[2] || 0 : row[1] || 0;
    });
    const total = viewsList.reduce((s, v) => s + v, 0);
    return viewsList.length > 0 ? total / viewsList.length : 0;
  }, [data]);

  return (
    <div className="card" style={{ marginBottom: 24 }}>
      <div className="card-header">
        <h3>{T.analyticsTopVideos || "Top videos"}</h3>
        <span className="help">
          {T.analyticsByViews || "by views"} · {T.analyticsLast || "last"}{" "}
          {days} {T.analyticsDays || "days"}
        </span>
      </div>
      <div className="card-body" style={{ padding: 0 }}>
        <table className="data">
          <thead>
            <tr>
              <th style={{ minWidth: 320 }}>
                {T.analyticsColVideo || "Video"}
              </th>
              <th className="num">{T.analyticsViews || "Views"}</th>
              <th className="num">{T.analyticsWatchTime || "Watch time"}</th>
              <th className="num">
                {T.analyticsAvgDuration || "Avg duration"}
              </th>
              <th className="num">{T.analyticsRetention || "Retention"}</th>
              <th className="num">Outlier</th>
            </tr>
          </thead>
          <tbody>
            {data.rows.map((row, i) => {
              const videoId = row[0];
              const hasTitle =
                typeof row[1] === "string" && isNaN(Number(row[1]));
              const title = hasTitle ? row[1] : null;
              const views = hasTitle ? row[2] : row[1];
              const watchMin = hasTitle ? row[3] : row[2];
              const avgDur = hasTitle ? row[4] : row[3];
              const retention = hasTitle ? row[5] : row[4];
              const outlierScore =
                avgViews > 0 ? (views || 0) / avgViews : null;

              return (
                <tr key={i}>
                  <td>
                    <a
                      href={`https://youtube.com/watch?v=${videoId}`}
                      target="_blank"
                      style={{
                        fontSize: 13,
                        color: "var(--fg)",
                        fontWeight: 500,
                        textDecoration: "none",
                        display: "block",
                        maxWidth: 320,
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                      }}
                      title={title || videoId}
                    >
                      {title || videoId}
                    </a>
                    {title && (
                      <span
                        style={{
                          fontSize: 11,
                          color: "var(--fg-faint)",
                          fontFamily: "var(--mono)",
                        }}
                      >
                        {videoId}
                      </span>
                    )}
                  </td>
                  <td className="num">{window.fmtNum(views)}</td>
                  <td className="num">
                    {window.fmtNum(Math.round((watchMin || 0) / 60))}h
                  </td>
                  <td className="num">{fmtSeconds(avgDur || 0)}</td>
                  <td className="num">{fmtPct(retention || 0)}</td>
                  <td className="num">
                    <OutlierBadge score={outlierScore} />
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ── Main Analytics Screen ─────────────────────────────────────────────────

const AnalyticsScreen = ({ userId }) => {
  const T = window.T || {};
  const [channels, setChannels] = React.useState([]);
  const [selectedChannel, setSelectedChannel] = React.useState(null);
  const [analytics, setAnalytics] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [analyticsLoading, setAnalyticsLoading] = React.useState(false);
  const [days, setDays] = React.useState(28);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    if (!userId) return;
    setLoading(true);
    fetch(`${API_URL_ANALYTICS}/api/analytics/channels?user_id=${userId}`)
      .then((r) => r.json())
      .then((json) => {
        setChannels(json.channels || []);
        if (json.channels?.length > 0) setSelectedChannel(json.channels[0]);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [userId]);

  React.useEffect(() => {
    if (!selectedChannel || !userId) return;
    setAnalyticsLoading(true);
    setAnalytics(null);
    setError(null);

    fetch(
      `${API_URL_ANALYTICS}/api/analytics/channel/${selectedChannel.channel_id}?user_id=${userId}&days=${days}`,
    )
      .then((r) => {
        if (!r.ok) throw new Error(`Error ${r.status}`);
        return r.json();
      })
      .then((json) => {
        setAnalytics(json);
        setAnalyticsLoading(false);
      })
      .catch(() => {
        setError(
          T.analyticsError ||
            "Failed to load analytics. Check that YouTube Analytics API is enabled.",
        );
        setAnalyticsLoading(false);
      });
  }, [selectedChannel?.channel_id, days, userId]);

  const summary = React.useMemo(() => {
    if (!analytics?.analytics?.rows?.length) return null;
    const rows = analytics.analytics.rows;
    return {
      views: rows.reduce((s, r) => s + (r[1] || 0), 0),
      watchMinutes: rows.reduce((s, r) => s + (r[2] || 0), 0),
      avgDuration: rows.reduce((s, r) => s + (r[3] || 0), 0) / rows.length,
      avgRetention: rows.reduce((s, r) => s + (r[4] || 0), 0) / rows.length,
      subsGained: rows.reduce((s, r) => s + (r[5] || 0), 0),
      subsLost: rows.reduce((s, r) => s + (r[6] || 0), 0),
      likes: rows.reduce((s, r) => s + (r[7] || 0), 0),
    };
  }, [analytics]);

  if (loading) {
    return (
      <div className="page">
        <div
          style={{
            padding: "60px 0",
            textAlign: "center",
            color: "var(--fg-faint)",
          }}
        >
          {T.loading || "Loading…"}
        </div>
      </div>
    );
  }

  return (
    <div className="page" style={{ maxWidth: 1200 }}>
      {/* Топбар-контролы: канал + период + добавить */}
      {channels.length > 0 && (
        <div
          style={{
            display: "flex",
            gap: 8,
            alignItems: "center",
            marginBottom: 20,
          }}
        >
          {channels.length > 1 && (
            <select
              className="select"
              style={{ height: 36, fontSize: 13, width: 330, flexShrink: 0 }}
              value={selectedChannel?.channel_id}
              onChange={(e) => {
                const found = channels.find(
                  (c) => c.channel_id === e.target.value,
                );
                if (found) setSelectedChannel(found);
              }}
            >
              {channels.map((ch) => (
                <option key={ch.channel_id} value={ch.channel_id}>
                  {ch.channel_name}
                </option>
              ))}
            </select>
          )}

          {channels.length === 1 && selectedChannel && (
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              {selectedChannel.channel_thumbnail && (
                <img
                  src={selectedChannel.channel_thumbnail}
                  style={{ width: 28, height: 28, borderRadius: "50%" }}
                  alt=""
                />
              )}
              <span style={{ fontWeight: 600, fontSize: 14 }}>
                {selectedChannel.channel_name}
              </span>
            </div>
          )}

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

          <div className="segmented">
            {[7, 28, 90].map((d) => (
              <button
                key={d}
                className={days === d ? "active" : ""}
                onClick={() => setDays(d)}
              >
                {d}
                {T.analyticsDaysShort || "d"}
              </button>
            ))}
          </div>

          <button
            className="btn sm"
            onClick={() =>
              (window.location.href = `${API_URL_ANALYTICS}/auth/youtube?user_id=${userId}`)
            }
          >
            <Icon name="plus" size={13} />{" "}
            {T.analyticsAddChannel || "Add channel"}
          </button>
        </div>
      )}

      {channels.length === 0 && <ConnectChannelCard userId={userId} />}

      {channels.length > 0 && (
        <>
          {analyticsLoading && (
            <div
              style={{
                padding: "60px 0",
                textAlign: "center",
                color: "var(--fg-faint)",
              }}
            >
              {T.analyticsLoading || "Loading analytics…"}
            </div>
          )}

          {error && !analyticsLoading && (
            <div
              style={{
                padding: "20px",
                borderRadius: "var(--radius)",
                background: "rgba(220,38,38,0.08)",
                color: "var(--bad)",
                fontSize: 13,
                marginBottom: 24,
              }}
            >
              {error}
            </div>
          )}

          {analytics && !analyticsLoading && summary && (
            <>
              {/* ── 1. Все 6 метрик в одну строку ── */}
              <div
                className="kpi-grid"
                style={{
                  gridTemplateColumns: "repeat(6, 1fr)",
                  marginBottom: 24,
                }}
              >
                <StatCard
                  label={T.analyticsViews || "Views"}
                  value={window.fmtNum(summary.views)}
                  sub={`${T.analyticsLast || "last"} ${days} ${T.analyticsDays || "days"}`}
                />
                <StatCard
                  label={T.analyticsWatchTime || "Watch time"}
                  value={`${window.fmtNum(Math.round(summary.watchMinutes / 60))}h`}
                  sub={T.analyticsHoursWatched || "hours watched"}
                />
                <StatCard
                  label={T.analyticsAvgRetention || "Avg. retention"}
                  value={fmtPct(summary.avgRetention)}
                  sub={T.analyticsAvgViewPct || "average view %"}
                />
                <StatCard
                  label={T.analyticsNetSubs || "Net subscribers"}
                  value={`+${window.fmtNum(summary.subsGained - summary.subsLost)}`}
                  sub={`${window.fmtNum(summary.subsGained)} ${T.analyticsGained || "gained"}`}
                />
                <StatCard
                  label={T.analyticsAvgDuration || "Avg. duration"}
                  value={fmtSeconds(summary.avgDuration)}
                  sub="min:sec"
                />
                <StatCard
                  label={T.analyticsLikes || "Likes"}
                  value={window.fmtNum(summary.likes)}
                  sub={T.analyticsTotal || "total"}
                />
              </div>

              {/* ── 2. График просмотров — полная ширина ── */}
              <div className="card" style={{ marginBottom: 24 }}>
                <div className="card-header">
                  <h3>{T.analyticsViewsPerDay || "Views per day"}</h3>
                  <span className="help">
                    {days} {T.analyticsDays || "days"}
                  </span>
                </div>
                <div className="card-body">
                  <DailyChart data={analytics.analytics} />
                </div>
              </div>

              {/* ── 3. Топ видео — полная ширина ── */}
              <TopVideosTable data={analytics.top_videos} days={days} />

              {/* ── 4. Аудитория (слева) + Источники трафика (справа) ── */}
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 16,
                  marginBottom: 24,
                }}
              >
                <div className="card">
                  <div className="card-header">
                    <h3>{T.analyticsAudience || "Audience"}</h3>
                  </div>
                  <div className="card-body">
                    <AudienceInsights data={analytics.audience} />
                  </div>
                </div>
                <div className="card">
                  <div className="card-header">
                    <h3>{T.analyticsTrafficSources || "Traffic sources"}</h3>
                  </div>
                  <div className="card-body">
                    <TrafficSourcesTable data={analytics.traffic_sources} />
                  </div>
                </div>
              </div>
            </>
          )}
        </>
      )}
    </div>
  );
};

Object.assign(window, { AnalyticsScreen });
