/** 结构来自 posts6.json；播放地址改成本地/稳定 CDN（抖音 CDN 会 ERR_CONNECTION_RESET） */
import posts6 from './posts6.json'

export type RecommendVideo = (typeof posts6)[number] & { type: string }

/** 本地演示视频，避免 douyin 跳转 CDN 连接被重置 */
const LOCAL_MP4 = '/video/demo.mp4'

/** 本地竖屏视频 1080×1920（从 posts6 抖音源下载） */
const LOCAL_PORTRAIT_MP4 = '/video/portrait.mp4'
const LOCAL_PORTRAIT_MP4_2 = '/video/portrait2.mp4'

const REMOTE_MP4 = [
  'https://www.w3schools.com/html/mov_bbb.mp4',
  'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4',
]

function applyPortraitVideo(
  item: RecommendVideo,
  postIndex: number,
  portraitFile: string,
  label = '竖屏',
): RecommendVideo {
  const raw = posts6[postIndex]
  const w = raw?.video?.play_addr?.width ?? 1080
  const h = raw?.video?.play_addr?.height ?? 1920
  return {
    ...item,
    desc: `【${label}】${raw?.desc?.slice(0, 30) || ''}`,
    video: {
      ...item.video,
      width: w,
      height: h,
      play_addr: {
        ...item.video.play_addr,
        width: w,
        height: h,
        url_list: [portraitFile],
      },
    },
  } as RecommendVideo
}

function buildVideoList(
  source: typeof posts6,
  options: { playIndexOffset?: number; primaryUrl?: string; fallbackUrl?: string } = {},
): RecommendVideo[] {
  const { playIndexOffset = 0, primaryUrl = LOCAL_MP4, fallbackUrl } = options
  const farmNames = ['农场名称一', '农场名称二', '农场名称三', '农场名称四', '农场名称五', '农场名称六']
  return source.map((v, i) => ({
    ...v,
    type: 'recommend-video',
    farmName: farmNames[i] || `农场名称${i + 1}`,
    adopt_friends_count: [3, 5, 8, 2, 6, 4][i] ?? 3,
    isLoved: false,
    isCollect: false,
    isAttention: false,
    video: {
      ...v.video,
      play_addr: {
        ...v.video?.play_addr,
        url_list: [
          primaryUrl,
          fallbackUrl ?? REMOTE_MP4[(i + playIndexOffset) % REMOTE_MP4.length],
        ],
      },
    },
  })) as RecommendVideo[]
}

/** 第 1 条：横屏 demo */
function applyLandscapeDemo(item: RecommendVideo): RecommendVideo {
  return {
    ...item,
    desc: `【横屏demo】${item.desc?.slice(0, 28) || ''}`,
    video: {
      ...item.video,
      width: 1920,
      height: 1080,
      play_addr: {
        ...item.video.play_addr,
        width: 1920,
        height: 1080,
        url_list: [LOCAL_MP4],
      },
    },
  } as RecommendVideo
}

/** 推荐 Tab：第1条横屏 demo；第2、3条竖屏 9:16 */
export const recommendVideos = buildVideoList(posts6, { primaryUrl: LOCAL_MP4 }).map((v, i) => {
  if (i === 0) return applyLandscapeDemo(v)
  if (i === 1) return applyPortraitVideo(v, 1, LOCAL_PORTRAIT_MP4, '竖屏2')
  if (i === 2) return applyPortraitVideo(v, 3, LOCAL_PORTRAIT_MP4_2, '竖屏3')
  return v
})

/** 我的 Tab：另一段远程演示视频，便于区分 */
export const myVideos = buildVideoList(posts6.slice(2), {
  primaryUrl: REMOTE_MP4[1],
  fallbackUrl: REMOTE_MP4[0],
}).map((v, i) => {
  if (i === 0) {
    return { ...v, desc: `【我的频道】${v.desc || '竖屏视频'}` }
  }
  if (i === 1) {
    return applyPortraitVideo(v, 3, LOCAL_PORTRAIT_MP4_2)
  }
  return v
})

const AVATAR =
  'https://p3-pc.douyinpic.com/img/aweme-avatar/tos-cn-avt-0015_99d3a4923c94e1e27b16209743eaec24~c5_168x168.jpeg?from=2956013662'

export const miniPrograms = [
  {
    id: 'mp1',
    name: '飞鸟认养',
    icon: 'https://lf3-static.bytednsdoc.com/obj/eden-cn/pipieh7nupabozups/toutiao_web_pc/tt-icon.png',
  },
  {
    id: 'mp2',
    name: '果园直播',
    icon: 'https://gd-hbimg.huaban.com/65130a3e6a139530bb03bd118e21a2603af7df4e1303b-OOzcBu_fw658webp',
  },
]

export const recentUsers = recommendVideos.slice(0, 6).map((v) => ({
  uid: String(v.author?.uid || v.author_user_id),
  nickname: v.author?.nickname || '用户',
  avatar: v.author?.avatar_168x168?.url_list?.[0] || AVATAR,
}))

export const longVideos = recommendVideos.slice(0, 2).map((v, i) => ({
  id: `lv${i}`,
  title: v.desc?.slice(0, 20) || '长视频',
  cover: v.video?.cover?.url_list?.[0] || '',
  duration: '10:00',
  play_count: v.statistics?.play_count || v.statistics?.digg_count || 0,
  author: v.author?.nickname || '',
}))

export const communityPosts = recommendVideos.slice(0, 2).map((v, i) => ({
  id: `cp${i}`,
  title: v.desc || '经验分享',
  cover: v.video?.cover?.url_list?.[0] || '',
  author: v.author?.nickname || '',
  digg_count: v.statistics?.digg_count || 0,
}))

export const hotFeed = recommendVideos.slice(0, 2)
export const followFeed = recommendVideos.slice(2, 3)

export type VideoCommentItem = {
  comment_id: string
  create_time: number
  ip_location?: string
  content: string
  user_buried: boolean
  user_digged: boolean
  digg_count: number
  nickname: string
  avatar: string
  sub_comment_count: number
  showChildren?: boolean
  children?: VideoCommentItem[]
}

const COMMENT_VIDEO_IDS = [
  '7267478481213181238',
  '7128686458763889956',
]

function normalizeComment(raw: Record<string, unknown>): VideoCommentItem {
  return {
    comment_id: String(raw.comment_id),
    create_time: Number(raw.create_time),
    ip_location: raw.ip_location as string | undefined,
    content: String(raw.content || ''),
    user_buried: Boolean(raw.user_buried),
    user_digged: Boolean(raw.user_digged),
    digg_count: Number(raw.digg_count) || 0,
    nickname: String(raw.nickname || '用户'),
    avatar: String(raw.avatar || AVATAR),
    sub_comment_count: Number(raw.sub_comment_count) || 0,
    showChildren: false,
    children: [],
  }
}

export function getRecommendedVideos(pageNo = 0, pageSize = 10) {
  const start = pageNo * pageSize
  const list = recommendVideos.slice(start, start + pageSize)
  return {
    code: 200,
    msg: '',
    data: { total: recommendVideos.length, list },
  }
}

/** 与 douyin-vue 一致：按视频 id 拉取评论 json */
export async function fetchVideoComments(videoId: string) {
  let id = videoId
  if (!COMMENT_VIDEO_IDS.includes(String(id))) {
    id = COMMENT_VIDEO_IDS[0]
  }
  try {
    const res = await fetch(`/data/comments/video_id_${id}.json`)
    const data = (await res.json()) as Record<string, unknown>[]
    return { success: true, data: data.map(normalizeComment) }
  } catch {
    return { success: false, data: [] as VideoCommentItem[] }
  }
}

export function formatCount(n: number) {
  if (n >= 10000) return (n / 10000).toFixed(1) + 'w'
  if (n >= 1000) return (n / 1000).toFixed(1) + 'k'
  return String(n)
}
