import { RichText, Text, View } from "@tarojs/components";
import { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import { getContentDetail, getContents } from "../../api/contents";
import "../about-intro/index.scss";

function blocksOf(detail: any) {
  const blocks = detail?.bodyParsed || detail?.blocks || detail?.bodyJson || detail?.body_json;
  if (Array.isArray(blocks)) return blocks;
  const body = String(detail?.body || detail?.summary || "").trim();
  return body ? [{ type: body.includes("<") ? "html" : "text", content: body }] : [];
}

export default function AboutStructurePage() {
  const [detail, setDetail] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        const rows = await getContents({ type: "about_structure", page: 1, pageSize: 1 });
        const first = Array.isArray(rows) ? rows[0] : null;
        const full = first?.id ? await getContentDetail(first.id) : null;
        setDetail(full || first || null);
        setError("");
      } catch (e: any) {
        setError(e?.message || "组织架构加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  const blocks = blocksOf(detail);

  return (
    <View className="about-page">
      <View className="about-page__body">
        {error ? <Text className="about-state is-error">{error}</Text> : null}
        {loading ? <Text className="about-state">加载中...</Text> : null}
        <View className="about-panel">
          <Text className="about-title">{detail?.title || "组织架构"}</Text>
          {detail?.summary ? <Text className="about-summary">{detail.summary}</Text> : null}
          {blocks.length ? (
            blocks.map((block: any, index: number) => {
              const type = String(block?.type || "text").toLowerCase();
              const content = String(block?.content || block?.text || "");
              return type === "html" ? (
                <View key={index} className="about-rich">
                  <RichText nodes={content} />
                </View>
              ) : (
                <Text key={index} className="about-paragraph">{content}</Text>
              );
            })
          ) : (
            <Text className="about-paragraph">组织架构内容暂未配置，请在 web 后台维护后同步展示。</Text>
          )}
        </View>
      </View>
    </View>
  );
}
