// Shared components & icons.

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ── routing (hash-based) ─────────────────────────────────────
function useRoute() {
  const parse = () => {
    const h = (window.location.hash || "#/projects").replace(/^#\/?/, "");
    const parts = h.split("/").filter(Boolean);
    if (parts.length === 0) return { name: "projects" };
    if (parts[0] === "case") return { name: "case", id: parts[1] };
    return { name: parts[0] };
  };
  const [route, setRoute] = useState(parse);
  useEffect(() => {
    const onHash = () => setRoute(parse());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
}

function navigate(hash) {
  window.location.hash = hash;
  // scroll to top smoothly
  window.scrollTo({ top: 0, behavior: "instant" });
}

// ── tiny inline icons ───────────────────────────────────────
function Icon({ name, size = 14 }) {
  const stroke = "currentColor";
  const sw = 1.6;
  const common = {
    width: size,
    height: size,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke,
    strokeWidth: sw,
    strokeLinecap: "round",
    strokeLinejoin: "round",
    className: "i",
  };
  switch (name) {
    case "arrow-tr":
      return (
        <svg {...common}>
          <path d="M7 17 L17 7" />
          <path d="M9 7 L17 7 L17 15" />
        </svg>
      );
    case "arrow-l":
      return (
        <svg {...common}>
          <path d="M14 6 L8 12 L14 18" />
        </svg>
      );
    case "play":
      return (
        <svg {...common}>
          <path d="M8 5 L19 12 L8 19 Z" fill="currentColor" stroke="none" />
        </svg>
      );
    case "mail":
      return (
        <svg {...common}>
          <rect x="3" y="5" width="18" height="14" rx="2" />
          <path d="M3 7 L12 13 L21 7" />
        </svg>
      );
    case "tg":
      return (
        <svg {...common}>
          <path d="M21 4 L3 11 L9 14 L11 20 L14 16 L19 19 Z" />
        </svg>
      );
    case "in":
      return (
        <svg {...common}>
          <rect x="3" y="3" width="18" height="18" rx="2" />
          <path d="M7 10 V17 M7 7 V7.01 M11 17 V12 M11 14 C11 12.5 12 11.5 13.5 11.5 C15 11.5 16 12.5 16 14 V17" />
        </svg>
      );
    case "wa":
      return (
        <svg {...common}>
          <path d="M12 2C6.477 2 2 6.477 2 12c0 1.89.525 3.66 1.438 5.168L2 22l4.832-1.438A9.956 9.956 0 0 0 12 22c5.523 0 10-4.477 10-10S17.523 2 12 2z" />
          <path d="M8.5 9c0-.5.4-1 .9-1 .3 0 .5.1.7.4l1 1.8c.2.3.1.6-.1.9l-.5.6c.5 1 1.4 1.9 2.4 2.4l.6-.5c.3-.2.6-.3.9-.1l1.8 1c.3.2.4.4.4.7 0 .5-.5.9-1 .9-2.8 0-6.1-3.3-6.1-6.1z" />
        </svg>
      );
    case "be":
      return (
        <svg {...common}>
          <path d="M3 7 H8 C9.5 7 10.5 7.8 10.5 9 C10.5 10.2 9.5 11 8 11 H3 Z" />
          <path d="M3 11 H8.5 C10.2 11 11.2 12 11.2 13.5 C11.2 15 10.2 16 8.5 16 H3 Z" />
          <path d="M14 8 H20" />
          <path d="M14 13 H21 C21 11 19.5 10 17.5 10 C15.5 10 14 11 14 13 C14 15 15.5 16 17.5 16 C19 16 20 15.4 20.5 14.4" />
        </svg>
      );
    case "cv":
      return (
        <svg {...common}>
          <rect x="4" y="3" width="16" height="18" rx="2" />
          <path d="M8 8 H16 M8 12 H16 M8 16 H13" />
        </svg>
      );
    case "cal":
      return (
        <svg {...common}>
          <rect x="3" y="5" width="18" height="16" rx="2" />
          <path d="M3 10 H21 M8 3 V7 M16 3 V7" />
        </svg>
      );
    case "ext":
      return (
        <svg {...common}>
          <path d="M9 5 H5 V19 H19 V15" />
          <path d="M14 5 H19 V10" />
          <path d="M11 13 L19 5" />
        </svg>
      );
    case "trophy":
      return (
        <svg {...common}>
          <path d="M8 5 H16 V10 C16 12.5 14 14 12 14 C10 14 8 12.5 8 10 Z" />
          <path d="M8 7 H4 V9 C4 10.5 5.5 12 7 12" />
          <path d="M16 7 H20 V9 C20 10.5 18.5 12 17 12" />
          <path d="M10 18 H14 M12 14 V18 M9 21 H15" />
        </svg>
      );
    case "spark":
      return (
        <svg {...common}>
          <path d="M12 3 L13.5 9 L20 12 L13.5 14.5 L12 21 L10.5 14.5 L4 12 L10.5 9 Z" />
        </svg>
      );
    case "filter":
      return (
        <svg {...common}>
          <path d="M3 5 H21 M6 12 H18 M10 19 H14" />
        </svg>
      );
    case "doc":
      return (
        <svg {...common}>
          <path d="M7 3 H14 L19 8 V21 H7 Z" />
          <path d="M14 3 V8 H19" />
        </svg>
      );
    case "sun":
      return (
        <svg {...common}>
          <circle cx="12" cy="12" r="4" />
          <path d="M12 2 V4 M12 20 V22 M2 12 H4 M20 12 H22 M5 5 L6.5 6.5 M17.5 17.5 L19 19 M5 19 L6.5 17.5 M17.5 6.5 L19 5" />
        </svg>
      );
    case "moon":
      return (
        <svg {...common}>
          <path d="M20 14 A8 8 0 1 1 10 4 A6 6 0 0 0 20 14 Z" />
        </svg>
      );
    default:
      return null;
  }
}

// ── topbar / nav ────────────────────────────────────────────
function Topbar({ route, person, lang, switchLang, ui }) {
  const nav = ui.nav;
  const items = [
    { id: "projects", label: nav.projects },
    { id: "about", label: nav.about },
    { id: "process", label: nav.process },
    { id: "cv", label: <><span className="nav-label-full">{nav.cv}</span><span className="nav-label-short">CV</span></> },
    { id: "contacts", label: nav.contacts },
  ];

  const activeId =
    route.name === "case" || route.name === "all"
      ? "projects"
      : items.find((i) => i.id === route.name)?.id || "projects";

  const navRef = useRef(null);
  const [pill, setPill] = useState({ left: 0, width: 0, ready: false });
  const [hoveredId, setHoveredId] = useState(null);

  const movePillTo = useCallback((id) => {
    if (!navRef.current) return;
    const target = navRef.current.querySelector(`[data-navid="${id}"]`);
    if (!target) return;
    const navRect = navRef.current.getBoundingClientRect();
    const tRect = target.getBoundingClientRect();
    setPill({ left: tRect.left - navRect.left, width: tRect.width, ready: true });
  }, []);

  // Move pill instantly to active tab on route change + scroll active tab into view on mobile
  useEffect(() => {
    const raf = requestAnimationFrame(() => {
      movePillTo(activeId);
      if (!navRef.current) return;
      const target = navRef.current.querySelector(`[data-navid="${activeId}"]`);
      if (target) target.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "instant" });
    });
    return () => cancelAnimationFrame(raf);
  }, [activeId, movePillTo]);

  // Move pill on hover
  useEffect(() => {
    movePillTo(hoveredId || activeId);
  }, [hoveredId, activeId, movePillTo]);

  return (
    <header className="topbar">
      <div className="topbar__brand">
        <a
          href="#/projects"
          className="topbar__brand"
          style={{ padding: 0 }}
          aria-label="Home"
        >
          <span className="brand-name">stanislav mitrofanov</span>
        </a>
      </div>

      <nav
        className="topbar__nav"
        aria-label="Primary"
        ref={navRef}
        onMouseLeave={() => setHoveredId(null)}
      >
        <div
          className="nav-pill"
          style={{
            left: pill.left,
            width: pill.width,
            opacity: pill.ready ? 1 : 0,
            transition: pill.ready
              ? "left 0.28s cubic-bezier(.4,0,.2,1), width 0.28s cubic-bezier(.4,0,.2,1)"
              : "none",
          }}
        />
        {items.map((it) => (
          <a
            key={it.id}
            href={`#/${it.id}`}
            className="nav-tab"
            data-navid={it.id}
            aria-current={it.id === activeId ? "page" : undefined}
            onMouseEnter={() => setHoveredId(it.id)}
          >
            {it.label}
          </a>
        ))}
      </nav>

      <div className="topbar__lang">
        <div className="lang-switch">
          <button
            className={`lang-btn${lang === "en" ? " is-active" : ""}`}
            onClick={() => switchLang("en")}
          >EN</button>
          <span className="lang-sep">·</span>
          <button
            className={`lang-btn${lang === "ru" ? " is-active" : ""}`}
            onClick={() => switchLang("ru")}
          >RU</button>
        </div>
      </div>

      <div className="topbar__right">
        {person.available && (
          <span className="availability">{ui.openToRoles}</span>
        )}
      </div>
    </header>
  );
}

// ── footer ──────────────────────────────────────────────────
function Footer({ person }) {
  return (
    <footer className="footer">
      <span className="footer__year">© {new Date().getFullYear()}</span>
    </footer>
  );
}

Object.assign(window, { useRoute, navigate, Icon, Topbar, Footer });
