import type { CurrentUser, SiteSettings } from '../env';
import { safeJson } from '../utils/html';
import { mediaUrl } from '../utils/image';
import { Icons } from './components/icons';
import { LoginModal } from './components/login-modal';
import { RegisterModal } from './components/register-modal';
import { SettingModal } from './components/setting-modal';
import { LinksModal } from './components/links-modal';
import { WriteModal } from './components/write-modal';
import { DialogRoot } from './components/dialog';

interface LayoutProps {
  title?: string;
  settings: SiteSettings;
  currentUser: CurrentUser | null;
  csrfToken: string;
  links?: Array<{ id: string; name: string; url: string; avatar: string | null; description: string; category: string }>;
  showHero?: boolean;
  children: any;
}

export function Layout(props: LayoutProps) {
  const siteTitle = props.title ? `${props.title} - ${props.settings.site_name}` : props.settings.site_name;
  const avatarUrl = mediaUrl(props.settings.cdn_base_url, props.settings.site_avatar_key);
  const topImageUrl = mediaUrl(props.settings.cdn_base_url, props.settings.top_image_key, '');
  const topVideoUrl = mediaUrl(props.settings.cdn_base_url, props.settings.top_video_key, '');
  const config = {
    apiBase: '/api',
    uploadBase: '/api/uploads',
    csrfToken: props.csrfToken,
    defaultAvatar: '/assets/images/default-avatar.svg',
    homeUrl: '/',
    locationLookupEnabled: Boolean(props.settings.tencent_map_key),
    currentUser: props.currentUser
      ? {
          id: props.currentUser.id,
          username: props.currentUser.username,
          displayName: props.currentUser.displayName,
          role: props.currentUser.role,
          avatarUrl: mediaUrl(props.settings.cdn_base_url, props.currentUser.avatarKey)
        }
      : null,
    currentUserIsAdmin: props.currentUser?.role === 'admin',
    commentMode: props.settings.comment_mode
  };

  return (
    <html lang="zh-CN">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="color-scheme" content="light dark" />
        <title>{siteTitle}</title>
        <script dangerouslySetInnerHTML={{ __html: "(function(){var t=localStorage.getItem('wemoments_theme_mode');if(t==='dark')document.documentElement.classList.add('dark');})();" }} />
        <link rel="stylesheet" href="/assets/css/fancybox.css" />
        <link rel="stylesheet" href="/assets/css/wemoments.css" />
        {props.settings.custom_css ? <style dangerouslySetInnerHTML={{ __html: props.settings.custom_css }} /> : null}
        <script dangerouslySetInnerHTML={{ __html: `window.WEMOMENTS_CONFIG=${safeJson(config)};` }} />
      </head>
      <body x-data="wemomentsShell()">
        <main class="page-shell">
          <nav class="top-nav" data-top-nav>
            <div class="nav-left">
              <button type="button" data-open-modal={props.currentUser ? 'settings' : 'login'} aria-label={props.currentUser ? '用户设置' : '登录'}>
                {Icons.user()}
              </button>
              <button type="button" data-open-modal="links" aria-label="友链">{Icons.links()}</button>
              <button type="button" data-open-modal="settings" aria-label="设置">{Icons.settings()}</button>
            </div>
            <a class="nav-title" href="/">{props.settings.site_name}</a>
            <div class="nav-right">
              {props.currentUser ? (
                <button type="button" data-open-modal="write" aria-label="发布说说">{Icons.camera()}</button>
              ) : (
                <button type="button" data-open-modal="login" aria-label="登录后发布">{Icons.camera()}</button>
              )}
            </div>
          </nav>
          {props.showHero !== false ? (
            <header class="header-container">
              {topVideoUrl ? (
                <video class="header-video" src={topVideoUrl} autoplay muted loop playsinline poster={topImageUrl || undefined}></video>
              ) : (
                <div class="header-image" style={topImageUrl ? `background-image:url('${topImageUrl}')` : undefined}></div>
              )}
              <div class="site-profile">
                <div class="site-copy">
                  <h1>{props.settings.site_name}</h1>
                  {props.settings.site_description ? <p>{props.settings.site_description}</p> : null}
                </div>
                <a href={props.settings.avatar_link || '/'} class="site-avatar">
                  <img src={avatarUrl} alt={`${props.settings.site_name} 头像`} />
                </a>
              </div>
            </header>
          ) : null}
          <section class="content-container">{props.children}</section>
          {props.settings.beian_info ? <footer class="site-footer">{props.settings.beian_info}</footer> : null}
        </main>
        <LoginModal />
        <RegisterModal allowRegister={props.settings.allow_register} />
        <SettingModal />
        <LinksModal links={props.links || []} />
        {props.currentUser ? <WriteModal /> : null}
        <DialogRoot />
        <script defer src="/assets/js/wemoments.js"></script>
        <script defer src="/assets/js/axios.min.js"></script>
        <script defer src="/assets/js/fancybox.umd.js"></script>
        <script defer src="/assets/js/alpine.min.js"></script>
        {props.settings.analytics_code ? <script dangerouslySetInnerHTML={{ __html: props.settings.analytics_code }} /> : null}
        {props.settings.custom_js ? <script dangerouslySetInnerHTML={{ __html: props.settings.custom_js }} /> : null}
      </body>
    </html>
  );
}
