import type { Meta, StoryObj } from '@storybook/vue3-vite';
import { defineComponent, h } from 'vue';

const ThemePlaceholder = defineComponent({
  name: 'ThemePlaceholder',
  render() {
    return h('div');
  },
});

const meta: Meta<typeof ThemePlaceholder> = {
  title: 'CSS utility/Hover Layer',
  component: ThemePlaceholder,
  tags: ['autodocs'],
  parameters: {
    layout: 'fullscreen',
  },
};

export default meta;
type Story = StoryObj<typeof ThemePlaceholder>;

const copyScript = `
  function copyToClipboard(text, el) {
    navigator.clipboard.writeText(text).then(() => {
      el.classList.add('copied');
      setTimeout(() => el.classList.remove('copied'), 1500);
    });
  }
`;

const HOVER_VARIANTS = ['subtle', 'default', 'strong'] as const;
type HoverVariant = (typeof HOVER_VARIANTS)[number];

const EXAMPLES: Array<{
  title: string;
  description: string;
  baseClass: string;
  contentClass: string;
  borderClass: string;
  hoverClass?: string;
  activeClass?: string;
}> = [
  {
    title: 'Background Surface',
    description: 'Hover layer over a surface background.',
    baseClass: 'bg-background-surface-primary',
    contentClass: 'text-content-on-surface-primary',
    borderClass: 'border-border-surface-default',
  },
  {
    title: 'Content On Button',
    description: 'Hover layer behind button foreground content.',
    baseClass: 'bg-background-button-primary-button',
    contentClass: 'text-content-on-button-primary-button',
    borderClass: 'border-transparent',
  },
  {
    title: 'Bordered Control',
    description: 'Hover layer with an explicit border token.',
    baseClass: 'bg-transparent',
    contentClass: 'text-content-on-surface-primary',
    borderClass: 'border-border-button-outlined',
  },
  {
    title: 'No Existing Background Color',
    description:
      'Use muted-subtle as the hover fill when the component has no background.',
    baseClass: 'bg-transparent',
    contentClass: 'text-content-on-surface-primary',
    borderClass: 'border-border-button-outlined',
    hoverClass: 'hover:bg-background-surface-muted-subtle',
    activeClass: 'bg-background-surface-muted-subtle',
  },
];

const renderCopyCode = (text: string): string => `
  <code
    class="copy-btn label-12-regular text-content-on-surface-muted inline-block px-1 py-0.5 rounded"
    onclick="copyToClipboard('${text}', this)"
  >${text}</code>
`;

const renderPreview = (
  example: (typeof EXAMPLES)[number],
  variant: HoverVariant,
): string => {
  const hoverClass = `hover-layer hover-layer-${variant}`;
  const className = `${example.baseClass} ${example.contentClass} ${example.borderClass} border ${hoverClass} hover-layer-active`;
  return `
    <td class="p-3 align-top">
      <div class="flex flex-col gap-2">
        <button
          type="button"
          class="${className} h-16 w-36 rounded-md px-3 body-14-medium"
        >
          <span>${variant}</span>
        </button>
        ${renderCopyCode(`${example.baseClass} ${hoverClass}`)}
      </div>
    </td>
  `;
};

const renderFixedHoverPreview = (
  example: (typeof EXAMPLES)[number],
): string => {
  const hoverClass = example.hoverClass ?? '';
  const activeClass = example.activeClass ?? '';
  const className = `${example.baseClass} ${example.contentClass} ${example.borderClass} border ${hoverClass} ${activeClass}`;
  return `
    <td class="p-3 align-top" colspan="${HOVER_VARIANTS.length}">
      <div class="flex flex-col gap-2">
        <button
          type="button"
          class="${className} h-16 w-36 rounded-md px-3 body-14-medium"
        >
          <span>hover</span>
        </button>
        ${renderCopyCode(hoverClass)}
      </div>
    </td>
  `;
};

const renderExampleRow = (example: (typeof EXAMPLES)[number]): string => `
  <tr class="border-b border-border-surface-default last:border-b-0">
    <td class="p-3 align-top">
      <div class="body-14-medium text-content-on-surface-primary">${example.title}</div>
      <p class="label-12-regular text-content-on-surface-muted mt-1">${example.description}</p>
    </td>
    ${
      example.hoverClass
        ? renderFixedHoverPreview(example)
        : HOVER_VARIANTS.map((variant) => renderPreview(example, variant)).join(
            '',
          )
    }
  </tr>
`;

/**
 * General hover layer utilities. Combine a base surface/content/border class
 * with `hover-layer hover-layer-{subtle|default|strong}`. The hover state is
 * painted by a shared `::after` layer using the current overlay hover token.
 */
export const All: Story = {
  render: () => ({
    template: `
      <div class="p-8 bg-white dark:bg-background min-h-screen">
        <style>
          .copy-btn { cursor: pointer; transition: all 0.15s; }
          .copy-btn:hover { background: rgba(0,0,0,0.05); }
          .copy-btn.copied { background: #22c55e22; }
          .copy-btn.copied::after { content: ' ✓'; color: #22c55e; }
        </style>
        <script>${copyScript}</script>

        <div class="mb-6">
          <h2 class="heading-s text-content-on-surface-primary mb-1">Hover Layer</h2>
          <p class="body-14-regular text-content-on-surface-muted max-w-3xl">
            Use <code class="label-12-medium">hover-layer</code> with
            <code class="label-12-medium">hover-layer-subtle</code>,
            <code class="label-12-medium">hover-layer-default</code>, or
            <code class="label-12-medium">hover-layer-strong</code>.
            The layer is rendered with <code class="label-12-medium">::after</code>
            and uses <code class="label-12-medium">overlay-hover-*</code> tokens directly.
          </p>
          <div class="mt-4 max-w-3xl rounded-md border border-border-surface-default bg-background-surface-muted p-4">
            <h3 class="body-14-bold text-content-on-surface-primary mb-2">Hover Anatomy</h3>
            <div class="grid gap-3 md:grid-cols-2">
              <div>
                <p class="label-12-medium text-content-on-surface-primary mb-1">No existing background color</p>
                <p class="label-12-regular text-content-on-surface-muted">
                  State: Hover<br />
                  Fill 1: <code class="label-12-medium">hover:bg-background-surface-muted-subtle</code>
                </p>
              </div>
              <div>
                <p class="label-12-medium text-content-on-surface-primary mb-1">Existing background color</p>
                <p class="label-12-regular text-content-on-surface-muted">
                  State: Hover<br />
                  Fill 1: inherited from the component<br />
                  Fill 2: <code class="label-12-medium">hover-layer hover-layer-subtle</code>,
                  <code class="label-12-medium">hover-layer hover-layer-default</code>, or
                  <code class="label-12-medium">hover-layer hover-layer-strong</code>
                </p>
              </div>
            </div>
            <p class="label-12-regular text-content-on-surface-muted mt-3">
              The design team defines hover strength at component level based on the underlying base color.
              Always check which strength the component uses before changing it.
            </p>
          </div>
        </div>

        <div class="overflow-x-auto">
          <table class="w-full border-collapse text-left">
            <thead>
              <tr class="border-b border-border-surface-default">
                <th class="p-3 label-12-medium text-content-on-surface-muted font-medium">Example</th>
                <th class="p-3 label-12-medium text-content-on-surface-muted font-medium">Subtle</th>
                <th class="p-3 label-12-medium text-content-on-surface-muted font-medium">Default</th>
                <th class="p-3 label-12-medium text-content-on-surface-muted font-medium">Strong</th>
              </tr>
            </thead>
            <tbody>
              ${EXAMPLES.map(renderExampleRow).join('')}
            </tbody>
          </table>
        </div>
      </div>
    `,
  }),
};
