"use client";
import Counter from "@/components/common/Counter";
import React, { useEffect, useState } from "react";
import axios from "axios";

export default function Facts() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        setLoading(true);
        const res = await axios.get("/api/get-component-data", {
          params: { component_name: "Facts" },
        });
        setData(res.data.data);
      } catch (err) {
        setError("获取Facts数据失败");
      } finally {
        setLoading(false);
      }
    }
    fetchData();
  }, []);

  if (loading) return <div className="text-center py-20">Loading...</div>;
  if (error) return null;
  if (!data) return null;

  // items 子表
  const items = data.items || [];

  return (
    <section className="wrapper !bg-[#edf2fc] angled lower-start">
      <div className="container py-[4.5rem] xl:!py-24 lg:!py-24 md:!py-24">
        <div className="flex flex-wrap mx-[-15px] !mb-10">
          <div className="xl:w-10/12 w-full flex-[0_0_auto] !px-[15px] max-w-full !mx-auto">
            <div className="flex flex-wrap mx-[-15px] items-center counter-wrapper !mt-[-30px] !text-center">
              {items.map((item, idx) => (
                <div className="xl:w-3/12 lg:w-3/12 md:w-3/12 w-full flex-[0_0_auto] !px-[15px] max-w-full !mt-[30px]" key={item.no || idx}>
                  {item.item_html_code ? (
                    <div
                      style={{ display: "inline-block", width: "2.6rem", height: "2.6rem", marginBottom: "1rem"  }}
                      dangerouslySetInnerHTML={{ __html: item.item_html_code }}
                    />
                  ) : (
                    <img
                      src={item.item_icon}
                      alt="icon"
                      style={{ display: "inline-block", width: "2.6rem", height: "2.6rem", marginBottom: "1rem" }}
                    />
                  )}
                  <h3 className="counter xl:!text-[2rem] !text-[calc(1.325rem_+_0.9vw)] !tracking-[normal] !leading-none !mb-2">
                    <Counter max={parseInt(item.item_title) || 0} />
                  </h3>
                  <p className="text-[0.8rem] font-medium !mb-0">
                    {item.item_subtitle}
                  </p>
                </div>
              ))}
            </div>
            {/*/.row */}
          </div>
          {/* /column */}
        </div>
        {/* /.row */}
      </div>
      {/* /.container */}
    </section>
  );
}
