"use client";

import { useState, useEffect, useCallback } from "react";

function SearchIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="11" cy="11" r="8" />
      <path d="M21 21l-4.35-4.35" />
    </svg>
  );
}

function TelegramIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
      <path d="M9.914 13.74l-.395 5.566c.563 0 .805-.243 1.095-.533l2.631-2.488 5.455 3.975c1 .55 1.711.263 1.978-.915l3.582-16.8c.326-1.513-.549-2.103-1.525-1.733L1.52 9.956c-1.472.571-1.45 1.391-.251 1.76l5.7 1.778L19.33 6.34c.6-.366 1.146-.164.697.202" />
    </svg>
  );
}

export default function StickyNav() {
  const [navVisible, setNavVisible] = useState(false);

  const onScroll = useCallback(() => {
    const shouldShow = window.scrollY > window.innerHeight * 0.7;
    setNavVisible((prev) => (prev !== shouldShow ? shouldShow : prev));
  }, []);

  useEffect(() => {
    let ticking = false;
    const handleScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          onScroll();
          ticking = false;
        });
        ticking = true;
      }
    };
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, [onScroll]);

  return (
    <nav
      className={`fixed top-0 left-0 right-0 z-[9999] bg-[#F9F9F7]/95 backdrop-blur-xl border-b border-black/10 px-6 h-14 flex items-center justify-between transition-transform duration-500 ease-out ${
        navVisible ? "translate-y-0" : "-translate-y-full"
      }`}
    >
      <a
        href="/"
        className="font-bold text-sm tracking-wide hover:text-[#7a1b1b] transition-colors"
      >
        Victor Buto
      </a>
      <div className="flex items-center gap-1">
        <a
          href="/#materials"
          className="text-xs font-semibold px-4 py-2 border border-black/10 hover:border-[#7a1b1b] hover:text-[#7a1b1b] transition-colors"
        >
          Все статьи
        </a>
        <button
          className="w-9 h-9 flex items-center justify-center border border-black/10 hover:border-[#7a1b1b] hover:text-[#7a1b1b] transition-colors"
          aria-label="Поиск"
        >
          <SearchIcon />
        </button>
        <a
          href="https://t.me/+apzJx1vMpr84NzYy"
          target="_blank"
          rel="noopener noreferrer"
          className="w-9 h-9 flex items-center justify-center border border-black/10 hover:border-[#7a1b1b] hover:text-[#7a1b1b] transition-colors"
          aria-label="Telegram"
        >
          <TelegramIcon />
        </a>
      </div>
    </nav>
  );
}
