'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';

interface Member {
  id: number;
  name: string;
  role: string;
  qualification: string | null;
  image_url: string;
  is_head: boolean;
}

interface TabData {
  head: Member | null;
  members: Member[];
}

interface FamilyData {
  science: TabData;
  farm: TabData;
  allied: TabData;
}

const TEAM_CONFIG = {
  science: { icon: 'fa-microscope', label: 'Science & Innovation',  headIcon: 'fa-star'      },
  farm:    { icon: 'fa-tractor',    label: 'Farm, Feed Mill & QC',   headIcon: 'fa-tractor'   },
  allied:  { icon: 'fa-briefcase',  label: 'Allied Services',         headIcon: 'fa-briefcase' },
} as const;

type TeamKey = keyof typeof TEAM_CONFIG;

export default function TeamPage() {
  const params = useParams();
  const teamKey = params.team as TeamKey;
  const config = TEAM_CONFIG[teamKey];

  const [data, setData] = useState<TabData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!config) { setLoading(false); return; }
    const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';
    fetch(`${apiBaseUrl}/api/homepage/family`)
      .then((r) => r.json())
      .then((res) => {
        if (res.success) setData((res.data as FamilyData)[teamKey]);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [teamKey, config]);

  if (!config) return null;

  return (
    <>
      {/* ── Hero ── */}
      <div className="op-hero">
        <div className="op-hero-deco" aria-hidden="true">
          <svg className="deco-leaf-1" viewBox="0 0 200 300" fill="none">
            <path d="M100 10 C160 40 190 120 160 200 C130 280 40 290 20 220 C0 150 40 80 100 10Z" fill="#7abf9e"/>
            <path d="M100 50 C140 70 160 130 140 190 C120 250 60 260 40 200" stroke="#a9d4bc" strokeWidth="1.5" fill="none"/>
          </svg>
          <svg className="deco-leaf-2" viewBox="0 0 200 300" fill="none">
            <path d="M100 10 C160 40 190 120 160 200 C130 280 40 290 20 220 C0 150 40 80 100 10Z" fill="#c9a84c"/>
          </svg>
          <svg className="deco-dots" viewBox="0 0 200 60" fill="none">
            {Array.from({ length: 24 }).map((_, i) => (
              <circle key={i} cx={(i % 6) * 36 + 10} cy={Math.floor(i / 6) * 18 + 10} r="2.5" fill="#fff"/>
            ))}
          </svg>
        </div>

        <div className="container op-hero-inner">
          <nav className="op-breadcrumb" aria-label="Breadcrumb">
            <Link href="/" className="op-bc-item">Home</Link>
            <span className="op-bc-sep" aria-hidden="true">/</span>
            <Link href="/our-people" className="op-bc-item">Our People</Link>
            <span className="op-bc-sep" aria-hidden="true">/</span>
            <span className="op-bc-item active">{config.label}</span>
          </nav>
          <h1>
            {config.label.includes('&')
              ? <>{config.label.split('&')[0].trim()} <em>&amp; {config.label.split('&')[1].trim()}</em></>
              : <em>{config.label}</em>}
          </h1>
        </div>

        <div className="op-hero-wave" aria-hidden="true">
          <svg viewBox="0 0 1440 60" preserveAspectRatio="none" fill="#fff">
            <path d="M0,40 C360,70 1080,10 1440,40 L1440,60 L0,60Z"/>
          </svg>
        </div>
      </div>

      {/* ── Members ── */}
      {loading ? (
        <div style={{ minHeight: '40vh', display: 'flex', justifyContent: 'center', alignItems: 'center', color: '#7abf9e', fontSize: '3rem' }}>
          <i className="fas fa-spinner" style={{ animation: 'op-spin 1s linear infinite' }}></i>
        </div>
      ) : data ? (
        <div className="container" style={{ paddingBottom: '5rem' }}>
          <div className="op-section">
            <div className="op-section-header">
              <div className="op-section-icon">
                <i className={`fas ${config.icon}`}></i>
              </div>
              <h2 className="op-section-title">
                {config.label.includes('&')
                  ? <>{config.label.split('&')[0].trim()} <em>&amp;</em> {config.label.split('&')[1].trim()}</>
                  : config.label}
              </h2>
            </div>

            {data.head && (
              <div className="op-head-card">
                <div className="op-head-img">
                  <img src={data.head.image_url} alt={data.head.name} />
                </div>
                <div>
                  <div className="op-head-badge">
                    <i className={`fas ${config.headIcon}`}></i> {data.head.role}
                  </div>
                  <p className="op-head-name">{data.head.name}</p>
                  {data.head.qualification && <p className="op-head-qual">{data.head.qualification}</p>}
                </div>
              </div>
            )}

            {data.members.length > 0 && (
              <div className="op-grid">
                {data.members.map((m) => (
                  <div key={m.id} className="op-card">
                    <div className="op-card-img">
                      <img src={m.image_url} alt={m.name} />
                    </div>
                    <div className="op-card-info">
                      <h4>{m.name}</h4>
                      <span>{m.role}</span>
                      {m.qualification && <p>{m.qualification}</p>}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          <div className="op-team-back-row">
            <Link href="/our-people" className="op-team-back-btn">
              <i className="fas fa-arrow-left"></i> View All Teams
            </Link>
          </div>
        </div>
      ) : null}
    </>
  );
}
