"use client";

/**
 * PticaShell — cockpit chrome: sticky topbar (ПТИЦА wordmark + 4 tab buttons,
 * active state driven by props) and a left rail of 7 icon+label nav buttons,
 * plus a mono timestamp footer.
 *
 * The rail mirrors the prototype (ptica-redesign/app.js RAIL_TARGET): five
 * `scroll` items jump to a cockpit section by element id, two `tab` items switch
 * the top tab. A `scroll` item first activates the analysis tab (if needed) and
 * scrolls on the next frame so the target is mounted before scrollIntoView runs.
 *
 * The timestamp is rendered only after mount (useState gated by an effect) to
 * avoid an SSR/client hydration mismatch on the clock value. The effect drives a
 * UI clock — no HTTP — which is the allowed use of useEffect here.
 */

import { useEffect, useState } from "react";
import Link from "next/link";

import styles from "@/app/site-finder/analysis/[cad]/ptica/ptica.module.css";

export type PticaTab = "analysis" | "scenarios" | "reports" | "compare";

interface TabDef {
  id: PticaTab;
  label: string;
}

const TABS: TabDef[] = [
  { id: "analysis", label: "Анализ участка" },
  { id: "scenarios", label: "Сценарии" },
  { id: "reports", label: "Отчёты" },
  { id: "compare", label: "Сравнение" },
];

type RailItem =
  | {
      key: string;
      label: string;
      icon: React.ReactNode;
      kind: "scroll";
      target: string;
    }
  | {
      key: string;
      label: string;
      icon: React.ReactNode;
      kind: "tab";
      target: PticaTab;
    };

const RAIL: RailItem[] = [
  {
    key: "parcel",
    label: "Участок",
    kind: "scroll",
    target: "ptica-hero",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <circle cx="12" cy="12" r="8" stroke="currentColor" strokeWidth="1.5" />
        <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="1.5" />
        <path
          d="M12 2v3M12 19v3M2 12h3M19 12h3"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
        />
      </svg>
    ),
  },
  {
    key: "potential",
    label: "Потенциал",
    kind: "scroll",
    target: "ptica-potential",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path
          d="M4 16l5-5 4 3 7-8"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
        <path
          d="M16 6h4v4"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    ),
  },
  {
    key: "product",
    label: "Продукт",
    kind: "scroll",
    target: "ptica-product",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path
          d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3z"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinejoin="round"
        />
        <path
          d="M4 7.5l8 4.5 8-4.5M12 12v9"
          stroke="currentColor"
          strokeWidth="1.2"
          opacity="0.7"
        />
      </svg>
    ),
  },
  {
    key: "economy",
    label: "Экономика",
    kind: "scroll",
    target: "ptica-economy",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path
          d="M4 20V10M10 20V5M16 20v-7M22 20H2"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
        />
      </svg>
    ),
  },
  {
    key: "risks",
    label: "Риски",
    kind: "scroll",
    target: "ptica-risks",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path
          d="M12 4l8 14H4L12 4z"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinejoin="round"
        />
        <path
          d="M12 10v4M12 16.5v.5"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
        />
      </svg>
    ),
  },
  {
    key: "compare",
    label: "Сравнение",
    kind: "tab",
    target: "compare",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <rect
          x="3"
          y="5"
          width="7"
          height="14"
          rx="1.5"
          stroke="currentColor"
          strokeWidth="1.5"
        />
        <rect
          x="14"
          y="5"
          width="7"
          height="14"
          rx="1.5"
          stroke="currentColor"
          strokeWidth="1.5"
        />
      </svg>
    ),
  },
  {
    key: "reports",
    label: "Отчёты",
    kind: "tab",
    target: "reports",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path
          d="M6 3h8l4 4v14H6V3z"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinejoin="round"
        />
        <path
          d="M14 3v4h4M9 13h6M9 16h6"
          stroke="currentColor"
          strokeWidth="1.2"
          strokeLinecap="round"
        />
      </svg>
    ),
  },
];

const BirdMark = ({ className }: { className: string }) => (
  <svg className={className} viewBox="0 0 40 40" fill="none" aria-hidden="true">
    <path
      d="M6 15 C14 13 18 17 20 23 C22 17 26 13 34 15 C27 17 23 22 20 30 C17 22 13 17 6 15 Z"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinejoin="round"
    />
  </svg>
);

/** Toggle native fullscreen for the whole document (topbar fullscreen icon). */
function toggleFullscreen() {
  if (typeof document === "undefined") return;
  if (document.fullscreenElement) {
    void document.exitFullscreen?.();
  } else {
    void document.documentElement.requestFullscreen?.();
  }
}

interface Props {
  activeTab: PticaTab;
  onTabChange: (tab: PticaTab) => void;
  children: React.ReactNode;
}

export function PticaShell({ activeTab, onTabChange, children }: Props) {
  const [clock, setClock] = useState<string | null>(null);
  // Last clicked scroll target, used to highlight the matching rail item while
  // the analysis tab is active. Defaults to the hero (Участок).
  const [activeScroll, setActiveScroll] = useState<string>("ptica-hero");

  function handleRailClick(item: RailItem) {
    if (item.kind === "tab") {
      onTabChange(item.target);
      return;
    }
    setActiveScroll(item.target);
    if (activeTab !== "analysis") {
      onTabChange("analysis");
      requestAnimationFrame(() => {
        document
          .getElementById(item.target)
          ?.scrollIntoView({ behavior: "smooth", block: "start" });
      });
      return;
    }
    document
      .getElementById(item.target)
      ?.scrollIntoView({ behavior: "smooth", block: "start" });
  }

  function isRailActive(item: RailItem): boolean {
    if (item.kind === "tab") return activeTab === item.target;
    return activeTab === "analysis" && activeScroll === item.target;
  }

  useEffect(() => {
    function tick() {
      const now = new Date();
      const hh = String(now.getHours()).padStart(2, "0");
      const mm = String(now.getMinutes()).padStart(2, "0");
      const ss = String(now.getSeconds()).padStart(2, "0");
      setClock(`${hh}:${mm}:${ss}`);
    }
    tick();
    const id = window.setInterval(tick, 1000);
    return () => window.clearInterval(id);
  }, []);

  return (
    <div className={styles.shell}>
      {/* ── Left rail ───────────────────────────────────────────────── */}
      <aside className={styles.rail}>
        <div className={styles.brand}>
          <BirdMark className={styles.brandMark} />
        </div>
        <nav className={styles.nav} aria-label="Разделы анализа">
          {RAIL.map((item) => (
            <button
              key={item.key}
              type="button"
              className={`${styles.navItem} ${
                isRailActive(item) ? styles.navItemActive : ""
              }`}
              aria-current={isRailActive(item) ? "true" : undefined}
              onClick={() => handleRailClick(item)}
            >
              {item.icon}
              <span>{item.label}</span>
            </button>
          ))}
        </nav>
        <div className={styles.navFoot}>
          <div className={styles.mono} suppressHydrationWarning>
            DATA
            <br />
            {clock ?? "—"}
          </div>
          <button
            type="button"
            className={styles.helpDot}
            title="Справка — скоро"
            aria-label="Справка"
            aria-disabled="true"
          >
            ?
          </button>
        </div>
      </aside>

      {/* ── Main column ─────────────────────────────────────────────── */}
      <div className={styles.main}>
        <header className={styles.topbar}>
          <Link
            href="/site-finder"
            className={styles.wordmark}
            aria-label="На главную — Site Finder"
          >
            <BirdMark className={styles.bird} />
            <div>
              <div className={styles.wordmarkTitle}>ПТИЦА</div>
              <div className={styles.wordmarkSub}>
                платформа территориального
                <br />
                информационно-цифрового анализа
              </div>
            </div>
          </Link>
          <nav className={styles.tabs} aria-label="Режимы">
            {TABS.map((tab) => (
              <button
                key={tab.id}
                type="button"
                className={`${styles.tab} ${
                  activeTab === tab.id ? styles.tabActive : ""
                }`}
                aria-current={activeTab === tab.id ? "page" : undefined}
                onClick={() => onTabChange(tab.id)}
              >
                {tab.label}
              </button>
            ))}
          </nav>
          <div className={styles.sysbar}>
            <div className={styles.clock} suppressHydrationWarning>
              <b>{clock ?? "—"}</b>
            </div>
            <button
              type="button"
              className={styles.iconBtn}
              title="Экспорт / отчёты"
              aria-label="Экспорт — открыть отчёты"
              onClick={() => onTabChange("reports")}
            >
              <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path
                  d="M12 3v12m0 0l-4-4m4 4l4-4M4 17v3h16v-3"
                  stroke="currentColor"
                  strokeWidth="1.6"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </button>
            <button
              type="button"
              className={styles.iconBtn}
              title="Настройки — скоро"
              aria-label="Настройки"
              aria-disabled="true"
            >
              <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <circle
                  cx="12"
                  cy="12"
                  r="3.2"
                  stroke="currentColor"
                  strokeWidth="1.6"
                />
                <path
                  d="M12 2.5l1.4 2.2 2.5-.7.6 2.6 2.6.6-.7 2.5 2.2 1.4-2.2 1.4.7 2.5-2.6.6-.6 2.6-2.5-.7L12 21.5l-1.4-2.2-2.5.7-.6-2.6-2.6-.6.7-2.5L3.4 13l2.2-1.4-.7-2.5 2.6-.6.6-2.6 2.5.7L12 2.5z"
                  stroke="currentColor"
                  strokeWidth="1.4"
                  strokeLinejoin="round"
                />
              </svg>
            </button>
            <button
              type="button"
              className={styles.iconBtn}
              title="Полный экран"
              aria-label="Полный экран"
              onClick={toggleFullscreen}
            >
              <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path
                  d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"
                  stroke="currentColor"
                  strokeWidth="1.6"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </button>
          </div>
        </header>

        <div className={styles.canvas}>{children}</div>

        <footer className={styles.appFooter}>
          <span>
            ПТИЦА · платформа территориального информационно-цифрового анализа
          </span>
          <span>
            Не является публичной офертой · информация носит оценочный характер
          </span>
        </footer>
      </div>
    </div>
  );
}
