import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';

/* NavStylePanel (via useNodeProp/LinkPicker in this file) needs useEditor
   from @craftjs/core and usePages from PageContext. Mock both following the
   DOM-harness pattern used across this repo's other *StylePanel tests (no
   @testing-library/react here) -- PageContext itself is Wave-2's territory,
   this package only READS pages via usePages(), so mocking it is the
   correct boundary for these tests. */
const setPropSpy = vi.fn((_id: string, updater: (p: any) => void) => {
  updater(lastProps);
});
let lastProps: any;

vi.mock('@craftjs/core', () => ({
  useEditor: () => ({ actions: { setProp: setPropSpy } }),
}));

let mockPages: { id: string; name: string; slug: string; craftState: string | null }[] = [];
vi.mock('../../../state/PageContext', () => ({
  usePages: () => ({ pages: mockPages }),
}));

vi.mock('../../../ui/AssetPicker', () => ({
  AssetPicker: () => null,
}));

import { NavStylePanel, LinkPicker, pageHref } from './NavStylePanel';

let container: HTMLDivElement;
let root: Root;

function render(ui: React.ReactElement) {
  container = document.createElement('div');
  document.body.appendChild(container);
  act(() => {
    root = createRoot(container);
    root.render(ui);
  });
}

function rerender(ui: React.ReactElement) {
  act(() => { root.render(ui); });
}

function unmount() {
  act(() => { root.unmount(); });
  container.remove();
}

function setValue(el: HTMLInputElement | HTMLSelectElement, value: string) {
  const proto = el instanceof HTMLSelectElement ? window.HTMLSelectElement.prototype : window.HTMLInputElement.prototype;
  const setter = Object.getOwnPropertyDescriptor(proto, 'value')!.set!;
  act(() => {
    setter.call(el, value);
    el.dispatchEvent(new Event('input', { bubbles: true }));
    el.dispatchEvent(new Event('change', { bubbles: true }));
  });
}

function click(el: Element | null) {
  act(() => { (el as HTMLElement).dispatchEvent(new MouseEvent('click', { bubbles: true })); });
}

beforeEach(() => {
  setPropSpy.mockClear();
  mockPages = [
    { id: 'home', name: 'Home', slug: 'index', craftState: null },
    { id: 'about', name: 'About', slug: 'about', craftState: null },
  ];
});

afterEach(() => {
  if (container) unmount();
});

describe('pageHref (landing page is always "/")', () => {
  test('index 0 (landing page) -> "/"', () => {
    expect(pageHref(mockPages[0], 0)).toBe('/');
  });

  test('any other page -> "/{slug}"', () => {
    expect(pageHref(mockPages[1], 1)).toBe('/about');
  });
});

describe('LinkPicker (F1: link-to-page picker + manual URL/anchor/tel/mailto)', () => {
  test('a value matching a page href starts in "Page" mode and lists every page', () => {
    render(<LinkPicker value="/about" onChange={vi.fn()} />);
    const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
    expect(modeSelect.value).toBe('page');
    const optionText = Array.from(container.querySelectorAll('option')).map((o) => o.textContent);
    expect(optionText).toContain('Home');
    expect(optionText).toContain('About');
  });

  test('picking a different page from the page dropdown emits that page\'s href', () => {
    const onChange = vi.fn();
    render(<LinkPicker value="/about" onChange={onChange} />);
    const [, pageSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
    setValue(pageSelect, '/');
    expect(onChange).toHaveBeenCalledWith('/');
  });

  test('a "#section" value starts in Anchor mode', () => {
    render(<LinkPicker value="#pricing" onChange={vi.fn()} />);
    const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
    expect(modeSelect.value).toBe('anchor');
    const input = container.querySelector('input[type="text"]') as HTMLInputElement;
    expect(input.value).toBe('#pricing');
  });

  test('switching mode to Anchor seeds a bare "#"', () => {
    const onChange = vi.fn();
    render(<LinkPicker value="/about" onChange={onChange} />);
    const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
    setValue(modeSelect, 'anchor');
    expect(onChange).toHaveBeenCalledWith('#');
  });

  test('mailto: helper strips the scheme for editing and re-adds it on change', () => {
    const onChange = vi.fn();
    render(<LinkPicker value="mailto:foo@example.com" onChange={onChange} />);
    const input = container.querySelector('input[type="text"]') as HTMLInputElement;
    expect(input.value).toBe('foo@example.com');
    setValue(input, 'bar@example.com');
    expect(onChange).toHaveBeenCalledWith('mailto:bar@example.com');
  });

  test('tel: helper strips the scheme for editing and re-adds it on change', () => {
    const onChange = vi.fn();
    render(<LinkPicker value="tel:5551234567" onChange={onChange} />);
    const input = container.querySelector('input[type="text"]') as HTMLInputElement;
    expect(input.value).toBe('5551234567');
    setValue(input, '5559876543');
    expect(onChange).toHaveBeenCalledWith('tel:5559876543');
  });

  test('a plain https:// URL falls back to Custom URL mode', () => {
    render(<LinkPicker value="https://example.com" onChange={vi.fn()} />);
    const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
    expect(modeSelect.value).toBe('url');
  });
});

describe('NavStylePanel Links section: href set via LinkPicker (F1 wired into the panel)', () => {
  test('choosing a page for a Navbar link writes that page\'s href onto the link', () => {
    lastProps = {
      links: [{ text: 'Home', href: '/old-home' }],
    };
    render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);

    const selects = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
    // First select for the one link item is its LinkPicker mode select (the
    // href starts as a Custom URL, so it opens on "url" mode); switch it to
    // "page" then pick the About page from the resulting page dropdown.
    const modeSelect = selects[0];
    setValue(modeSelect, 'page');
    expect(setPropSpy).toHaveBeenCalled();
    expect(lastProps.links[0].href).toBe('/'); // defaults to the first page

    // The mock setProp mutates `lastProps` in place rather than triggering a
    // real Craft.js state update, so force a re-render (passing the same,
    // now-mutated, object) to get the LinkPicker to reflect its new "page"
    // mode and render the page <select>.
    rerender(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);

    const pageSelect = Array.from(container.querySelectorAll('select'))[1] as HTMLSelectElement;
    setValue(pageSelect, '/about');
    expect(lastProps.links[0].href).toBe('/about');
  });

  test('toggling the Download checkbox for a link sets download:true', () => {
    lastProps = { links: [{ text: 'Brochure', href: '/brochure.pdf' }] };
    render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
    const checkbox = container.querySelector('input[type="checkbox"]') as HTMLInputElement;
    act(() => { checkbox.click(); });
    expect(lastProps.links[0].download).toBe(true);
  });
});

describe('NavStylePanel: "Sync links with Pages" (F2, regression vs legacy builder)', () => {
  test('populates links from the mocked pages list and preserves the CTA link', () => {
    lastProps = {
      links: [
        { text: 'Old Home', href: '/old' },
        { text: 'Old About', href: '/old-about' },
        { text: 'Get Started', href: '#signup', isCta: true },
      ],
    };
    render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);

    const syncBtn = Array.from(container.querySelectorAll('button'))
      .find((b) => b.textContent?.includes('Sync links with Pages'))!;
    expect(syncBtn).toBeTruthy();
    click(syncBtn);

    expect(lastProps.links).toEqual([
      { text: 'Home', href: '/' },
      { text: 'About', href: '/about' },
      { text: 'Get Started', href: '#signup', isCta: true },
    ]);
  });

  test('with no CTA link, sync just replaces links 1:1 with the pages list', () => {
    lastProps = { links: [{ text: 'Stale', href: '/stale' }] };
    render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);

    const syncBtn = Array.from(container.querySelectorAll('button'))
      .find((b) => b.textContent?.includes('Sync links with Pages'))!;
    click(syncBtn);

    expect(lastProps.links).toEqual([
      { text: 'Home', href: '/' },
      { text: 'About', href: '/about' },
    ]);
  });

  test('the Links section (and its Sync button) is not shown for Footer (no `links` prop)', () => {
    lastProps = { text: '© 2026' };
    render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
    const syncBtn = Array.from(container.querySelectorAll('button'))
      .find((b) => b.textContent?.includes('Sync links with Pages'));
    expect(syncBtn).toBeUndefined();
  });
});

/** The Spacing/Border & Effects/Animation/Visibility CollapsibleSections all
 *  default closed (defaultOpen={false}, matching the pre-existing "Spacing"
 *  section's convention) -- open one by clicking its header button before
 *  asserting on / interacting with its contents. */
function openSection(title: string) {
  const header = Array.from(container.querySelectorAll('button'))
    .find((b) => b.textContent?.includes(title))!;
  click(header);
}

describe('NavStylePanel: box-model + animation + visibility controls always present', () => {
  test('Spacing (Margin/Padding), Border & Effects, Animation, and Visibility sections render for a Navbar', () => {
    lastProps = {
      backgroundColor: '#ffffff',
      style: {},
      animation: 'none',
      animationDelay: '0',
      hideOnDesktop: false,
      hideOnTablet: false,
      hideOnMobile: false,
    };
    render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
    openSection('Spacing');
    openSection('Border & Effects');
    openSection('Animation');
    openSection('Visibility');
    expect(container.querySelector('[data-testid="spacing-control"]')).toBeTruthy();
    expect(container.querySelector('[data-testid="border-control"]')).toBeTruthy();
    expect(container.querySelector('[data-testid="animation-control"]')).toBeTruthy();
    expect(container.querySelector('[data-testid="visibility-control"]')).toBeTruthy();
  });

  test('checking "Hide on Mobile" writes hideOnMobile:true via setProp', () => {
    lastProps = { hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false };
    render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
    openSection('Visibility');
    const checkbox = container.querySelector('[data-testid="visibility-hideOnMobile"]') as HTMLInputElement;
    act(() => {
      checkbox.click();
    });
    expect(lastProps.hideOnMobile).toBe(true);
  });

  test('picking an entrance animation writes animation via setProp', () => {
    lastProps = { animation: 'none', animationDelay: '0' };
    render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
    openSection('Animation');
    const fadeInBtn = Array.from(container.querySelectorAll('[data-testid="animation-control"] button'))
      .find((b) => b.textContent === 'Fade In')!;
    click(fadeInBtn);
    expect(lastProps.animation).toBe('fade-in');
  });
});
