/**
 * R7FE-009: TrialExpirationBanner uses localYmd() for the daily dedupe key.
 *
 * The daily dedupe key (warningStorageKey) must reflect the user's LOCAL date,
 * not UTC. A user in UTC-5 sees their local date advance at local midnight, not
 * at 7pm UTC (5h early).
 */
import { render } from '@testing-library/react';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';

// vi.mock is hoisted by Vitest's transform. To spy on localYmd we use the
// module factory form (string literal — no variable reference allowed at hoist time).
vi.mock('@/lib/format', () => ({
  localYmd: vi.fn().mockReturnValue('2026-06-11'),
  formatDateTime: (v: string) => v,
}));

// Mock analytics so no real calls fire.
vi.mock('@/lib/analytics', () => ({ trackEvent: vi.fn() }));
vi.mock('@/lib/event-catalog', () => ({
  TRIAL_BANNER_DISMISSED: 'trial_banner_dismissed',
  TRIAL_BANNER_SHOWN: 'trial_banner_shown',
  TRIAL_BANNER_UPGRADE_CLICKED: 'trial_banner_upgrade_clicked',
  UPGRADE_CLICKED: 'upgrade_clicked',
}));

vi.mock('@inertiajs/react', () => ({
  usePage: vi.fn(() => ({
    props: {
      features: { billing: true },
      trial: { active: true, daysRemaining: 5 },
      limits: null,
    },
  })),
  Link: ({ children, href }: { children: React.ReactNode; href: string }) => (
    <a href={href}>{children}</a>
  ),
}));

vi.mock('@/Components/billing/BillingLink', () => ({
  BillingLink: ({ children, onClick, className }: { children: React.ReactNode; onClick?: () => void; className?: string }) => (
    <button onClick={onClick} className={className}>{children}</button>
  ),
}));

import * as formatLib from '@/lib/format';

import { TrialExpirationBanner } from './TrialExpirationBanner';

describe('TrialExpirationBanner — R7FE-009 localYmd dedupe key', () => {
  beforeAll(() => {
    localStorage.clear();
  });

  afterAll(() => {
    localStorage.clear();
  });

  it('R7FE-009: calls localYmd() to build the daily dedupe key (not UTC toISOString)', () => {
    vi.mocked(formatLib.localYmd).mockClear();
    render(<TrialExpirationBanner />);
    // localYmd() must have been called to construct todayKey().
    expect(formatLib.localYmd).toHaveBeenCalled();
  });

  it('R7FE-009: the dismissal storage key uses the localYmd value', () => {
    vi.mocked(formatLib.localYmd).mockReturnValue('2026-06-11');
    const expectedKey = 'trial_banner_warning_dismissed_2026-06-11';
    localStorage.setItem(expectedKey, 'true');

    // With the warning key dismissed, the warning banner should NOT render.
    const { container } = render(<TrialExpirationBanner />);
    // The banner is suppressed when warningDismissed===true; no warning-border element.
    expect(container.querySelector('[class*="warning-border"]')).toBeNull();

    localStorage.removeItem(expectedKey);
  });
});
