import {Outlet, useLocation} from "react-router-dom";
import menuItems from "@/data/menuItems";
import React from "react";

const Layout = () => {
  const {pathname} = useLocation();

  const matched = menuItems
    .flatMap(parent =>
      (parent.children ?? []).map(child => ({
        parent,
        child,
        fullHref: parent.href.endsWith("/") || child.href.startsWith("/")
          ? `${parent.href}${child.href}`
          : `${parent.href}/${child.href}`
      }))
    )
    .find(({fullHref}) => fullHref === pathname);

  const title = matched?.parent.label || "";
  const description = matched?.parent.description || "";
  const layoutImg = matched?.parent.layoutImg || "/hero.jpg";
  const subTitle = matched?.child.label || "";

  return (
    <>
      <div
        className="w-full h-[360px] bg-cover bg-center relative"
        style={{backgroundImage: `url('${layoutImg}')`}}
      >
        <div className="absolute inset-0 bg-black/40"/>
        <div className="relative max-w-7xl top-10 h-full mx-auto flex flex-col justify-center gap-2">
          <div className="text-white text-4xl font-bold font-['Inter']">{title}</div>
          <div className="text-white text-lg font-normal font-['Inter']">{description}</div>
        </div>
      </div>

      {/* page header */}
      <div className="w-full border-b-3 border-gray-300 py-5">
        <div className="max-w-7xl mx-auto flex flex-col gap-2">
          <h2 className="text-3xl text-blue-900 font-bold font-['Inter']">
            {subTitle}
          </h2>
          <div className="text-sm text-gray-400 font-['Inter'] self-end">
            {`HOME > ${title} > ${subTitle}`}
          </div>
        </div>
      </div>

      {/* 하위 라우트 렌더링 */}
      <Outlet/>
    </>
  );
};

export default Layout;
