import { EMPTY_EMAIL_PERFORMANCE } from '@/lib/domain/pilot-network'
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { renderToString as reactRenderToString } from 'react-dom/server'

// Client components call the app router; there is none in a server render test.
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: () => {}, refresh: () => {} }), useSearchParams: () => new URLSearchParams() }))
/** SSR separates adjacent text nodes with `<!-- -->`; strip them so assertions read like the screen. */
const renderToString = (el: Parameters<typeof reactRenderToString>[0]) => reactRenderToString(el).replace(/<!--.*?-->/g, '')
import { PilotInvitationManager } from '@/app/admin/pilot-invitations/pilot-invitation-manager'
import { ClaimForm } from '@/app/pilot/claim/[token]/claim-form'
import type { PilotProfile } from '@/lib/domain/pilot-network'

/** Pilot Invitation Manager + claim page render on server with sample data (2026-09-14). */

const lead: PilotProfile = {
  id: '11111111-1111-4111-8111-111111111111', name: 'Michael Remala', company_name: 'Immanuel PCS, LLC', email: 'mremala@yahoo.com', phone: '(480) 244-2636',
  primary_state: 'AK', related_states: ['AK'], account_type: 'unknown', claim_status: 'unclaimed', invitation_status: 'imported', email_opt_in_status: 'not_opted_in', sms_opt_in_status: 'not_opted_in',
  source: 'pilotcarloads.com', source_reference: 'AK listing', last_contacted_at: null, next_follow_up_at: null, claimed_user_id: null, claimed_company_id: null, claimed_at: null, admin_notes: null,
  claim_token: 'a'.repeat(48), unsubscribe_token: 'b'.repeat(48), created_at: '2026-09-14T00:00:00Z', updated_at: '2026-09-14T00:00:00Z',
  capabilities: [
    { capability_type_id: 'c1', key: 'high_pole', label: 'High Pole', group: 'position', data_status: 'imported' },
    { capability_type_id: 'c2', key: 'third_car', label: 'Third Car', group: 'position', data_status: 'imported' },
  ],
  suppression_reason: null,
}
const noCompany: PilotProfile = { ...lead, id: '22222222-2222-4222-8222-222222222222', name: 'Jermond Thompson', company_name: null, email: 'isathompsonjermond@gmail.com' }

describe('Pilot Invitation Manager', () => {
  it('shows the migration banner when the tables are missing', () => {
    const html = renderToString(createElement(PilotInvitationManager, { available: false, states: ['AK'] }))
    expect(html).toContain('Migration 0018 is not applied')
  })
  it('renders the eight summary cards, the leads table with — for a missing company, and the statuses', () => {
    const html = renderToString(
      createElement(PilotInvitationManager, {
        available: true,
        states: ['AK', 'AZ', 'TX'],
        summary: { total: 4, unclaimed: 4, approved: 0, invitations_sent: 0, claimed: 0, opted_in: 0, unsubscribed: 0, bounced_invalid: 0 },
        leads: { profiles: [lead, noCompany], total: 2, page: 1, pageSize: 50 },
        filters: { q: '', state: '', capabilities: [], status: '', page: 1 },
        capabilityTypes: [{ id: 'c1', key: 'high_pole', label: 'High Pole', group: 'position', sort_order: 30, active: true }, { id: 'c9', key: 'witpac', label: 'WITPAC', group: 'certification', sort_order: 110, active: true }],
        campaigns: [],
        templates: [{ id: 't1', key: 'pilot_invitation_initial', name: 'Initial Pilot Invitation', subject: 's', body: 'b', cta_text: 'Claim My Pilot Profile', footer: null, unsubscribe_text: null, active: true, updated_by: null, updated_at: null }],
        analytics: { total_imported: 4, invitations_sent: 0, claimed: 0, opted_in: 0, unsubscribed: 0, bounced: 0, bounce_rate: null, claim_conversion_rate: null, by_state: [{ state: 'AK', count: 4 }], by_capability: [{ label: 'High Pole', count: 4 }], email: EMPTY_EMAIL_PERFORMANCE },
        audit: [],
        settings: { cron_enabled: false, last_run_at: null, last_run_summary: null, updated_by: null, updated_at: null },
      }),
    )
    for (const card of ['Total Pilot Leads', 'Unclaimed Profiles', 'Approved for Invitation', 'Invitations Sent', 'Profiles Claimed', 'Opted Into Alerts', 'Unsubscribed', 'Bounced / Invalid Emails']) expect(html).toContain(card)
    expect(html).toContain('Michael Remala')
    expect(html).toContain('Immanuel PCS, LLC')
    expect(html).toContain('Jermond Thompson')
    expect(html).toContain('<td class="px-3 py-2">—</td>')
    expect(html).toContain('Imported')
    expect(html).toContain('Daily send cron')
    expect(html).toContain('Run today’s batch')
    expect(html).not.toContain('pilotcarloads.com')
    // Nash, 2026-09-14: certifications are not pilot car types — not shown on the leads.
    expect(html).toContain('High Pole')
    expect(html).not.toContain('WITPAC')
  })
})

describe('Claim page form (§20–§22)', () => {
  it('shows the imported data, the two account types, the capability check and an unchecked opt-in', () => {
    const html = renderToString(
      createElement(ClaimForm, {
        token: 'a'.repeat(48),
        initial: { name: 'Jermond Thompson', company_name: null, email: 'isathompsonjermond@gmail.com', phone: '(832) 229-1089', states: ['AK'], capabilities: [{ key: 'lead', label: 'Lead', group: 'position' }, { key: 'high_pole', label: 'High Pole', group: 'position' }] },
        capabilityTypes: [{ key: 'lead', label: 'Lead', group: 'position' }, { key: 'high_pole', label: 'High Pole', group: 'position' }, { key: 'chase', label: 'Chase', group: 'position' }, { key: 'witpac', label: 'WITPAC', group: 'certification' }],
        states: ['AK', 'AZ'],
      }),
    )
    expect(html).toContain('What describes you?')
    expect(html).toContain('Pilot Driver')
    expect(html).toContain('Pilot Company / Pilot Dispatch')
    expect(html).toContain('We currently have the following capabilities associated with your profile.')
    expect(html).toContain('✓ Lead')
    expect(html).toContain('Add more')
    expect(html).toContain('Chase')
    expect(html).not.toContain('WITPAC')
    expect(html).toContain('Claim My Pilot Profile')
    expect(html).not.toMatch(/type="checkbox"[^>]*checked=""/)
    expect(html).not.toContain('pilotcarloads')
  })
})
