/* Plans screen — v4 тиры (май 2026) */
/* YOUN-58: живой каталог докупок из /api/purchases/catalog + превью стоимости */

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

const PLANS = window.PLANS || [];

const getTrialDaysLeft = (trialEndsAt) => {
  if (!trialEndsAt) return 0;
  const ends = new Date(trialEndsAt);
  const now = new Date();
  return Math.max(0, Math.ceil((ends - now) / (1000 * 60 * 60 * 24)));
};

const FeatureValue = ({ value, highlighted }) => {
  if (value === true)
    return (
      <span
        style={{
          color: highlighted ? "rgba(255,255,255,0.9)" : "var(--good)",
          fontWeight: 600,
        }}
      >
        ✓
      </span>
    );
  if (value === false)
    return (
      <span
        style={{
          color: highlighted ? "rgba(255,255,255,0.3)" : "var(--fg-faint)",
        }}
      >
        —
      </span>
    );
  return <span style={{ fontSize: 13, fontWeight: 500 }}>{value}</span>;
};

// ── Блок докупок — живой каталог ───────────────────────────────────────────
const AddonsBlock = ({ userId }) => {
  const [catalog, setCatalog] = React.useState(null);
  const [preview, setPreview] = React.useState(null);
  const [previewSku, setPreviewSku] = React.useState(null);
  const [loadingPreview, setLoadingPreview] = React.useState(false);

  React.useEffect(() => {
    fetch(`${API_URL_PLANS}/api/purchases/catalog`)
      .then((r) => r.json())
      .then((d) => setCatalog(d.catalog || {}))
      .catch(() => {});
  }, []);

  const skuRubPrices = {
    ai_runs_1: 390,
    ai_runs_5: 1490,
    oauth_channels: 490,
    team_members: 790,
  };

  const handlePreview = (sku) => {
    if (!userId) {
      const item = catalog[sku];
      if (!item) return;
      setPreviewSku(sku);
      setPreview({
        label: item.label,
        type: item.type,
        price_now_eur: item.price_eur,
        price_now_rub: skuRubPrices[sku] || null,
        price_recurring_eur: item.type !== "ai_runs" ? item.price_eur : 0,
        price_recurring_rub:
          item.type !== "ai_runs" ? skuRubPrices[sku] || null : 0,
        is_recurring: item.type !== "ai_runs",
        period_end: null,
      });
      return;
    }
    setLoadingPreview(true);
    setPreviewSku(sku);
    fetch(`${API_URL_PLANS}/api/purchases/preview?user_id=${userId}&sku=${sku}`)
      .then((r) => r.json())
      .then((d) => {
        const fullRub = skuRubPrices[sku] || null;
        // Пропорциональный расчёт ₽ если есть period_end (середина периода)
        let nowRub = fullRub;
        if (
          fullRub &&
          d.period_end &&
          d.price_now_eur &&
          d.price_recurring_eur
        ) {
          // Считаем пропорцию как EUR: price_now / price_recurring
          const ratio =
            d.price_recurring_eur > 0
              ? d.price_now_eur / d.price_recurring_eur
              : 1;
          nowRub = Math.round(fullRub * ratio);
        }
        setPreview({
          ...d,
          price_now_rub: nowRub,
          price_recurring_rub: d.is_recurring ? fullRub : 0,
        });
        setLoadingPreview(false);
      })
      .catch(() => setLoadingPreview(false));
  };

  const handleClose = () => {
    setPreview(null);
    setPreviewSku(null);
  };

  const rubPrices = {
    ai_runs_1: "₽390",
    ai_runs_5: "₽1 490",
    oauth_channels: "₽490",
    team_members: "₽790",
  };

  if (!catalog)
    return (
      <div
        style={{
          padding: "24px 0",
          textAlign: "center",
          color: "var(--fg-faint)",
          fontSize: 13,
        }}
      >
        {window.T?.loading || "Загружаем…"}
      </div>
    );

  return (
    <div>
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 12,
          marginTop: 16,
        }}
      >
        {Object.entries(catalog).map(([sku, item]) => (
          <div
            key={sku}
            style={{
              padding: "14px 16px",
              border: `1px solid ${previewSku === sku ? "var(--accent)" : "var(--border)"}`,
              borderRadius: "var(--radius)",
              background:
                previewSku === sku ? "var(--accent-soft)" : "var(--bg-elev)",
              transition: "border-color 0.15s",
            }}
          >
            <div
              style={{
                fontSize: 13,
                fontWeight: 500,
                marginBottom: 8,
                lineHeight: 1.4,
              }}
            >
              {(() => {
                const labelMap = {
                  ai_runs_1: window.ADDONS_COPY?.ai_run_1,
                  ai_runs_5: window.ADDONS_COPY?.ai_run_5,
                  oauth_channels: window.ADDONS_COPY?.oauth_channel,
                  team_members: window.ADDONS_COPY?.team_member,
                };
                return labelMap[sku] || item.label;
              })()}
            </div>
            <div
              style={{
                fontSize: 18,
                fontWeight: 700,
                color: "var(--accent)",
                marginBottom: 2,
              }}
            >
              {window.PRODUCT_MODE === "ru" && rubPrices[sku]
                ? rubPrices[sku].replace("/мес", "").replace("₽", "₽")
                : `€${item.price_eur}`}
              {item.type !== "ai_runs" && (
                <span
                  style={{
                    fontSize: 11,
                    fontWeight: 400,
                    color: "var(--fg-faint)",
                  }}
                >
                  {window.ADDONS_COPY?.perMonth || "/мес"}
                </span>
              )}
            </div>
            <div
              style={{
                fontSize: 11,
                color: "var(--fg-faint)",
                marginBottom: 12,
              }}
            ></div>
            <button
              className="btn primary sm"
              style={{ width: "100%" }}
              onClick={() =>
                previewSku === sku ? handleClose() : handlePreview(sku)
              }
            >
              {previewSku === sku
                ? window.ADDONS_COPY?.close || "Закрыть"
                : window.ADDONS_COPY?.details || "Подробнее"}
            </button>
          </div>
        ))}
      </div>

      {previewSku && preview && (
        <div
          style={{
            marginTop: 16,
            padding: "16px 20px",
            borderRadius: "var(--radius)",
            background: "var(--bg-sunk)",
            border: "1px solid var(--border)",
          }}
        >
          {loadingPreview ? (
            <div style={{ fontSize: 13, color: "var(--fg-faint)" }}>
              {window.ADDONS_COPY?.calculating || "Считаем стоимость…"}
            </div>
          ) : (
            <>
              <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 12 }}>
                {(() => {
                  const labelMap = {
                    "1 ран с Claude AI": window.ADDONS_COPY?.ai_run_1,
                    "5 ранов с Claude AI": window.ADDONS_COPY?.ai_run_5,
                    "Доп. YouTube канал (OAuth)":
                      window.ADDONS_COPY?.oauth_channel,
                    "Доп. член команды": window.ADDONS_COPY?.team_member,
                  };
                  return labelMap[preview.label] || preview.label;
                })()}
              </div>
              <div style={{ display: "flex", gap: 32, marginBottom: 14 }}>
                <div>
                  <div
                    style={{
                      fontSize: 11,
                      color: "var(--fg-faint)",
                      marginBottom: 2,
                    }}
                  >
                    {window.ADDONS_COPY?.payNow || "К ОПЛАТЕ СЕЙЧАС"}
                  </div>
                  <div style={{ fontSize: 22, fontWeight: 700 }}>
                    {window.PRODUCT_MODE === "ru" && preview.price_now_rub
                      ? `₽${preview.price_now_rub.toLocaleString()}`
                      : `€${preview.price_now_eur}`}
                  </div>
                  {preview.is_recurring && preview.period_end && userId && (
                    <div
                      style={{
                        fontSize: 11,
                        color: "var(--fg-faint)",
                        marginTop: 2,
                      }}
                    >
                      {window.PRODUCT_MODE === "en" ? "" : "за"}{" "}
                      {Math.max(
                        0,
                        Math.round(
                          (new Date(preview.period_end) - new Date()) /
                            86400000,
                        ),
                      )}{" "}
                      {window.ADDONS_COPY?.daysLeft || "дней до конца периода"}
                    </div>
                  )}
                  {preview.is_recurring && !userId && (
                    <div
                      style={{
                        fontSize: 11,
                        color: "var(--fg-faint)",
                        marginTop: 2,
                      }}
                    >
                      {window.ADDONS_COPY?.fullCost ||
                        "полная стоимость за период"}
                    </div>
                  )}
                </div>
                {preview.is_recurring && (
                  <div>
                    <div
                      style={{
                        fontSize: 11,
                        color: "var(--fg-faint)",
                        marginBottom: 2,
                      }}
                    >
                      {window.ADDONS_COPY?.nextPeriod || "В СЛЕДУЮЩЕМ ПЕРИОДЕ"}
                    </div>
                    <div style={{ fontSize: 22, fontWeight: 700 }}>
                      {window.PRODUCT_MODE === "ru" &&
                      preview.price_recurring_rub
                        ? `₽${preview.price_recurring_rub.toLocaleString()}`
                        : `€${preview.price_recurring_eur}`}
                      <span style={{ fontSize: 12, fontWeight: 400 }}>
                        {window.ADDONS_COPY?.perMonth || "/мес"}
                      </span>
                    </div>
                  </div>
                )}
              </div>
              <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <a
                  href={`mailto:hello@younalyse.app?subject=Докупка: ${preview.label}&body=Хочу докупить: ${preview.label}.${userId ? `%0AМой user_id: ${userId}` : ""}`}
                  className="btn primary sm"
                >
                  {window.ADDONS_COPY?.requestAddon || "Запросить докупку →"}
                </a>
                <button className="btn sm" onClick={handleClose}>
                  {window.ADDONS_COPY?.cancel || "Отмена"}
                </button>
              </div>
              <div
                style={{
                  fontSize: 11,
                  color: "var(--fg-faint)",
                  marginTop: 10,
                }}
              >
                {window.ADDONS_COPY?.manualNote ||
                  "Пока платёжка не подключена — отправьте запрос, зачислим вручную в течение часа."}
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
};

// ── PlansScreen ────────────────────────────────────────────────────────────
const PlansScreen = ({ userProfile, userId }) => {
  const tier = userProfile?.subscription_tier || "trial";
  const trialEndsAt = userProfile?.trial_ends_at;
  const daysLeft = getTrialDaysLeft(trialEndsAt);
  const isTrialExpired = tier === "trial" && daysLeft === 0;
  const isExpired = tier === "expired" || isTrialExpired;
  const [billing, setBilling] = React.useState("monthly");

  const handleUpgrade = (planId) => {
    window.location.href = `mailto:hello@younalyse.app?subject=Upgrade to ${planId}&body=I'd like to upgrade my Younalyse plan to ${planId}.`;
  };

  const price = (plan) => {
    if (billing === "annual")
      return {
        eur: plan.priceEurYear,
        rub: plan.priceRubYear,
        suffix: window.T?.plansPriceSuffixYear || "/год",
        isAnnual: true,
      };
    return {
      eur: plan.priceEur,
      rub: plan.priceRub,
      suffix: window.T?.plansPriceSuffix || "/мес",
      isAnnual: false,
    };
  };

  return (
    <div className="page" style={{ maxWidth: 1200 }}>
      {/* Заголовок */}
      <div
        className="page-header"
        style={{ textAlign: "center", marginBottom: 32 }}
      >
        <h2 style={{ fontSize: 28, marginBottom: 8 }}>
          {window.T?.plansTitle || "Выберите план"}
        </h2>
        <p
          style={{
            fontSize: 15,
            color: "var(--fg-muted)",
            maxWidth: 520,
            margin: "0 auto 20px",
          }}
        >
          {window.T?.plansSubtitle ||
            "Анализируйте YouTube-каналы, исследуйте ключевые слова и получайте AI-инсайты."}
        </p>
        <div className="segmented" style={{ display: "inline-flex" }}>
          <button
            className={billing === "monthly" ? "active" : ""}
            onClick={() => setBilling("monthly")}
          >
            {window.T?.plansMonthly || "Ежемесячно"}
          </button>
          <button
            className={billing === "annual" ? "active" : ""}
            onClick={() => setBilling("annual")}
          >
            {window.T?.plansAnnual || "Ежегодно"}{" "}
            <span
              style={{
                fontSize: 11,
                color: "var(--good)",
                fontWeight: 600,
                marginLeft: 4,
              }}
            >
              −10%
            </span>
          </button>
        </div>

        {tier === "trial" && !isExpired && (
          <div
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 10,
              marginTop: 16,
              padding: "10px 20px",
              background: "var(--accent-soft)",
              border: "1px solid var(--accent)",
              borderRadius: "var(--radius-lg)",
              fontSize: 13,
            }}
          >
            <span>
              {window.T?.plansTrialActive ||
                "🎉 Вы на бесплатном пробном периоде"}
            </span>
            <span style={{ color: "var(--accent)", fontWeight: 600 }}>
              {window.PRODUCT_MODE === "en"
                ? `${daysLeft}d left`
                : `${daysLeft} ${daysLeft === 1 ? "день" : daysLeft < 5 ? "дня" : "дней"} осталось`}
            </span>
          </div>
        )}

        {isExpired && (
          <div
            style={{
              display: "flex",
              justifyContent: "center",
              marginTop: 16,
            }}
          >
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 10,
                padding: "10px 20px",
                background: "rgba(220,38,38,0.08)",
                border: "1px solid var(--bad)",
                borderRadius: "var(--radius-lg)",
                fontSize: 13,
                color: "var(--bad)",
              }}
            >
              {window.T?.plansTrialExpired ||
                "⚠️ Пробный период истёк. Выберите план для продолжения работы."}
            </div>
          </div>
        )}
      </div>

      {/* Карточки тиров */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 16,
          marginBottom: 48,
        }}
      >
        {PLANS.map((plan) => {
          const isCurrent = tier === plan.id;
          const isHighlighted = plan.highlight;
          const p = price(plan);
          return (
            <div
              key={plan.id}
              style={{
                background: isHighlighted ? "var(--accent)" : "var(--bg)",
                border: isCurrent
                  ? "2px solid var(--good)"
                  : isHighlighted
                    ? "none"
                    : "1px solid var(--border)",
                borderRadius: "var(--radius-lg)",
                padding: "24px 20px",
                position: "relative",
                boxShadow: isHighlighted
                  ? "var(--shadow-lg)"
                  : "var(--shadow-sm)",
                display: "flex",
                flexDirection: "column",
              }}
            >
              {isCurrent && (
                <div
                  style={{
                    position: "absolute",
                    top: -12,
                    left: "50%",
                    transform: "translateX(-50%)",
                    background: "var(--good)",
                    color: "white",
                    padding: "3px 14px",
                    borderRadius: 20,
                    fontSize: 11,
                    fontWeight: 600,
                    whiteSpace: "nowrap",
                  }}
                >
                  {window.T?.plansCurrentPlan ||
                    window.T?.plansCurrentPlan ||
                    "Текущий план"}
                </div>
              )}
              {isHighlighted && !isCurrent && (
                <div
                  style={{
                    position: "absolute",
                    top: -12,
                    left: "50%",
                    transform: "translateX(-50%)",
                    background: "white",
                    color: "var(--accent)",
                    padding: "3px 14px",
                    borderRadius: 20,
                    fontSize: 11,
                    fontWeight: 700,
                    whiteSpace: "nowrap",
                  }}
                >
                  {window.T?.plansPopular ||
                    window.T?.plansPopular ||
                    "Популярный"}
                </div>
              )}

              <div style={{ marginBottom: 16 }}>
                <div style={{ fontSize: 26, marginBottom: 4 }}>
                  {plan.emoji}
                </div>
                <div
                  style={{
                    fontSize: 18,
                    fontWeight: 700,
                    color: isHighlighted ? "white" : "var(--fg)",
                    marginBottom: 4,
                  }}
                >
                  {plan.name}
                </div>
                <div
                  style={{
                    fontSize: 12,
                    lineHeight: 1.4,
                    color: isHighlighted
                      ? "rgba(255,255,255,0.7)"
                      : "var(--fg-muted)",
                  }}
                >
                  {plan.description}
                </div>
              </div>

              <div style={{ marginBottom: 20 }}>
                {/* Главная цена */}
                <div
                  style={{ display: "flex", alignItems: "baseline", gap: 8 }}
                >
                  <div
                    style={{
                      fontSize: 32,
                      fontWeight: 800,
                      letterSpacing: "-0.02em",
                      color: isHighlighted ? "white" : "var(--fg)",
                    }}
                  >
                    {window.PRODUCT_MODE === "ru"
                      ? `₽${p.rub.toLocaleString()}`
                      : `€${p.eur}`}
                  </div>
                  {/* Зачёркнутая цена до скидки при annual */}
                  {p.isAnnual && (
                    <div
                      style={{
                        fontSize: 14,
                        color: isHighlighted
                          ? "rgba(255,255,255,0.4)"
                          : "var(--fg-faint)",
                        textDecoration: "line-through",
                      }}
                    >
                      {window.PRODUCT_MODE === "ru"
                        ? `₽${(plan.priceRub * 12).toLocaleString()}`
                        : `€${(plan.priceEur * 12).toFixed(2)}`}
                    </div>
                  )}
                </div>
                <div
                  style={{
                    fontSize: 12,
                    color: isHighlighted
                      ? "rgba(255,255,255,0.6)"
                      : "var(--fg-faint)",
                  }}
                >
                  {p.suffix}
                </div>
              </div>

              {isCurrent ? (
                <div
                  style={{
                    padding: "10px 0",
                    textAlign: "center",
                    fontSize: 13,
                    fontWeight: 500,
                    color: isHighlighted
                      ? "rgba(255,255,255,0.7)"
                      : "var(--good)",
                    marginBottom: 16,
                  }}
                >
                  {window.T?.plansActivePlan || "✓ Активный план"}
                </div>
              ) : (
                <button
                  className={"btn lg" + (isHighlighted ? "" : " primary")}
                  onClick={() => handleUpgrade(plan.id)}
                  style={{
                    width: "100%",
                    marginBottom: 16,
                    background: isHighlighted ? "white" : undefined,
                    color: isHighlighted ? "var(--accent)" : undefined,
                    borderColor: isHighlighted ? "white" : undefined,
                    fontWeight: 600,
                  }}
                >
                  {tier === "trial" || tier === "expired"
                    ? `${window.T?.plansStartWith || window.T?.plansStartWith || "Начать с"} ${plan.name}`
                    : `${window.T?.plansUpgradeTo || window.T?.plansUpgradeTo || "Перейти на"} ${plan.name}`}
                </button>
              )}

              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  gap: 8,
                  flex: 1,
                }}
              >
                {plan.features.map((f, i) => (
                  <div
                    key={i}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      gap: 8,
                      fontSize: 12,
                      color: isHighlighted
                        ? "rgba(255,255,255,0.8)"
                        : "var(--fg-muted)",
                      paddingBottom: 8,
                      borderBottom:
                        i < plan.features.length - 1
                          ? `1px solid ${isHighlighted ? "rgba(255,255,255,0.12)" : "var(--border)"}`
                          : "none",
                    }}
                  >
                    <span>{f.label}</span>
                    <FeatureValue value={f.value} highlighted={isHighlighted} />
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      {/* Докупки — живой каталог */}
      <div className="form-card" style={{ marginBottom: 32 }}>
        <h3 style={{ marginBottom: 4 }}>
          {window.T?.plansAddons || "Докупки"}
        </h3>
        <p className="hint">
          {window.T?.plansAddonsHint ||
            window.T?.plansAddonsHint ||
            "Расширьте возможности без смены плана. Одноразовые или ежемесячные — по выбору."}
        </p>
        <AddonsBlock userId={userId} />
      </div>

      {/* Таблица сравнения */}
      <div className="form-card" style={{ marginBottom: 32 }}>
        <h3 style={{ marginBottom: 4 }}>
          {window.T?.plansFullComparison || "Полное сравнение"}
        </h3>
        <p className="hint">
          {window.T?.plansFullComparisonHint ||
            window.T?.plansFullComparisonHint ||
            "Детальное сравнение всех возможностей."}
        </p>
        <div className="table-scroll" style={{ marginTop: 16 }}>
          <table className="data" style={{ fontSize: 13 }}>
            <thead>
              <tr>
                <th style={{ minWidth: 200, fontWeight: 600 }}>
                  {window.ADDONS_COPY?.paramLabel || "Параметр"}
                </th>
                {PLANS.map((p) => (
                  <th
                    key={p.id}
                    style={{
                      textAlign: "center",
                      color: tier === p.id ? "var(--accent)" : undefined,
                    }}
                  >
                    {p.emoji} {p.name}
                    {tier === p.id && (
                      <span
                        style={{
                          display: "block",
                          fontSize: 10,
                          color: "var(--good)",
                          fontWeight: 400,
                        }}
                      >
                        {window.ADDONS_COPY?.currentLabel || "текущий"}
                      </span>
                    )}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {PLANS[0].features.map((f, i) => (
                <tr key={i}>
                  <td style={{ color: "var(--fg-muted)", fontSize: 12 }}>
                    {f.label}
                  </td>
                  {PLANS.map((p) => (
                    <td key={p.id} style={{ textAlign: "center" }}>
                      <FeatureValue value={p.features[i]?.value} />
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* FAQ */}
      <div style={{ maxWidth: 640, margin: "0 auto" }}>
        <h3
          style={{
            fontSize: 16,
            fontWeight: 600,
            marginBottom: 16,
            textAlign: "center",
          }}
        >
          {window.ADDONS_COPY?.faq || "Часто задаваемые вопросы"}
        </h3>
        {(
          window.ADDONS_COPY?.faqItems || [
            {
              q: "Можно ли сменить план в любое время?",
              a: "Да, вы можете повысить или понизить план в любой момент. Изменения вступают в силу немедленно.",
            },
            {
              q: "Что происходит после окончания триала?",
              a: "После 7 дней триала доступ к анализу ограничивается. Данные сохраняются — выберите подходящий план и продолжите работу.",
            },
            {
              q: "Есть ли скидка при оплате за год?",
              a: "Да, при годовой оплате скидка 10% на любой план.",
            },
            {
              q: "Как работают раны с Claude AI?",
              a: "Claude AI анализирует комментарии и генерирует инсайты. Количество AI ранов включено в каждый план, дополнительные можно докупить по €3.99 за ран.",
            },
            {
              q: "Как считается стоимость периодической докупки?",
              a: "При подключении в середине периода вы платите пропорционально за оставшиеся дни. Со следующего периода — полная стоимость вместе с основной подпиской. При отключении докупка остаётся активной до конца оплаченного периода.",
            },
            {
              q: "Что такое 'Каналов в списке наблюдения'?",
              a: "Это каналы конкурентов, за которыми вы следите. Раны можно запускать по любому каналу — лимит на список наблюдения не влияет на количество ранов.",
            },
          ]
        ).map((item, i, arr) => (
          <div
            key={i}
            style={{
              padding: "16px 0",
              borderBottom:
                i < arr.length - 1 ? "1px solid var(--border)" : "none",
            }}
          >
            <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 6 }}>
              {item.q}
            </div>
            <div
              style={{
                fontSize: 13,
                color: "var(--fg-muted)",
                lineHeight: 1.6,
              }}
            >
              {item.a}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

Object.assign(window, { PlansScreen, getTrialDaysLeft });
