'use client';

import { useState, useEffect, forwardRef, useImperativeHandle } from 'react';

export type ServicesSectionHandle = {
  canGoNext: () => boolean;
  canGoPrev: () => boolean;
  goNext: () => void;
  goPrev: () => void;
};

// ─── Types ───────────────────────────────────────────────────────────────────

type Tab = {
  id: string;
  label: string;
  title: React.ReactNode;
  excerpt?: React.ReactNode;
};

type Slide = {
  tabs: Tab[];
};

// ─── Data ────────────────────────────────────────────────────────────────────

const slides: Slide[] = [
  {
    tabs: [
      {
        id: 'info-site',
        label: 'Info Site',
        title: <>We Build Websites That <span>GET NOTICED.</span></>,
        excerpt: "Our web design solutions integrate unique and smart art design into a user friendly interface that reflects the personality of you and your business. At the same time, we build your site to optimize numerous marketing channels to drive traffic to your site.",
      },
      {
        id: 'ecommerce',
        label: 'eCommerce',
        title: <>We Build Websites That <span>DRIVE SALES!</span></>,
        excerpt: "From landing page to checkout confirmation, we design every nuance of your site to facilitate successful sales conversions.",
      },
      {
        id: 'mobile',
        label: 'Mobile Apps',
        title: <>We Build <span>MOBILE APPS</span> that allow users to <span>CONNECT</span> in <span>THE WAY USERS PREFER.</span></>,
        excerpt: "Diverse users interact on the internet using a wide range of devices. We build mobile sites that provide the best user experience no matter what device is being used.",
      },
      {
        id: 'cms',
        label: 'CMS',
        title: <>We Build Websites that facilitate <span>YOU MANAGING YOUR OWN CONTENT</span> to help you keep your costs low.</>,
      },
      {
        id: 'analytics',
        label: 'Analytics',
        title: <>We include code automatically in every website we build that helps you understand <span>HOW AND WHY INTERNET TRAFFIC IS COMING</span> to your website.</>,
        excerpt: "We also help you understand which marketing or promotions are working best for you. We even perform a competitive analysis to help you understand how competitors are driving traffic to their websites.",
      },
      {
        id: 'enterprise',
        label: 'Enterprise',
        title: <>Complete web application development, <span>B2C &amp; B2B</span> applications including financial, banking and e-commerce solutions, back-end administrative modules, standalone web applications, web services and CMS integration.</>,
        excerpt: "Web site design, streamlined design and user oriented interfaces built with accessibility in mind. Database design, optimization, management and backup. Web solutions & strategies, data storage & security, software maintenance & migration.",
      },
    ],
  },
  {
    tabs: [
      {
        id: 'graphic-design',
        label: 'Graphic Design',
        title: <>We provide <span>FULL SERVICE GRAPHIC DESIGN</span> for branding, display, digital and printed materials.</>,
        excerpt: <>LOW Hourly Rate <span>$40</span></>,
      },
      {
        id: 'branding',
        label: 'Branding',
        title: <>We <span>TRANSFORM</span> your concept and business personality into unique and exciting <span>BRAND IDENTITIES</span></>,
        excerpt: <>Prices starting <span>at $500</span></>,
      },
      {
        id: 'cards',
        label: 'Business Cards',
        title: <>We create artwork for business cards that not only provide your information but also <span>FURTHER BRAND</span> your <span>BUSINESS</span> and speak who you are.</>,
        excerpt: <>Just <span>$70</span></>,
      },
      {
        id: 'newsletters',
        label: 'Newsletters',
        title: <>Promotional newsletters are a great way to <span>CONNECT</span> and <span>STAY CONNECTED</span> to your customers.</>,
        excerpt: <>Prices starting at <span>$70 per Newsletter</span></>,
      },
      {
        id: 'printed',
        label: 'Printed Materials',
        title: <>We <span>INTERPRET</span> your concepts and create artwork for exciting eye-catching Posters, Brochures, Flyers, Postcards, and Perforated Window Film.</>,
      },
    ],
  },
  {
    tabs: [
      {
        id: 'emarketing',
        label: 'eMarketing',
        title: "Today's internet marketing is a constantly evolving landscape that has all but replaced the old advertising methods of print, radio and TV. At Bitsia we understand how users connect and know how to connect you with your desired audience.",
      },
      {
        id: 'ppc',
        label: 'PPC',
        title: <>An ineffective or poorly designed PPC Marketing campaign can be costly and drive irrelevant traffic to your website. At Bitsia Solutions, we know how to make the most of your <span>PPC DOLLARS</span> and drive quality traffic to your site.</>,
        excerpt: <>Monthly Fees as low <span>as $9.99</span></>,
      },
      {
        id: 'social',
        label: 'Social Media',
        title: <><span>CONTENT ADVERTISING</span> and <span>INTERACTION</span> on Social Media is a great way to connect with your customers for free.</>,
        excerpt: <>Monthly Fees as low <span>as $9.99</span></>,
      },
      {
        id: 'seo',
        label: 'SEO',
        title: <>Search Engines are incredibly efficient at connecting users with desired results. At Bitsia Solutions, we understand how to help you connect your website with your desired audience by building <span>SEO FRIENDLY CONTENT.</span></>,
      },
    ],
  },
];

const slideLabels = ['Web Development', 'Graphic Design', 'Internet Marketing'];

const slideBackgrounds = [
  "url('/img/Resources.jpg')",
  "url('/img/graphic-design-bg.svg')",
  "url('/img/internet-marketing-bg.svg')",
];

// ─── Component ───────────────────────────────────────────────────────────────

const ServicesSection = forwardRef<ServicesSectionHandle>(function ServicesSection(_props, ref) {
  const [slide, setSlide] = useState(0);
  const [activeTab, setActiveTab] = useState(0);
  const total = slides.length;

  const handleSlideChange = (next: number) => {
    setSlide(next);
    setActiveTab(0);
  };

  useImperativeHandle(ref, () => ({
    canGoNext: () => slide < slides.length - 1,
    canGoPrev: () => slide > 0,
    goNext: () => handleSlideChange(slide + 1),
    goPrev: () => handleSlideChange(slide - 1),
  }), [slide]);

  useEffect(() => {
    const handler = (e: Event) => {
      const { slide: idx } = (e as CustomEvent<{ slide: number }>).detail;
      setSlide(idx);
      setActiveTab(0);
    };
    window.addEventListener('services:activate', handler);
    return () => window.removeEventListener('services:activate', handler);
  }, []);

  const tabs = slides[slide].tabs;
  const tab = tabs[activeTab];

  return (
    <section
      id="services"
      style={{
        position: 'relative',
        height: '100vh',
        overflow: 'hidden',
        backgroundColor: '#fff',
      }}
    >
      {/* ── Background photo (full section, z-index below content) ── */}
      <div
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          backgroundImage: slideBackgrounds[slide],
          transition: 'background-image 0.4s ease',
          backgroundSize: 'cover',
          backgroundPosition: 'top center',
          backgroundRepeat: 'no-repeat',
          zIndex: 0,
        }}
      />

      {/* ── Decorative rectangles ── */}
      {/* Orange bottom-left */}
      <div
        style={{
          position: 'absolute',
          width: 144,
          height: 51,
          bottom: 180,
          left: 50,
          backgroundColor: 'rgba(255,153,0,0.84)',
          zIndex: 2,
        }}
      />
      {/* Red top-center */}
      <div
        style={{
          position: 'absolute',
          width: 61,
          height: 27,
          top: 39,
          left: 'calc(50% - 25px)',
          backgroundColor: '#d85218',
          zIndex: 2,
        }}
      />

      {/* ── Content card (sits on right ~59% of screen) ── */}
      <div
        style={{
          position: 'relative',
          zIndex: 3,
          height: '100%',
          display: 'flex',
          alignItems: 'center',
          paddingLeft: '41%',
          boxSizing: 'border-box',
        }}
        className="services-wrapper"
      >
        <div
          style={{
            backgroundColor: '#fff',
            width: '100%',
            maxWidth: 743,
          }}
        >
          {/* ── Tab bar (orange strip) ── */}
          <div
            className="services-tabs"
            style={{
              backgroundColor: '#d85218',
              display: 'flex',
              alignItems: 'flex-end',
              minHeight: 55,
              paddingLeft: 8,
            }}
          >
            {tabs.map((t, i) => (
              <button
                key={t.id}
                onClick={() => setActiveTab(i)}
                style={{
                  background: i === activeTab ? '#fff' : 'transparent',
                  color: i === activeTab ? '#d85218' : '#fff',
                  border: 'none',
                  cursor: 'pointer',
                  fontSize: '0.813em',
                  fontWeight: 600,
                  lineHeight: 1.1,
                  padding: i === activeTab ? '16px 20px 16px 20px' : '8px 16px',
                  marginBottom: i === activeTab ? 0 : 0,
                  marginTop: i === activeTab ? 0 : 'auto',
                  textTransform: 'uppercase',
                  letterSpacing: '0.3px',
                  transition: 'all 0.15s ease-in-out',
                  whiteSpace: 'nowrap',
                  alignSelf: i === activeTab ? 'stretch' : 'center',
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                {t.label}
              </button>
            ))}
          </div>

          {/* ── Tab content ── */}
          <div
            key={`${slide}-${activeTab}`}
            className="services-content"
            style={{
              padding: '25px 40px',
              animation: 'fadeInTab 0.2s ease-in-out',
            }}
          >
            <p
              style={{
                color: '#242D27',
                fontSize: '2em',
                fontWeight: 600,
                lineHeight: '55px',
                margin: 0,
                paddingBottom: 12,
              }}
              className="services-title"
            >
              {tab.title}
            </p>
            {tab.excerpt && (
              <p
                style={{
                  color: '#45130f',
                  fontSize: '1.25em',
                  lineHeight: '35px',
                  margin: 0,
                  maxWidth: 510,
                }}
                className="services-excerpt"
              >
                {tab.excerpt}
              </p>
            )}
          </div>

          {/* ── Category selector ── */}
          <div style={{ display: 'flex', borderTop: '1px solid rgba(0,0,0,0.08)' }}>
            {slideLabels.map((label, i) => (
              <button
                key={label}
                onClick={() => handleSlideChange(i)}
                aria-pressed={i === slide}
                style={{
                  flex: 1,
                  background: 'none',
                  border: 'none',
                  borderTop: i === slide ? '3px solid #d85218' : '3px solid transparent',
                  borderRight: i < slideLabels.length - 1 ? '1px solid rgba(0,0,0,0.07)' : 'none',
                  cursor: 'pointer',
                  padding: '14px 10px 16px',
                  textAlign: 'center',
                  transition: 'border-color 0.2s ease, color 0.2s ease',
                }}
              >
                <span style={{
                  display: 'block',
                  fontSize: '0.625em',
                  fontWeight: 700,
                  letterSpacing: '1px',
                  color: i === slide ? '#d85218' : 'rgba(0,0,0,0.3)',
                  marginBottom: 4,
                  transition: 'color 0.2s ease',
                }}>
                  {String(i + 1).padStart(2, '0')}
                </span>
                <span style={{
                  display: 'block',
                  fontSize: '0.688em',
                  fontWeight: 700,
                  letterSpacing: '1.2px',
                  textTransform: 'uppercase',
                  color: i === slide ? '#d85218' : 'rgba(0,0,0,0.4)',
                  lineHeight: 1.3,
                  transition: 'color 0.2s ease',
                }}>
                  {label}
                </span>
              </button>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
});

export default ServicesSection;
