---
import type { BundledLanguage } from 'shiki';

import ServerCode from '@/components/Code/ServerCode.astro';
import { Tab, TabsList, TabsPanel, TabsRoot } from '@/components/Tabs';

interface FileTab {
  title: string;
  code: string;
  lang: BundledLanguage;
}

interface Props {
  files: FileTab[];
}

const { files } = Astro.props;

function hash(input: string): string {
  let value = 5381;
  for (let i = 0; i < input.length; i++) {
    value = ((value << 5) + value) ^ input.charCodeAt(i);
  }
  return Math.abs(value >>> 0).toString(36);
}

const cssFile = files.find((file) => file.lang === 'css');
const scopeSeed = files.map((file) => `${file.title}:${file.lang}\n${file.code}`).join('\n\n');
const scopeId = cssFile ? `demo-${hash(scopeSeed)}` : null;
const scopedCss = cssFile && scopeId ? `@scope ([data-demo-scope="${scopeId}"]) {\n${cssFile.code}\n}` : null;
---

<div
  class="mx-auto my-6 flex w-full max-w-3xl flex-col overflow-hidden rounded-xs border border-faded-black dark:border-manila-dark"
>
  {scopedCss && <style is:inline set:html={scopedCss} />}
  <div
    class="relative z-20 bg-manila-light dark:bg-faded-black"
    data-demo-scope={scopeId}
  >
    <slot />
  </div>
  <TabsRoot
    client:idle
    maxWidth={false}
    className="my-0 rounded-none border-0 border-t border-faded-black dark:border-manila-dark"
  >
    <TabsList client:idle label="Demo source code">
      {
        files.map((file, i) => (
          <Tab client:idle value={file.title} initial={i === 0}>
            {file.title}
          </Tab>
        ))
      }
    </TabsList>
    {
      files.map((file, i) => (
        <TabsPanel client:idle value={file.title} initial={i === 0}>
          <ServerCode code={file.code} lang={file.lang} />
        </TabsPanel>
      ))
    }
  </TabsRoot>
</div>
