'use client';

import { useEffect, useRef, useState } from 'react';

// ─── Data ────────────────────────────────────────────────────────────────────

const roles = [
  {
    role: 'Software Developers',
    icon: (
      <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" />
      </svg>
    ),
    headline: 'Code at the speed of thought',
    points: [
      'AI-assisted code generation and refactoring',
      'Automated test suite generation and debugging',
      'Architecture review and performance analysis',
      'Security vulnerability scanning in real time',
    ],
  },
  {
    role: 'Graphic Design Artists',
    icon: (
      <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10" /><circle cx="12" cy="12" r="3" />
        <line x1="12" y1="2" x2="12" y2="5" /><line x1="12" y1="19" x2="12" y2="22" />
        <line x1="2" y1="12" x2="5" y2="12" /><line x1="19" y1="12" x2="22" y2="12" />
      </svg>
    ),
    headline: 'From concept to pixel — instantly',
    points: [
      'AI mood-board and concept generation',
      'Rapid visual prototyping and style exploration',
      'Background removal and image enhancement',
      'Brand consistency checks across deliverables',
    ],
  },
  {
    role: 'Business Consultants',
    icon: (
      <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <line x1="18" y1="20" x2="18" y2="10" /><line x1="12" y1="20" x2="12" y2="4" />
        <line x1="6" y1="20" x2="6" y2="14" /><polyline points="22 20 2 20" />
      </svg>
    ),
    headline: 'Sharper insights, faster decisions',
    points: [
      'AI-powered competitive landscape analysis',
      'Market trend forecasting and opportunity mapping',
      'Automated business reporting and KPI dashboards',
      'Data-driven strategic planning and modeling',
    ],
  },
  {
    role: 'Certified Public Accountant',
    icon: (
      <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="3" width="20" height="14" rx="2" /><line x1="8" y1="21" x2="16" y2="21" /><line x1="12" y1="17" x2="12" y2="21" />
      </svg>
    ),
    headline: 'Numbers that tell the full story',
    points: [
      'AI-driven financial modeling and forecasting',
      'Automated bookkeeping anomaly detection',
      'Tax optimization scenario simulation',
      'Instant compliance and regulatory checks',
    ],
  },
  {
    role: 'Google Ads Specialist',
    icon: (
      <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" />
      </svg>
    ),
    headline: 'Every ad dollar works harder',
    points: [
      'AI bid strategy and budget optimization',
      'Predictive audience targeting and segmentation',
      'Automated A/B copy and creative testing',
      'Real-time campaign performance forecasting',
    ],
  },
];

// ─── Grid card (desktop) ──────────────────────────────────────────────────────

function GridRoleCard({ role, icon, headline, points, index }: typeof roles[0] & { index: number }) {
  const ref = useRef<HTMLDivElement>(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setVisible(true); observer.disconnect(); } },
      { threshold: 0.15 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  return (
    <div
      ref={ref}
      style={{
        backgroundColor: 'rgba(255,255,255,0.04)',
        border: '1px solid rgba(255,255,255,0.1)',
        padding: '32px 28px',
        display: 'flex',
        flexDirection: 'column',
        gap: 16,
        opacity: visible ? 1 : 0,
        transform: visible ? 'translateY(0)' : 'translateY(30px)',
        transition: `opacity 0.5s ease ${index * 0.08}s, transform 0.5s ease ${index * 0.08}s`,
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      <div style={{ position: 'absolute', top: 0, left: 0, width: 4, height: '100%', backgroundColor: '#d85218' }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ color: '#d85218', flexShrink: 0 }}>{icon}</div>
        <span style={{ fontSize: '0.75em', fontWeight: 700, letterSpacing: '1.5px', textTransform: 'uppercase', color: 'rgba(255,255,255,0.55)' }}>
          {role}
        </span>
      </div>
      <p style={{ fontSize: '1.25em', fontWeight: 600, color: '#fff', lineHeight: 1.35, margin: 0 }}>
        {headline}
      </p>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {points.map((pt) => (
          <li key={pt} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: '0.875em', color: 'rgba(255,255,255,0.72)', lineHeight: 1.5 }}>
            <span style={{ color: '#d85218', marginTop: 3, flexShrink: 0, fontSize: '0.75em' }}>◆</span>
            {pt}
          </li>
        ))}
      </ul>
    </div>
  );
}

// ─── Slider card (compact screens) ───────────────────────────────────────────

function SliderRoleCard({ role, icon, headline, points }: typeof roles[0]) {
  return (
    <div
      style={{
        backgroundColor: 'rgba(255,255,255,0.04)',
        border: '1px solid rgba(255,255,255,0.1)',
        padding: '32px 36px',
        display: 'flex',
        flexDirection: 'column',
        gap: 18,
        position: 'relative',
        overflow: 'hidden',
        height: '100%',
        boxSizing: 'border-box',
      }}
    >
      <div style={{ position: 'absolute', top: 0, left: 0, width: 4, height: '100%', backgroundColor: '#d85218' }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ color: '#d85218', flexShrink: 0 }}>{icon}</div>
        <span style={{ fontSize: '0.75em', fontWeight: 700, letterSpacing: '1.5px', textTransform: 'uppercase', color: 'rgba(255,255,255,0.55)' }}>
          {role}
        </span>
      </div>
      <p style={{ fontSize: '1.375em', fontWeight: 600, color: '#fff', lineHeight: 1.3, margin: 0 }}>
        {headline}
      </p>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {points.map((pt) => (
          <li key={pt} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: '0.938em', color: 'rgba(255,255,255,0.72)', lineHeight: 1.5 }}>
            <span style={{ color: '#d85218', marginTop: 3, flexShrink: 0, fontSize: '0.75em' }}>◆</span>
            {pt}
          </li>
        ))}
      </ul>
    </div>
  );
}

// ─── Slider nav button ────────────────────────────────────────────────────────

function NavBtn({ direction, onClick, disabled }: { direction: 'prev' | 'next'; onClick: () => void; disabled: boolean }) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      aria-label={direction === 'prev' ? 'Previous' : 'Next'}
      className="ai-nav-btn"
      style={{
        width: 44,
        height: 44,
        borderRadius: '50%',
        border: `1px solid ${disabled ? 'rgba(255,255,255,0.1)' : 'rgba(255,255,255,0.25)'}`,
        backgroundColor: disabled ? 'transparent' : 'rgba(255,255,255,0.06)',
        color: disabled ? 'rgba(255,255,255,0.2)' : '#fff',
        cursor: disabled ? 'default' : 'pointer',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexShrink: 0,
        transition: 'background-color 0.2s, border-color 0.2s',
      }}
    >
      <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
        {direction === 'prev'
          ? <polyline points="9 2 4 7 9 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          : <polyline points="5 2 10 7 5 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        }
      </svg>
    </button>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

/** Slider is used when the viewport is narrower than this threshold. */
const SLIDER_BREAKPOINT = 900;

export default function AiSection() {
  const [useSlider, setUseSlider] = useState(false);
  const [card, setCard] = useState(0);
  const [slideDir, setSlideDir] = useState<'fwd' | 'bwd'>('fwd');
  const headingRef = useRef<HTMLDivElement>(null);
  const [headingVisible, setHeadingVisible] = useState(false);

  // Detect layout mode based on viewport width
  useEffect(() => {
    const check = () => setUseSlider(window.innerWidth < SLIDER_BREAKPOINT);
    check();
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);

  // Heading entrance animation — re-attach when layout switches so the ref is current
  useEffect(() => {
    const el = headingRef.current;
    if (!el) return;
    if (headingVisible) return; // already animated, no need to observe
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setHeadingVisible(true); observer.disconnect(); } },
      { threshold: 0.1 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, [useSlider, headingVisible]);

  const go = (next: number) => {
    if (next < 0 || next >= roles.length) return;
    setSlideDir(next > card ? 'fwd' : 'bwd');
    setCard(next);
  };

  // ── Shared decorative elements ─────────────────────────────────────────────
  const decorative = (
    <>
      <div style={{ position: 'absolute', top: 0, left: '-10%', width: '120%', height: 6, backgroundColor: '#d85218', transform: 'skewX(-20deg)', zIndex: 2, pointerEvents: 'none' }} />
      <div style={{ position: 'absolute', top: '30%', right: '-15%', width: '40%', height: '60%', backgroundColor: 'rgba(31,113,163,0.08)', transform: 'skewX(-15deg)', pointerEvents: 'none', zIndex: 0 }} />
    </>
  );

  // ── Shared heading ─────────────────────────────────────────────────────────
  const heading = (
    <div
      ref={headingRef}
      style={{
        opacity: headingVisible ? 1 : 0,
        transform: headingVisible ? 'translateY(0)' : 'translateY(24px)',
        transition: 'opacity 0.6s ease, transform 0.6s ease',
      }}
    >
      <p style={{ fontSize: '0.75em', fontWeight: 700, letterSpacing: '3px', textTransform: 'uppercase', color: '#d85218', margin: '0 0 16px' }}>
        Our Competitive Edge
      </p>
      <h2 style={{ fontSize: 'clamp(2rem, 4vw, 3.25rem)', fontWeight: 700, color: '#fff', lineHeight: 1.15, margin: '0 0 20px', letterSpacing: '-0.5px' }}>
        Every expert on our team<br />
        <span style={{ color: '#d85218' }}>amplified by AI.</span>
      </h2>
      <p style={{ maxWidth: 620, fontSize: '1.063em', color: 'rgba(255,255,255,0.65)', lineHeight: '28px', margin: 0 }}>
        At Bitsia, artificial intelligence is not a buzzword — it is woven into the daily workflow
        of every specialist. The result: faster delivery, sharper output, and measurably better
        outcomes for every client project.
      </p>
    </div>
  );

  // ── Shared callout ─────────────────────────────────────────────────────────
  const callout = (
    <div
      style={{
        padding: '36px 40px',
        backgroundColor: '#d85218',
        display: 'flex',
        flexWrap: 'wrap',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: 20,
      }}
    >
      <p style={{ color: '#fff', fontSize: '1.25em', fontWeight: 600, lineHeight: 1.4, margin: 0, maxWidth: 560 }}>
        The same project scope. Delivered with greater precision — and in less time.
      </p>
      <a
        href="#contact-us"
        style={{
          display: 'inline-block',
          backgroundColor: '#fff',
          color: '#d85218',
          fontWeight: 700,
          fontSize: '0.875em',
          letterSpacing: '1.5px',
          textTransform: 'uppercase',
          padding: '14px 32px',
          textDecoration: 'none',
          whiteSpace: 'nowrap',
          flexShrink: 0,
        }}
      >
        Start a Project
      </a>
    </div>
  );

  // ── Slider layout (compact screens) ───────────────────────────────────────
  if (useSlider) {
    return (
      <section
        id="ai"
        style={{ position: 'relative', height: '100vh', backgroundColor: '#001545', overflow: 'hidden' }}
      >
        {decorative}
        <div
          className="ai-layout"
          style={{
            position: 'relative',
            zIndex: 1,
            height: '100%',
            display: 'flex',
            flexDirection: 'column',
            maxWidth: 1200,
            margin: '0 auto',
            padding: '96px 40px 36px',
            boxSizing: 'border-box',
          }}
        >
          {/* Compact heading for slider */}
          <div
            ref={headingRef}
            style={{
              flexShrink: 0,
              marginBottom: 24,
              opacity: headingVisible ? 1 : 0,
              transform: headingVisible ? 'translateY(0)' : 'translateY(24px)',
              transition: 'opacity 0.6s ease, transform 0.6s ease',
            }}
          >
            <p style={{ fontSize: '0.75em', fontWeight: 700, letterSpacing: '3px', textTransform: 'uppercase', color: '#d85218', margin: '0 0 10px' }}>
              Our Competitive Edge
            </p>
            <h2 style={{ fontSize: 'clamp(1.6rem, 3vw, 2.5rem)', fontWeight: 700, color: '#fff', lineHeight: 1.15, margin: '0 0 10px', letterSpacing: '-0.5px' }}>
              Every expert on our team{' '}
              <span style={{ color: '#d85218' }}>amplified by AI.</span>
            </h2>
            <p className="ai-desc" style={{ maxWidth: 580, fontSize: '0.938em', color: 'rgba(255,255,255,0.6)', lineHeight: '22px', margin: 0 }}>
              AI is woven into the daily workflow of every specialist — faster delivery, sharper output.
            </p>
          </div>

          {/* Slider */}
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 16, minHeight: 0 }}>
            <NavBtn direction="prev" onClick={() => go(card - 1)} disabled={card === 0} />

            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 16, minHeight: 0 }}>
              <div key={card} className={`ai-card-${slideDir}`} style={{ flex: 1, minHeight: 0 }}>
                <SliderRoleCard {...roles[card]} />
              </div>
              {/* Dots */}
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, flexShrink: 0 }}>
                {roles.map((_, i) => (
                  <button
                    key={i}
                    onClick={() => go(i)}
                    aria-label={`Slide ${i + 1}`}
                    style={{
                      width: i === card ? 28 : 8,
                      height: 8,
                      borderRadius: 4,
                      backgroundColor: i === card ? '#d85218' : 'rgba(255,255,255,0.22)',
                      border: 'none',
                      cursor: 'pointer',
                      padding: 0,
                      transition: 'width 0.3s ease, background-color 0.3s ease',
                    }}
                  />
                ))}
              </div>
            </div>

            <NavBtn direction="next" onClick={() => go(card + 1)} disabled={card === roles.length - 1} />
          </div>

          {/* Callout (compact) */}
          <div
            style={{
              flexShrink: 0,
              marginTop: 20,
              padding: '18px 28px',
              backgroundColor: '#d85218',
              display: 'flex',
              flexWrap: 'wrap',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: 12,
            }}
          >
            <p style={{ color: '#fff', fontSize: '1em', fontWeight: 600, lineHeight: 1.4, margin: 0 }}>
              The same scope. Greater precision. Less time.
            </p>
            <a href="#contact-us" style={{ display: 'inline-block', backgroundColor: '#fff', color: '#d85218', fontWeight: 700, fontSize: '0.813em', letterSpacing: '1.5px', textTransform: 'uppercase', padding: '10px 22px', textDecoration: 'none', whiteSpace: 'nowrap', flexShrink: 0 }}>
              Start a Project
            </a>
          </div>
        </div>
      </section>
    );
  }

  // ── Grid layout (desktop) ──────────────────────────────────────────────────
  return (
    <section
      id="ai"
      style={{ position: 'relative', backgroundColor: '#001545', overflow: 'hidden', padding: '96px 0 80px' }}
    >
      {decorative}
      <div style={{ position: 'relative', zIndex: 1, maxWidth: 1200, margin: '0 auto', padding: '0 40px' }}>
        <div style={{ marginBottom: 64 }}>{heading}</div>

        {/* Role cards grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 20 }}>
          {roles.map((r, i) => (
            <GridRoleCard key={r.role} {...r} index={i} />
          ))}
        </div>

        {/* Callout */}
        <div style={{ marginTop: 64 }}>{callout}</div>
      </div>
    </section>
  );
}
