// @vitest-environment node
import { describe, expect, it } from 'vitest'
import { createElement } from 'react'
import { renderToString as reactRenderToString } from 'react-dom/server'

/** 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 { PilotCompanyDashboard } from '@/app/pd-dashboard/pilot-company-dashboard'
import { PilotDriverView } from '@/app/pc-dashboard/pilot-driver-view'
import { PilotSignupWizard } from '@/app/(auth)/signup/pilot/pilot-signup-wizard'
import { PilotAssignmentWorkspace as PilotTripWorkspace } from '@/components/app/pilot-assignment/pilot-assignment-workspace'

/**
 * Server-render smoke test for the three pilot car replica screens
 * (2026-09-12). They run on demo data, so a render that throws or drops a
 * rule the article states is caught here without a signed-in browser.
 */
describe('pilot car replica screens render', () => {
  it('Pilot Dispatch dashboard shows the §38 tabs and hides the rate confirmation', () => {
    const html = renderToString(createElement(PilotCompanyDashboard))
    for (const tab of ['All Assignments', 'Pilot Drivers', 'Vehicles / Units', 'Documents', 'Company Profile', 'Billing / Plan']) {
      expect(html).toContain(tab)
    }
    expect(html).toContain('ABC Pilot Cars')
    expect(html).toContain('Business License Due in 22 Days')
    expect(html).toContain('Design preview')
  })

  it('Pilot Driver interface has the driver panes plus the extra Profile & Docs tab', () => {
    const html = renderToString(createElement(PilotDriverView))
    for (const pane of ['My Assignments', 'Active Assignment', 'Agent', 'Carrier Info', 'My Pilot Car']) {
      expect(html).toContain(pane)
    }
    // §18: the unshared PA permit on HH-2041 must not leak its details.
    expect(html).not.toContain('PA-OS-55120')
    expect(html).toContain('Not shared with you')
    // §44: the agent refuses the hidden document.
    expect(html).toContain('not available for your role')
    // Carrier Info pane: driver, dispatcher, truck, trailer, load — for record keeping.
    expect(html).toContain('Luis Fernandez')
    expect(html).toContain('Kevin Ortiz')
    expect(html).toContain('Goldhofer THP/SL 13-axle')
    expect(html).toContain('186,000 lbs')
    // Truck / trailer identification for legal follow-up: VIN, plate, registration state.
    expect(html).toContain('1XPBD49X1MD756021')
    expect(html).toContain('WA TRL 99835')
    // Unit number first, then year make model; no separate registration-state line.
    expect(html).toContain('Unit 412')
    expect(html).not.toContain('Registration state')
    // The three per-state links, same as the carrier driver.
    expect(html).toContain('View permit')
    expect(html).toContain('View provisions')
    expect(html).toContain('View state notes')
    // My Vehicle now lives inside My Pilot Car.
    expect(html).toContain('My Vehicle · step 5')
    // Agent pane is the carrier driver's ChatPanel (offline): the state selector offers the
    // shared state only — no "Whole trip" option on state-level access.
    expect(html).toContain('<option value="OH" selected="">OH</option>')
    expect(html).toContain('Tap to talk')
    expect(html).not.toContain('Whole trip')
    // Invoices & expenses live in My Pilot Car; Free owner → visible but locked (§24).
    expect(html).toContain('Invoices &amp; expenses — HH-2041')
    expect(html).toContain('Create Invoice - Pro Feature')
    expect(html).toContain('Upgrade to Pro')
  })

  it('Pilot signup starts on the driver-or-company question and is three steps', () => {
    const html = renderToString(createElement(PilotSignupWizard))
    expect(html).toContain('Are you signing up as a Pilot Driver or a Pilot Company?')
    expect(html).toContain('1. Account type')
    expect(html).toContain('2. Details')
    expect(html).toContain('3. Validate email')
    expect(html).not.toContain('4. ')
    expect(html).toContain('inside your dashboard')
    expect(html).not.toContain('Password')
  })

  it('a just-signed-up pilot driver sees steps 4–6 as unfinished tasks and can still open the assignment', () => {
    const html = renderToString(createElement(PilotDriverView, { fresh: true }))
    expect(html).toContain('Unfinished setup')
    expect(html).toContain('Step 4 · Required documents')
    expect(html).toContain('Step 5 · Your vehicle')
    expect(html).toContain('Step 6 · Capabilities')
    // reminder above the shared states on the assignment, permits still shown
    expect(html).toContain('Finish your setup')
    expect(html).toContain('OH-SL-88214')
    expect(html).toContain('only you can upload these')
  })

  it('a just-signed-up pilot company sees its setup tasks on the assignments tab', () => {
    const html = renderToString(createElement(PilotCompanyDashboard, { fresh: true }))
    expect(html).toContain('Unfinished setup')
    expect(html).toContain('Step 5 · Pilot units')
    expect(html).toContain('No assignments in this view')
  })

  it('pilot dispatch without a business license is blocked from the trip workspace', () => {
    const html = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'asg-1', as: 'pilot_company' }))
    expect(html).toContain('Upload your company documents before opening this trip')
    expect(html).toContain('Business license')
    expect(html).not.toContain('OH-SL-88214')
    expect(html).not.toContain('Admin bypass')
    // Internal admin gets the bypass button on the gate (Nash, 2026-09-12).
    const admin = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'asg-1', as: 'pilot_company', isAdmin: true }))
    expect(admin).toContain('Admin bypass')
  })

  it('pilot driver on a decide-later invitation sees no permits and can add only a dispatch', () => {
    const html = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'asg-5', as: 'pilot_driver', initialTab: 'people' }))
    expect(html).toContain('Nothing shared yet — carrier will decide')
    expect(html).not.toContain('OH-SL-88410')
    expect(html).toContain('Add pilot dispatch to this trip')
    expect(html).toContain('A pilot driver can add only their pilot dispatch')
  })

  it('pilot driver with Ohio state access sees Ohio only and inherits that access when adding people', () => {
    const html = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'asg-1', as: 'pilot_driver', initialTab: 'people' }))
    expect(html).toContain('OH-SL-88214')
    expect(html).not.toContain('PA-OS-55120')
    expect(html).toContain('access: OH (state)')
  })

  it('pilot dispatch trip workspace has a My Pilot tab with the plan-gated tools', () => {
    const html = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'asg-4', as: 'pilot_company', initialTab: 'my-pilot' }))
    // asg-4 dispatch view is blocked by the documents gate in the default demo; the driver view is not.
    const driverHtml = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'asg-1', as: 'pilot_driver', initialTab: 'my-pilot' }))
    expect(html + driverHtml).toContain('My Pilot')
    // Owner (ABC Pilot Cars) is on Free in the default preview → visible but locked (§24).
    expect(driverHtml).toContain('Create Invoice - Pro Feature')
    expect(driverHtml).toContain('Invoice owner: <span class="font-semibold">ABC Pilot Cars</span>')
  })

  it('carrier sees pilots, states, car and invoices; broker sees name/contact/state only', () => {
    const carrier = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'asg-1', as: 'carrier' }))
    expect(carrier).toContain('Dana Whitfield')
    expect(carrier).toContain('PC-01')
    expect(carrier).toContain('Pilot invoices for this trip')
    const broker = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'asg-1', as: 'broker' }))
    expect(broker).toContain('Dana Whitfield')
    expect(broker).not.toContain('PC-01')
    expect(broker).not.toContain('Pilot invoices for this trip')
    // Broker-arranged pilot (asg-3) → broker may see invoices.
    const brokerArranged = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'asg-3', as: 'broker' }))
    expect(brokerArranged).toContain('Pilot invoices for this trip')
  })
})

describe('"My Pilot" tab — pilot paperwork for brokers and carriers (Nash, 2026-09-13)', () => {
  it('pilot-preview carrier view lists the paperwork, the purpose line, the free window and the missing-paperwork alert', async () => {
    const html = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'HH-2041', as: 'carrier', isAdmin: true }))
    expect(html).toContain('brokers, carrier dispatchers and drivers')
    expect(html).toContain('Free for your first 90 days')
    expect(html).toContain('Certificate of insurance')
    expect(html).toContain('Missing paperwork: Business license missing')
    expect(html).toContain('Open Certificate of insurance PDF')
    expect(html).toContain('Your plan')
    expect(html).not.toContain('Starter Feature')
  })
  it('the broker view shows the paperwork too', async () => {
    const html = renderToString(createElement(PilotTripWorkspace, { assignmentKey: 'HH-2041', as: 'broker', isAdmin: true }))
    expect(html).toContain('Open Certificate of insurance PDF')
  })
  it('the locked card renders for a Free account after the 90 days', async () => {
    const { MyPilotTab } = await import('@/components/app/pilot-tools/my-pilot-tab')
    const pilots = [{ name: 'Mark Cuban', kind: 'Pilot dispatch' as const, phone: '', email: 'x@y', access: 'States: NM', states: ['NM'], status: 'Joined', documents: [] }]
    const locked = renderToString(createElement(MyPilotTab, { viewer: 'carrier', pilots, invoices: [], showInvoices: true, paperwork: { mode: 'locked' }, paperworkPlan: 'Free' }))
    expect(locked).toContain('Pilot paperwork - Starter Feature')
    expect(locked).toContain('Upgrade to Starter')
    expect(locked).toContain('Your free 90-day window has ended.')
    expect(locked).not.toContain('Open Certificate')
    const included = renderToString(createElement(MyPilotTab, { viewer: 'broker', pilots, invoices: [], showInvoices: false, paperwork: { mode: 'included' } }))
    expect(included).toContain('Included in your plan')
  })
})
