'use client';

import React from 'react';
import Link from 'next/link';
import { usePuck } from '@puckeditor/core';
import { Navigation } from '@/components/layout/Navigation';
import { MobileMenu } from '@/components/layout/MobileMenu';
import { buildNavigationTree } from '@/lib/navigation';

export function CanvasHeader({ 
  categories = [], 
  navigationItems: propNavigationItems 
}: { 
  categories?: any[], 
  navigationItems?: any[] 
}) {
  const { appState, dispatch } = usePuck();
  
  // Use prop if available, otherwise fallback to appState (though prop is preferred)
  const navigationItems = propNavigationItems || appState.data.root.props?._navigationItems || [];
  
  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    const index = appState.data.content.findIndex((b: any) => b.type === 'SiteHeader');
    if (index !== -1) {
      dispatch({ type: 'setUi', ui: { itemSelector: { index } } as any });
    }
  };
  
  const headerBlock = appState.data.content?.find((b: any) => b.type === 'SiteHeader');
  const logo = headerBlock?.props?.logo || '/logo.png';
  
  const navTree = buildNavigationTree(navigationItems, categories).filter(node => {
    // Only show items that are meant for the top header
    const dbItem = navigationItems.find((i: any) => i.sourceId === node.id || i.id.toString() === node.id);
    return !dbItem || dbItem.menuLocation === 'top_header';
  });

  return (
    <div onClick={handleClick} className="w-full bg-deep-black border-b border-crimson-red hover:ring-2 hover:ring-blue-500 cursor-pointer relative z-50 transition-all">
      <div className="absolute top-0 left-0 bg-blue-500 text-white text-[10px] px-2 py-0.5 font-bold z-50">SITE HEADER</div>
      <div className="container mx-auto px-4">
        <div className="flex items-center justify-between h-16 pt-3">
          <Link href="#" className="flex items-center" onClick={(e) => e.preventDefault()}>
            <img src={logo} alt="site logo" className="h-12 md:h-14 w-auto object-contain" />
          </Link>
          <div className="pointer-events-none flex items-center justify-between w-full ml-4">
            <Navigation className="hidden lg:flex" navigationTree={navTree} />
            <MobileMenu className="lg:hidden ml-auto" navigationTree={navTree} />
          </div>
        </div>
      </div>
    </div>
  );
}

export function CanvasFooter({ 
  categories = [],
  navigationItems: propNavigationItems
}: { 
  categories?: any[],
  navigationItems?: any[]
}) {
  const { appState, dispatch } = usePuck();
  
  const navigationItems = propNavigationItems || appState.data.root.props?._navigationItems || [];
  
  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    const index = appState.data.content.findIndex((b: any) => b.type === 'SiteFooter');
    if (index !== -1) {
      dispatch({ type: 'setUi', ui: { itemSelector: { index } } as any });
    }
  };
  
  const footerBlock = appState.data.content?.find((b: any) => b.type === 'SiteFooter');
  const headerBlock = appState.data.content?.find((b: any) => b.type === 'SiteHeader');
  const logo = headerBlock?.props?.logo || '/logo.png';
  const leftDescription = footerBlock?.props?.leftDescription || '日本発のゲーム攻略メディア「ten-sura-game.com」。メギド72の攻略情報、キャラクター評価、リセマラ情報など、プレイヤーに役立つ情報を分かりやすくお届けします。';
  const copyrightText = footerBlock?.props?.copyrightText || '© 2026 ten-sura-game.com. All rights reserved.';
  
  return (
    <div onClick={handleClick} className="bg-deep-black border-t border-crimson-red hover:ring-2 hover:ring-blue-500 cursor-pointer relative transition-all mt-auto">
      <div className="absolute top-0 left-0 bg-blue-500 text-white text-[10px] px-2 py-0.5 font-bold z-50">SITE FOOTER</div>
      <div className="container mx-auto px-4 py-10 md:py-14">
        <div className="flex flex-col md:flex-row md:justify-between md:items-start gap-8 md:gap-12">
          <div className="flex flex-col gap-4 max-w-xl">
            <Link href="#" className="inline-block" onClick={(e) => e.preventDefault()}>
              <img src={logo} alt="site logo" className="h-10 w-auto object-contain" />
            </Link>
            <p className="text-text-light-gray text-sm leading-relaxed">{leftDescription}</p>
          </div>
          <div className="flex-shrink-0">
            <h3 className="text-text-white font-semibold text-base mb-4">カテゴリー</h3>
            <ul className="flex flex-col gap-2.5">
              {categories.map((category) => (
                <li key={category.slug}>
                  <span className="text-text-light-gray text-sm">{category.name}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
      <div className="border-t border-soft-gray-border">
        <div className="container mx-auto px-4 py-5">
          <div className="flex flex-col sm:flex-row items-center justify-between gap-2">
            <p className="text-text-light-gray text-xs">{copyrightText}</p>
            <div className="flex items-center gap-4 pointer-events-none">
              <span className="text-text-light-gray text-xs">運営元について</span>
              <span className="text-text-light-gray text-xs">プライバシーポリシー</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
