'use client';

import { useState, useEffect } from 'react';

interface CoreDnaItem {
  id: number;
  icon: string;
  title: string;
  description: string;
  order: number;
}

interface CoreDnaSection {
  eyebrow: string;
  title_regular: string;
  title_emphasized: string;
}

interface CoreDnaData {
  section: CoreDnaSection;
  items: CoreDnaItem[];
}

export default function CoreDna() {
  const [coreDnaData, setCoreDnaData] = useState<CoreDnaData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchCoreDnaData();
  }, []);

  // Scroll reveal animation
  useEffect(() => {
    if (!coreDnaData) return;
    const timer = setTimeout(() => {
      const revealEls = document.querySelectorAll('.pillar-card.reveal');
      if (revealEls.length === 0) return;
      const obs = new IntersectionObserver((entries) => {
        entries.forEach(e => {
          if (e.isIntersecting) { e.target.classList.add('visible'); obs.unobserve(e.target); }
        });
      }, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });
      revealEls.forEach(el => obs.observe(el));
      return () => obs.disconnect();
    }, 100);
    return () => clearTimeout(timer);
  }, [coreDnaData]);

  const fetchCoreDnaData = async () => {
    try {
      const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';
      const response = await fetch(`${apiBaseUrl}/api/homepage/coredna`, {
        method: 'GET',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
      });
      if (!response.ok) { setError('unavailable'); return; }
      const result = await response.json();
      if (result.success && result.data) {
        setCoreDnaData(result.data);
      } else {
        setError('no data');
      }
    } catch {
      setError('fetch failed');
    } finally {
      setLoading(false);
    }
  };

  // Show loading spinner
  if (loading) {
    return (
      <section className="pillars" id="pillars">
        <div className="pillars-bg"></div>
        <div className="container">
          <div style={{ textAlign: 'center', padding: '100px 0' }}>
            <div style={{ 
              fontSize: '4rem',
              color: '#52b788',
              animation: 'spin 1s linear infinite'
            }}>
              <i className="fas fa-spinner"></i>
            </div>
            <p style={{ marginTop: '20px', color: '#666' }}>Loading Core DNA...</p>
          </div>
        </div>
        <style jsx>{`
          @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
          }
        `}</style>
      </section>
    );
  }

  // On API error, render nothing — don't expose error messages to users
  if (error) return null;

  if (!coreDnaData || !coreDnaData.items || coreDnaData.items.length === 0) return null;

  const { section, items } = coreDnaData;

  return (
    <section className="pillars" id="pillars">
      <div className="pillars-bg"></div>
      <div className="pillars-orb pillars-orb-1"></div>
      <div className="pillars-orb pillars-orb-2"></div>
      <div className="pillars-orb pillars-orb-3"></div>
      <div className="container">
        <div className="section-header center">
          <div className="section-eyebrow">{section.eyebrow}</div>
          <h2 className="section-title">
            {section.title_regular}<br/><em>{section.title_emphasized}</em>
          </h2>
        </div>
        <div className="pillars-grid">
          {items.map((item, index) => (
            <div 
              key={item.id} 
              className={`pillar-card reveal visible ${index > 0 ? `reveal-delay-${Math.min(index, 3)}` : ''}`}
            >
              <div className="pillar-icon-wrap">
                <div className="pillar-icon">
                  <i className={`fas ${item.icon}`}></i>
                </div>
                <div className="pillar-ring"></div>
              </div>
              <h3>{item.title}</h3>
              <p>{item.description}</p>
              <div className="pillar-line"></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
