import Image from 'next/image';
import React from 'react';

import Link from '@/components/link/Link';
import { FeatureConfig } from '@/state/sessionStore';

import { getFeatureIcon } from './featureIconMap';

interface FeatureHeaderProps {
  feature: FeatureConfig;
}

const parseSubtitleWithLinks = (text: string): React.ReactNode => {
  // return original text if no potential links found
  if (!text.includes('[') || !text.includes('](')) {
    return text;
  }

  const parts: React.ReactNode[] = [];
  const regex = /\[([^\]]+)\]\(([^)]+)\)/g; // markdown-style link pattern: [text](url)
  let lastIndex = 0;
  let match;
  let keyIndex = 0;

  while ((match = regex.exec(text)) !== null) {
    // add text before the current link
    if (match.index > lastIndex) {
      const beforeText = text.substring(lastIndex, match.index);
      if (beforeText) {
        parts.push(
          <React.Fragment key={`text-${keyIndex++}`}>
            {beforeText}
          </React.Fragment>
        );
      }
    }

    // add the link
    const linkText = match[1];
    const linkUrl = match[2];
    parts.push(
      <Link
        key={`link-${keyIndex++}`}
        href={linkUrl}
        target='_blank'
        rel='noopener noreferrer'
        className='text-white underline transition-colors hover:text-white/60'
      >
        {linkText}
      </Link>
    );
    lastIndex = regex.lastIndex;
  }

  // add remaining text after the last link
  if (lastIndex < text.length) {
    const remainingText = text.substring(lastIndex);
    if (remainingText) {
      parts.push(
        <React.Fragment key={`text-${keyIndex++}`}>
          {remainingText}
        </React.Fragment>
      );
    }
  }

  // if no links were found, return the original text
  if (parts.length === 0) {
    return text;
  }

  return <>{parts}</>;
};

export const FeatureHeader = ({ feature }: FeatureHeaderProps) => {
  const { title, subtitle, icon, background_image } = feature;

  const backgroundImageSrc =
    background_image || 'https://cdn-o.suno.com/Upsell_CropFade_gradient.jpg';

  return (
    <div className='relative w-full overflow-hidden'>
      <div className='relative h-[200px] w-full overflow-hidden'>
        <Image
          src={backgroundImageSrc}
          alt={title}
          fill
          className='pointer-events-none object-cover'
          style={{
            maskImage:
              'linear-gradient(to bottom, black 80%, transparent 100%)',
            WebkitMaskImage:
              'linear-gradient(to bottom, black 80%, transparent 100%)',
          }}
        />
        <div className='absolute inset-0' />
      </div>
      <div className='absolute inset-0 mb-[-10] flex flex-col items-center justify-end px-4 pb-5'>
        <div className='flex h-12 w-12 items-center justify-center rounded-full'>
          {getFeatureIcon(icon)}
        </div>
        <h2 className='text-center font-serif text-[40px] leading-tight font-light text-white/90'>
          {title}
        </h2>
        <p className='max-w-[280px] text-center font-sans text-sm leading-tight font-normal text-white/80'>
          {parseSubtitleWithLinks(subtitle)}
        </p>
      </div>
    </div>
  );
};
