"use client";
import React, { useEffect, useState } from "react";
import Image from "next/image";
import axios from "axios";

export default function Contact() {
  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: "Contact" },
        });
        setData(res.data.data);
      } catch (err) {
        setError("Failed to get Contact data");
      } finally {
        setLoading(false);
      }
    }
    fetchData();
  }, []);

  if (!data) return null;

  const title = data.title || "";
  const subtitle = data.subtitle || "";
  const description = data.description || "";
  const image = data.image || "/assets/img/logo-dark.png";
  const contacts = Array.isArray(data.items)
    ? data.items.filter(item => item.item_title)
    : [];
 

  return (
    <section className="w-full flex flex-col items-center">
      <div className="flex flex-col w-full px-2 md:px-4 mb-2">
      <Image
              className="mb-3"
              alt="image"
              width="160"
              height="40"
              src={image}
            />
        {subtitle && (
          <h2 className="pb-5 text-center">{subtitle}</h2>
        )}
      </div>
      <div className="w-full flex flex-col items-center px-2 md:px-4 mb-4">
        {contacts.map((item, idx) => (
          <div className="flex flex-row items-start mb-2 last:mb-0 w-full max-w-xs mx-auto" key={idx}>
            <div className="mr-3 flex-shrink-0">
              <div className="icon text-white">
                {item.item_html_code && (
                  <span style={{ display: 'inline-block', width: '2rem', height: '2rem', filter: 'brightness(0) invert(1)' }}
                    dangerouslySetInnerHTML={{ __html: item.item_html_code }} />
                )}
              </div>
            </div>
            <div className="flex-1">
              {/(mail)/i.test(item.item_title) ? (
                <p className="text-left break-words">
                  {item.item_title}
                  <a href={`mailto:${item.item_title}`} className="!text-white  hover:!underline">
                  {item.item_subtitle}
                  </a>
                </p>
              ) : (
                <p className="text-left break-words">
                  {item.item_title} {item.item_subtitle}
                </p>
              )}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}
