import type { Metadata, Viewport } from 'next'
import type React from 'react'

/**
 * H5 专属 layout（P0 独立化）。
 *
 * 设计目标：让 /h5/* 路由在视觉上与宿主 Forge 系统**解耦**。
 *
 * 为什么不直接切断 root layout？
 *   Next.js App Router 强制所有路由继承唯一的 root layout（src/app/layout.tsx），
 *   后者加载 globals.css（Tailwind base + @layer base 重置）、注入 themeInitScript
 *   （动态写 --bg-page 等）、加载 Google Fonts（Geist/Lora）。这些在 H5 页面也会生效。
 *
 * 务实隔离策略（容器级 + 变量重命名）：
 *   1. 本 layout 不 re-import globals.css —— 不可阻止 root 加载，但 H5 不消费那些变量。
 *   2. 在容器上注入独立的 --h5-* CSS 变量命名空间。宿主从不定义这些变量名，
 *      所以 fallback 必然生效，不会跟随 owner 主题切换。
 *   3. 系统字体栈通过 --h5-font-* 注入，不依赖宿主 Google Fonts（Geist/Lora）。
 *   4. CSS 用原生 <style dangerouslySetInnerHTML>（layout 是 Server Component，
 *      styled-jsx 会触发 client-only 导入错误）。
 *   5. 不依赖宿主 ThemeProvider/I18nProvider 的任何输出。
 *
 * P2 可定制化预留：
 *   未来对接 APP 可通过 URL query / postMessage / DB theme 字段注入一组 --h5-*
 *   变量覆盖，本 layout 仅提供默认值（深色），覆盖逻辑由 H5ClientApp 消费。
 */
export const metadata: Metadata = {
  title: 'Forge',
  description: 'Forge — AI Assistant',
}

export const viewport: Viewport = {
  width: 'device-width',
  initialScale: 1,
  maximumScale: 1,
  userScalable: false,
  viewportFit: 'cover',
}

export default function H5Layout({
  children,
}: {
  children: React.ReactNode
}): React.JSX.Element {
  return (
    <div className="h5-root" data-h5-root style={{ minHeight: '100vh' }}>
      {/* 预加载品牌字体（Inter + JetBrains Mono）。display=swap 不阻塞渲染，
          离线时自动 fallback 到 --h5-font-body 系统栈。 */}
      <link rel="preconnect" href="https://fonts.googleapis.com" />
      <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
      <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&family=Cormorant+Garamond:wght@400;500;600&display=swap"
        rel="stylesheet"
      />
      {/* eslint-disable-next-line react/no-danger */}
      <style dangerouslySetInnerHTML={{ __html: H5_ROOT_CSS }} />
      {children}
    </div>
  )
}

/**
 * H5 容器静态 CSS（含 --h5-* 变量命名空间默认值）。
 *
 * 用原生 <style> + dangerouslySetInnerHTML 注入，而非 styled-jsx：
 *   layout 是 Server Component，styled-jsx 要求 Client Component 会触发
 *   'client-only' 导入错误。这里不需要任何交互/CSS 变量动态性，纯静态字符串。
 *
 * 对接 APP 覆盖通道（P2 实现）：
 *   - URL query: ?h5-accent=#ff6600
 *   - postMessage bridge: { type: 'h5-theme', payload: {...} }
 *   - DB 持久化: app_secrets.theme JSON
 * 覆盖优先级：注入值 > 本默认值（永不回退到宿主 token）。
 */
const H5_ROOT_CSS = `
  [data-h5-root] {
    /* overscroll 禁止：防止 iOS/Android 橡皮筋滚动露出外层背景。 */
    overscroll-behavior: none;

    /* 默认主题：深色（H5 对话页典型场景：移动端夜间友好） */
    --h5-bg: #0a0a0a;
    --h5-surface: #1a1a1a;
    --h5-surface-hover: #1f1f1f;
    --h5-surface-active: #252525;
    --h5-border: #2a2a2a;
    --h5-border-subtle: #1a1a1a;
    --h5-text: #ffffff;
    --h5-text-secondary: #999999;
    --h5-text-muted: #6c6c6c;
    --h5-accent: #6366f1;
    --h5-accent-hover: #5558e3;
    --h5-success: #22c55e;
    --h5-warning: #f59e0b;
    --h5-error: #ef4444;
    --h5-on-accent: #ffffff;

    /* 圆角刻度 */
    --h5-radius-sm: 6px;
    --h5-radius-md: 8px;
    --h5-radius-lg: 12px;
    --h5-radius-xl: 16px;
    --h5-radius-full: 9999px;
    /* 语义圆角（可被预设覆盖） */
    --h5-radius-bubble: 16px;
    --h5-radius-input: 16px;
    /* 内容容器圆角：固定 Pi 圆润值，跨主题统一，不进主题契约（预设无法覆盖）。
       user 气泡 / 消息附件 / 代码块 / 表格 等会话内容容器共用。 */
    --h5-radius-content: 10px;
    /* 输入框/品牌图标圆角：固定 Pi 胶囊值，跨主题统一，不进主题契约。
       composer 输入框、welcome 品牌图标共用（52×52 + 28px 渲染为正圆）。 */
    --h5-radius-composer: 28px;

    /* 字体：Inter 为主（本 layout 已 preconnect 预加载），系统栈兜底，
       WebView 离线时自动回退。中文优先 PingFang/雅黑。 */
    --h5-font-body: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, 'Helvetica Neue', Arial, 'PingFang SC', 'Hiragino Sans GB',
      'Microsoft YaHei', sans-serif;
    --h5-font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, 'SF Mono',
      Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;
    /* 标题字体：默认与正文字体一致，可被主题预设覆盖（如 Claude 用 serif） */
    --h5-font-heading: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, 'Helvetica Neue', Arial, 'PingFang SC', 'Hiragino Sans GB',
      'Microsoft YaHei', sans-serif;
    /* 对话阅读字体默认继承 body；editorial 预设可独立覆盖。 */
    --h5-font-conversation: var(--h5-font-body);

    /* 角色级语义 token：默认回退到原有气泡体系，保证旧预设视觉不变。 */
    --h5-user-message-bg: var(--h5-accent);
    --h5-user-message-text: var(--h5-on-accent);
    --h5-composer-bg: var(--h5-surface);
    --h5-control-bg: var(--h5-surface-hover);
    --h5-conversation-text: var(--h5-text);

    /* 排版密度：editorial 阅读型默认值（Pi 基准），
       可被紧凑预设（Cursor/Linear/OpenCode）覆盖。 */
    --h5-fs-conversation: 17px;
    --h5-lh-conversation: 1.7;
    --h5-read-width: 680px;

    /* 字号刻度 */
    --h5-text-xs: 11px;
    --h5-text-sm: 12px;
    --h5-text-base: 14px;
    --h5-text-md: 15px;
    --h5-text-lg: 16px;

    color: var(--h5-text);
    background-color: var(--h5-bg);
    font-family: var(--h5-font-body);
    font-size: var(--h5-text-md);
    line-height: 1.5;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    -webkit-tap-highlight-color: transparent;
  }

  /* 重置宿主 globals.css 在 H5 容器内可能残留的全局影响 */
  [data-h5-root],
  [data-h5-root] * {
    box-sizing: border-box;
  }

  [data-h5-root] button {
    font-family: inherit;
  }

  [data-h5-root] input,
  [data-h5-root] textarea {
    font-family: inherit;
  }

  /* ── 骨架屏 + Shimmer 动画（SSR 立即可用，不等 React） ── */
  @keyframes h5-shimmer {
    0% { background-position: -200% 0; }
    100% { background-position: 200% 0; }
  }
  .h5-skeleton {
    background: linear-gradient(
      90deg,
      var(--h5-surface, #1a1a1a) 25%,
      var(--h5-surface-hover, #1f1f1f) 50%,
      var(--h5-surface, #1a1a1a) 75%
    );
    background-size: 200% 100%;
    animation: h5-shimmer 1.5s ease-in-out infinite;
    border-radius: var(--h5-radius-bubble, 16px);
  }

  /* hydration 前即可命中的 editorial 骨架，避免浅色预设先闪传统气泡。 */
  [data-h5-root] .h5-app[data-h5-visual-style='editorial'] .h5-skeleton-list {
    width: min(100%, 680px);
    margin: 0 auto;
    padding: 24px 20px !important;
  }
  [data-h5-root] .h5-app[data-h5-visual-style='editorial'] .h5-skeleton-bubble.assistant {
    width: 92%;
    height: 18px;
    margin-bottom: 10px;
    border-radius: 3px;
  }
  [data-h5-root] .h5-app[data-h5-visual-style='editorial'] .h5-skeleton-bubble.assistant.short {
    width: 58%;
  }
  [data-h5-root] .h5-app[data-h5-visual-style='editorial'] .h5-skeleton-bubble.user {
    width: 54%;
    height: 38px;
    margin-top: 24px;
    margin-left: auto;
    border-radius: var(--h5-radius-bubble, 10px);
  }
`
