"use client";

import React, { useEffect, useRef, useState } from "react";
import { ExternalLink } from "lucide-react";

// ── Types ─────────────────────────────────────────────────────────────────────

interface SubSection {
  id: string;
  label: string;
}

interface NavSection {
  id: string;
  label: string;
  sub?: SubSection[];
}

// ── Config ────────────────────────────────────────────────────────────────────

const NAV_SECTIONS: NavSection[] = [
  { id: "section-1", label: "1. Объект" },
  { id: "section-2", label: "2. Земля и риски" },
  {
    id: "section-3",
    label: "3. Рынок",
    sub: [
      { id: "section-3-1", label: "3.1 Настройки выборки" },
      { id: "section-3-2", label: "3.2 Планировки" },
      { id: "section-3-3", label: "3.3 Остатки и скорость" },
    ],
  },
  { id: "section-4", label: "4. Оценка" },
  { id: "section-5", label: "5. Атмосфера" },
  {
    id: "section-6",
    label: "6. Прогноз",
    sub: [
      { id: "section-6-1", label: "6.1 Прогноз по горизонтам" },
      { id: "section-6-2", label: "6.2 Сценарии" },
      { id: "section-6-3", label: "6.3 Уверенность" },
      { id: "section-6-4", label: "6.4 Рекомендация по продукту" },
      { id: "section-6-5", label: "6.5 Прозрачность скоринга" },
      { id: "section-6-6", label: "6.6 Будущее предложение и конкуренты" },
    ],
  },
];

// All section IDs in scroll order (for IntersectionObserver)
const ALL_SECTION_IDS: string[] = NAV_SECTIONS.flatMap((s) =>
  s.sub ? [s.id, ...s.sub.map((sub) => sub.id)] : [s.id],
);

// ── Component ─────────────────────────────────────────────────────────────────

export function AnalysisSidebar() {
  const [activeId, setActiveId] = useState<string>(ALL_SECTION_IDS[0]);
  const observerRef = useRef<IntersectionObserver | null>(null);

  // Scrollspy via IntersectionObserver
  useEffect(() => {
    const candidates = ALL_SECTION_IDS.map((id) =>
      document.getElementById(id),
    ).filter((el): el is HTMLElement => el !== null);

    if (candidates.length === 0) return;

    // Track which sections are visible; pick topmost visible one
    const visible = new Set<string>();

    observerRef.current = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            visible.add(entry.target.id);
          } else {
            visible.delete(entry.target.id);
          }
        });

        // Pick the topmost section that is currently visible
        const next = ALL_SECTION_IDS.find((id) => visible.has(id));
        if (next) setActiveId(next);
      },
      {
        root: null,
        // Trigger when section top enters top 60% of viewport
        rootMargin: "-8px 0px -40% 0px",
        threshold: 0,
      },
    );

    candidates.forEach((el) => observerRef.current!.observe(el));

    return () => {
      observerRef.current?.disconnect();
    };
  }, []);

  function handleAnchorClick(
    e: React.MouseEvent<HTMLAnchorElement>,
    targetId: string,
  ) {
    e.preventDefault();
    const el = document.getElementById(targetId);
    if (el) {
      el.scrollIntoView({ behavior: "smooth", block: "start" });
    }
    setActiveId(targetId);
  }

  return (
    <aside
      style={{
        width: 240,
        flexShrink: 0,
        background: "var(--bg-card)",
        borderRight: "1px solid var(--border-card)",
        padding: "16px 12px",
        display: "flex",
        flexDirection: "column",
        gap: 4,
        position: "sticky",
        top: 56,
        height: "calc(100vh - 56px)",
        overflowY: "auto",
      }}
    >
      {/* Section label */}
      <p
        style={{
          fontSize: 12,
          fontWeight: 500,
          textTransform: "uppercase",
          letterSpacing: "0.04em",
          color: "var(--fg-tertiary)",
          margin: "0 0 8px",
          padding: "0 4px",
        }}
      >
        Навигация
      </p>

      {/* Nav items */}
      {NAV_SECTIONS.map((section) => {
        const isParentActive =
          activeId === section.id ||
          section.sub?.some((s) => s.id === activeId);

        return (
          <div key={section.id}>
            <a
              href={`#${section.id}`}
              onClick={(e) => handleAnchorClick(e, section.id)}
              style={{
                display: "block",
                padding: "7px 10px",
                borderRadius: 8,
                fontSize: 13,
                fontWeight: isParentActive ? 600 : 400,
                color: isParentActive ? "var(--accent)" : "var(--fg-secondary)",
                background: isParentActive
                  ? "var(--accent-soft)"
                  : "transparent",
                textDecoration: "none",
                transition: "background 100ms, color 100ms",
                lineHeight: 1.4,
              }}
            >
              {section.label}
            </a>

            {/* Sub-sections */}
            {section.sub && (
              <div
                style={{
                  paddingLeft: 12,
                  marginTop: 2,
                  display: "flex",
                  flexDirection: "column",
                  gap: 2,
                }}
              >
                {section.sub.map((sub) => {
                  const isSubActive = activeId === sub.id;
                  return (
                    <a
                      key={sub.id}
                      href={`#${sub.id}`}
                      onClick={(e) => handleAnchorClick(e, sub.id)}
                      style={{
                        display: "block",
                        padding: "5px 10px",
                        borderRadius: 6,
                        fontSize: 12,
                        fontWeight: isSubActive ? 600 : 400,
                        color: isSubActive
                          ? "var(--accent)"
                          : "var(--fg-tertiary)",
                        background: isSubActive
                          ? "var(--accent-soft)"
                          : "transparent",
                        textDecoration: "none",
                        transition: "background 100ms, color 100ms",
                        lineHeight: 1.4,
                      }}
                    >
                      {sub.label}
                    </a>
                  );
                })}
              </div>
            )}
          </div>
        );
      })}

      {/* Sources footer */}
      <div
        style={{
          marginTop: "auto",
          paddingTop: 16,
          borderTop: "1px solid var(--border-soft)",
        }}
      >
        <p
          style={{
            fontSize: 11,
            fontWeight: 500,
            textTransform: "uppercase",
            letterSpacing: "0.04em",
            color: "var(--fg-tertiary)",
            margin: "0 0 6px",
            padding: "0 4px",
          }}
        >
          Источники
        </p>
        {[
          { label: "Росреестр / ЕГРН", href: "https://rosreestr.gov.ru" },
          { label: "НСПД", href: "https://nspd.gov.ru" },
          { label: "2ГИС / OSM", href: "https://2gis.ru" },
        ].map(({ label, href }) => (
          <a
            key={label}
            href={href}
            target="_blank"
            rel="noopener noreferrer"
            style={{
              display: "flex",
              alignItems: "center",
              gap: 4,
              padding: "4px 4px",
              fontSize: 11,
              color: "var(--fg-tertiary)",
              textDecoration: "none",
            }}
          >
            <ExternalLink size={10} strokeWidth={1.5} />
            {label}
          </a>
        ))}
      </div>
    </aside>
  );
}
