// biome-ignore lint/suspicious/noExplicitAny: Story type must be concrete to be rendered by CSF tooling
import type { Meta, StoryObj } from '../../../story.types';
import { ColumnToggle } from './column-toggle.component';

// biome-ignore lint/suspicious/noExplicitAny: Story type must be concrete to be rendered by CSF tooling
type Story = StoryObj<ColumnToggle<any>>;

const meta: Meta<ColumnToggle<unknown>> = {
  title: '@aurora/components/data-table/column-toggle',
  component: ColumnToggle,
  tags: ['autodocs'],
  argTypes: {
    table: {
      control: false,
      description:
        'TanStack `Table<T>` instance. Built by the host via `useDataTable` or `usePaginatedDataTable`. The toggle reads `table.getAllColumns()` to render items, and writes back via `column.pin(...)`, `column.toggleVisibility()`, and `table.setColumnOrder(...)`.',
    },
    columns: {
      control: false,
      description:
        'Array of `LabeledColumn` (`{ key, label }`). Resolved labels come from `getToggleableColumns(baseColumns)`; the toggle does NOT translate keys itself — the host passes already-translated labels (typically reactive via Transloco function form).',
    },
    tableId: {
      control: 'text',
      description:
        'Optional disambiguator for two tables on the same route. The persistence key is `au-data-table-state:<router.url>:<tableId>`. Default empty; set when a route hosts more than one `<au-column-toggle>` (e.g., a manager + a sibling list).',
    },
  },
  args: {
    tableId: '',
  },
  parameters: {
    aurora: {
      category: 'data-table',
      when: "A popover that lets the user manage column visibility, reorder columns within their zone (sticky-left or scrollable), pin/unpin columns, and reset to declared defaults. State is persisted in localStorage by route+tableId so the user's layout survives reloads.",
      whenNot:
        'If the consumer wants no user customization (a fixed table), do NOT mount this component. Layout/sticky stays controlled exclusively by the column definitions in that case.',
    },
  },
};

export default meta;

export const Default: Story = {
  name: 'Default (with declared sticky columns)',
  parameters: {
    docs: {
      description: {
        story:
          "Standard render: the popover lists every column. Columns whose `DataTableColumnDef` declared `sticky: 'left'` (typically `actions` and `select` in list pages) appear in the upper sticky zone with a HARD lock indicator (lock icon with a small dot) — clicking the indicator does nothing because dev-declared sticky is non-removable. Other columns appear in the scroll zone below a divider, each with an open lock icon that the user can click to pin them.",
      },
    },
  },
};

export const PinnedByUser: Story = {
  name: 'User-pinned column (soft lock)',
  parameters: {
    docs: {
      description: {
        story:
          "After the user clicks the open lock on a column not declared `sticky`, that column moves to the upper sticky zone with a NORMAL lock icon. Clicking that lock again unpins the column and returns it to the scroll zone. The user can pin any number of columns; soft-locked columns can be reordered within the sticky zone via drag.\n\nA `play` interaction (when Storybook is reintroduced) should verify: (1) clicking unlock on a scroll-zone item moves it to the sticky zone with `column.getIsPinned() === 'left'`; (2) clicking the resulting lock unpins it; (3) the item NEVER appears between the dev-declared stickies and the scroll boundary in a non-contiguous way.",
      },
    },
  },
};

export const TwoZoneDragAndDrop: Story = {
  name: 'Two-zone drag & drop (no cross-zone)',
  parameters: {
    docs: {
      description: {
        story:
          'Drag and drop is rendered as TWO independent `cdkDropList`s separated by a horizontal divider. They are NOT connected via `cdkDropListConnectedTo`, so CDK rejects any drag attempt that crosses the divider — the dragged item snaps back to its original position. To move a column between zones, the user MUST click the lock indicator. This guarantees the invariant "pinned columns form a contiguous group at the chosen edge".\n\nWithin each zone, drag-and-drop reorders freely. After a drop, `table.setColumnOrder([...stickyOrder, ...scrollOrder])` is called with the combined array; TanStack respects the order while keeping pinned columns at the start.',
      },
    },
  },
};

export const PersistedState: Story = {
  name: 'Persisted state (localStorage by route+tableId)',
  parameters: {
    docs: {
      description: {
        story:
          'On every change to pinning, visibility, or order, the toggle serializes `{ columnPinning, columnVisibility, columnOrder }` to `localStorage` under the key `au-data-table-state:<router.url>:<tableId>`. On component init, if a persisted entry exists for that key, the toggle restores the state into TanStack BEFORE rebuilding its own item list — the table renders with the user\'s saved layout on first frame.\n\n"Reset to default" removes the storage entry AND restores the defaults captured at first init (the pinning derived from `colDef.sticky`, plus the original visibility and column order). Restoration is wrapped in `try/catch` so a corrupted entry does not crash the component; it simply falls back to defaults.',
      },
    },
  },
};

export const PinnedWidthWarning: Story = {
  name: 'Soft warning when pinned width > 50% of viewport',
  parameters: {
    docs: {
      description: {
        story:
          'Whenever the sum of pinned-column widths exceeds 50% of `window.innerWidth`, a non-blocking warning appears next to the popover header — a small `lucideTriangleAlert` icon plus the rounded percentage. The warning is purely informational: the user can keep pinning additional columns even when the warning is active. Useful when the user accidentally pins multiple wide columns and the scroll zone becomes cramped.',
      },
    },
  },
};
