import { readFileSync } from 'fs';
import { render, screen, waitFor } from '@testing-library/react';
import ProfileSettingsModal from '@/app/components/ProfileSettingsModal';

describe('profile UI layout regressions', () => {
  const originalFetch = global.fetch;

  afterEach(() => {
    global.fetch = originalFetch;
    jest.resetAllMocks();
  });

  it('does not render the Telegram relink instruction block in profile settings', async () => {
    global.fetch = jest.fn().mockResolvedValue({
      ok: true,
      json: async () => ({
        telegram: {
          telegramId: '123456',
          telegramChatId: '123456',
          telegramUsername: 'tester',
          telegramLinkedAt: '2026-04-24T00:00:00.000Z',
        },
        botUrl: 'https://t.me/test_bot',
        clickNotifications: {
          hasBotToken: false,
          featureAvailableByPlan: true,
          canSendToUserNow: false,
        },
      }),
    }) as unknown as typeof fetch;

    render(<ProfileSettingsModal isOpen onClose={jest.fn()} />);

    await waitFor(() => {
      expect(screen.getByText('Уведомления о кликах')).toBeInTheDocument();
    });

    expect(screen.queryByText('Как перепривязать Telegram')).not.toBeInTheDocument();
    expect(screen.queryByText('Как привязать Telegram')).not.toBeInTheDocument();
    expect(screen.queryByText('Логика совпадает с входом в панель: ссылка запуска бота + одноразовый код.')).not.toBeInTheDocument();
  });

  it('keeps the link stats period menu outside clipped overflow containers', () => {
    const source = readFileSync('app/components/profile/ProfileLinkStatsView.tsx', 'utf8');

    expect(source).not.toContain('relative overflow-hidden rounded-2xl border border-white/10 bg-black/35 p-6');
    expect(source).toContain('relative z-[120] overflow-visible rounded-2xl border border-white/10 bg-black/35 p-6');
    expect(source).toContain('className="absolute right-0 top-[calc(100%+6px)] z-[220]');
  });

  it('centers wrapped filter controls on compact profile link screens', () => {
    const source = readFileSync('app/components/profile/_links/FilterToolbar.tsx', 'utf8');

    expect(source).toContain('col-span-2 grid grid-cols-2 justify-center gap-2 sm:flex sm:w-full sm:flex-wrap sm:items-center sm:justify-center sm:gap-2 lg:ml-auto lg:w-auto lg:justify-end');
    expect(source).not.toContain('col-span-2 grid grid-cols-2 gap-2 sm:ml-auto');
  });

  it('uses measured chart containers before rendering Recharts responsive charts', () => {
    const source = readFileSync('app/components/SafeResponsiveChart.tsx', 'utf8');
    const analytics = readFileSync('app/components/profile/ProfileAnalyticsTab.tsx', 'utf8');
    const overview = readFileSync('app/components/profile/ProfileOverviewTab.tsx', 'utf8');
    const stats = readFileSync('app/components/profile/ProfileLinkStatsView.tsx', 'utf8');

    expect(source).toContain('ResizeObserver');
    expect(source).toContain('size.width >= 16 && size.height >= 16');
    expect(source).toContain('cloneElement(children');
    expect(source).not.toContain('ResponsiveContainer');
    expect(analytics).toContain('<SafeResponsiveChart>');
    expect(overview).toContain('<SafeResponsiveChart>');
    expect(stats).toContain('<SafeResponsiveChart>');
    expect(analytics).not.toContain('<ResponsiveContainer width="100%" height="100%"');
    expect(overview).not.toContain('<ResponsiveContainer width="100%" height="100%"');
    expect(stats).not.toContain('<ResponsiveContainer width="100%" height="100%"');
  });

  it('keeps dashboard and overview data fetches uncached and quietly refreshed', () => {
    const dashboardRoute = readFileSync('app/api/profile/dashboard/route.ts', 'utf8');
    const overviewRoute = readFileSync('app/api/profile/overview/route.ts', 'utf8');
    const dashboardHook = readFileSync('app/profile/hooks/useProfileDashboardData.ts', 'utf8');
    const overviewHook = readFileSync('app/profile/hooks/useProfileOverviewData.ts', 'utf8');
    const overviewTab = readFileSync('app/components/profile/ProfileOverviewTab.tsx', 'utf8');
    const analyticsTab = readFileSync('app/components/profile/ProfileAnalyticsTab.tsx', 'utf8');
    const linksRequestCache = readFileSync('app/components/profile/_links/requestCache.ts', 'utf8');
    const linksTab = readFileSync('app/components/profile/ProfileLinksTab.tsx', 'utf8');

    expect(dashboardRoute).toContain("'Cache-Control': 'no-store'");
    expect(overviewRoute).toContain("'Cache-Control': 'no-store'");
    expect(overviewRoute).not.toContain('stale-while-revalidate');
    expect(dashboardHook).toContain("fetch('/api/profile/dashboard', { cache: 'no-store' })");
    expect(overviewHook).toContain("fetch(`/api/profile/overview?period=${period}`, { cache: 'no-store' })");
    expect(dashboardHook).toContain('window.setInterval(refresh, 15_000)');
    expect(overviewHook).toContain('window.setInterval(refresh, 15_000)');
    expect(overviewTab).toContain("fetch(`/api/profile/overview?period=${period}`, { cache: 'no-store' })");
    expect(analyticsTab).toContain("fetch(`/api/profile/overview?period=${period}`, { cache: 'no-store' })");
    expect(overviewTab).toContain("fetchPeriodData(selectedPeriod, { force: true, showLoader: false })");
    expect(analyticsTab).toContain("fetchPeriodData(selectedPeriod, { force: true, showLoader: false })");
    expect(linksRequestCache).toContain("fetch(requestUrl, { cache: 'no-store', signal })");
    expect(linksTab).toContain("fetch('/api/tags', { cache: 'no-store' })");
  });

  it('uses concise tariff warning text inside advanced link settings', () => {
    const createDialog = readFileSync('app/components/profile/CreateLinkDialog.tsx', 'utf8');
    const editDialog = readFileSync('app/components/profile/EditLinkDialog.tsx', 'utf8');

    expect(createDialog).toContain('className="text-xs text-amber-300">Недоступно на текущем тарифе.</p>');
    expect(editDialog).toContain('className="text-xs text-amber-300">Недоступно на текущем тарифе.</p>');
    expect(createDialog).not.toContain('На текущем тарифе расширенные поля недоступны.');
    expect(editDialog).not.toContain('На текущем тарифе расширенные поля недоступны.');
  });
});
