'use client';

import { useRouter } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from '@/lib/i18n';

export type DocEntry = {
  slug: string;
  title: string;
  order: number;
  description: string;
  fallback: boolean;
};

export type DocCategory = {
  slug: string;
  label: string;
  order: number;
  entries: DocEntry[];
};

export type DocsManifest = {
  locale: string;
  rootEntries: DocEntry[];
  categories: DocCategory[];
};

interface DocsSidebarProps {
  manifest: DocsManifest | null;
  activeSlug: string;
  isMobile: boolean;
}

function ChevronDown({ open }: { open: boolean }) {
  return (
    <svg
      width="12"
      height="12"
      viewBox="0 0 12 12"
      fill="none"
      style={{ transform: open ? 'rotate(0deg)' : 'rotate(-90deg)', transition: 'transform 0.15s' }}
    >
      <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function SidebarLink({
  slug,
  title,
  isActive,
  onSelect,
}: {
  slug: string;
  title: string;
  isActive: boolean;
  onSelect: (slug: string) => void;
}) {
  return (
    <button
      onClick={() => onSelect(slug)}
      style={{
        display: 'block',
        width: '100%',
        textAlign: 'left',
        padding: '7px 10px 7px 14px',
        background: isActive ? '#ededf7' : 'none',
        border: 'none',
        borderLeft: isActive ? '2px solid #5c5fbc' : '2px solid transparent',
        cursor: 'pointer',
        fontSize: '13.5px',
        fontWeight: isActive ? 600 : 500,
        color: isActive ? '#5c5fbc' : '#374151',
        borderRadius: '0 6px 6px 0',
        transition: 'background 0.15s, color 0.15s',
      }}
      onMouseEnter={e => {
        if (!isActive) {
          e.currentTarget.style.background = '#f5f5f5';
          e.currentTarget.style.color = '#1a1a2e';
        }
      }}
      onMouseLeave={e => {
        if (!isActive) {
          e.currentTarget.style.background = 'none';
          e.currentTarget.style.color = '#374151';
        }
      }}
    >
      {title}
    </button>
  );
}

function CategoryBlock({
  category,
  activeSlug,
  onSelect,
}: {
  category: DocCategory;
  activeSlug: string;
  onSelect: (slug: string) => void;
}) {
  const hasActive = category.entries.some(e => e.slug === activeSlug);
  const [open, setOpen] = useState<boolean>(true);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    if (hasActive) setOpen(true);
  }, [hasActive]);

  return (
    <div style={{ marginBottom: '8px' }}>
      <button
        onClick={() => setOpen(v => !v)}
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          width: '100%',
          padding: '8px 10px 8px 4px',
          background: 'none',
          border: 'none',
          cursor: 'pointer',
          fontSize: '11.5px',
          fontWeight: 700,
          color: '#6b7280',
          textTransform: 'uppercase',
          letterSpacing: '0.5px',
        }}
      >
        <ChevronDown open={open} />
        <span>{category.label}</span>
      </button>
      {open && (
        <div style={{ paddingLeft: '4px' }}>
          {category.entries.map(entry => (
            <SidebarLink
              key={entry.slug}
              slug={entry.slug}
              title={entry.title}
              isActive={entry.slug === activeSlug}
              onSelect={onSelect}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function SidebarBody({
  manifest,
  activeSlug,
  onSelect,
}: {
  manifest: DocsManifest;
  activeSlug: string;
  onSelect: (slug: string) => void;
}) {
  const { t } = useTranslation();
  return (
    <>
      <SidebarLink
        slug="index"
        title={t('docs.introduction')}
        isActive={activeSlug === 'index' || activeSlug === ''}
        onSelect={onSelect}
      />
      {manifest.rootEntries.map(entry => (
        <SidebarLink
          key={entry.slug}
          slug={entry.slug}
          title={entry.title}
          isActive={entry.slug === activeSlug}
          onSelect={onSelect}
        />
      ))}
      <div style={{ height: '10px' }} />
      {manifest.categories.map(cat => (
        <CategoryBlock key={cat.slug} category={cat} activeSlug={activeSlug} onSelect={onSelect} />
      ))}
    </>
  );
}

export default function DocsSidebar({ manifest, activeSlug, isMobile }: DocsSidebarProps) {
  const router = useRouter();
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const close = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [open]);

  const navigate = (slug: string) => {
    setOpen(false);
    if (slug === 'index' || slug === '') {
      router.push('/docs');
    } else {
      router.push(`/docs/${slug}`);
    }
  };

  if (!manifest) {
    return (
      <aside style={{
        padding: '24px 16px',
        fontSize: '13px',
        color: '#999',
      }}>
        {t('common.loading')}
      </aside>
    );
  }

  if (isMobile) {
    const flat = [
      { slug: 'index', title: t('docs.introduction') },
      ...manifest.rootEntries.map(e => ({ slug: e.slug, title: e.title })),
      ...manifest.categories.flatMap(c =>
        c.entries.map(e => ({ slug: e.slug, title: `${c.label} · ${e.title}` })),
      ),
    ];
    const active = flat.find(item => item.slug === activeSlug) ?? flat[0];

    return (
      <div ref={ref} style={{ position: 'relative', margin: '0 16px 12px' }}>
        <button
          onClick={() => setOpen(v => !v)}
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            width: '100%',
            padding: '10px 14px',
            background: '#fff',
            border: '1px solid #e5e7eb',
            borderRadius: '10px',
            cursor: 'pointer',
            fontSize: '13.5px',
            fontWeight: 600,
            color: '#1a1a2e',
          }}
        >
          <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: '2px' }}>
            <span style={{ fontSize: '10.5px', color: '#888', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
              {t('docs.menu')}
            </span>
            <span>{active.title}</span>
          </span>
          <ChevronDown open={open} />
        </button>
        {open && (
          <div style={{
            position: 'absolute',
            top: 'calc(100% + 6px)',
            left: 0,
            right: 0,
            background: '#fff',
            border: '1px solid #e5e7eb',
            borderRadius: '10px',
            boxShadow: '0 6px 24px rgba(0,0,0,0.08)',
            zIndex: 50,
            maxHeight: '70vh',
            overflowY: 'auto',
            padding: '10px 8px',
          }}>
            <SidebarBody manifest={manifest} activeSlug={activeSlug} onSelect={navigate} />
          </div>
        )}
      </div>
    );
  }

  return (
    <aside style={{
      position: 'sticky',
      top: '52px',
      alignSelf: 'flex-start',
      maxHeight: 'calc(100vh - 52px)',
      overflowY: 'auto',
      padding: '24px 14px 32px 0',
      borderRight: '1px solid #ececf0',
    }}>
      <SidebarBody manifest={manifest} activeSlug={activeSlug} onSelect={navigate} />
    </aside>
  );
}
