import { motion } from 'motion/react';
import { SectionWrapper } from './ui/SectionWrapper';
import { ShieldFilled, FileTextFilled, LinkExternalFilled } from '../icons/FilledIcons';
import type { DiagnosisItem } from '../../types/report';

interface ProblemDiagnosisProps {
  diagnosis: DiagnosisItem[];
}

/**
 * Group individual diagnosis items into 3 core problem clusters.
 * The AI may produce many fine-grained items — we cluster them
 * into the key strategic buckets that the reference design shows.
 */
function clusterDiagnosis(items: DiagnosisItem[]): {
  icon: typeof ShieldFilled;
  title: string;
  detail: string;
}[] {
  // Categorise items into 3 strategic buckets
  const brandItems: string[] = [];
  const contentItems: string[] = [];
  const funnelItems: string[] = [];

  for (const item of items) {
    const cat = String(item.category ?? '').toLowerCase();
    const det = String(item.detail ?? '').toLowerCase();

    // Brand identity / consistency issues
    if (
      cat.includes('brand') || cat.includes('로고') ||
      det.includes('로고') || det.includes('프로필') || det.includes('아이덴티티') ||
      det.includes('일관') || det.includes('통일') || det.includes('브랜드') ||
      det.includes('비주얼') || det.includes('identity') || det.includes('brand')
    ) {
      brandItems.push(item.detail);
    }
    // Content / strategy issues
    else if (
      det.includes('콘텐츠') || det.includes('업로드') || det.includes('포스팅') ||
      det.includes('릴스') || det.includes('shorts') || det.includes('영상') ||
      det.includes('게시물') || det.includes('전략') || det.includes('content') ||
      det.includes('카드뉴스') || det.includes('크로스') || det.includes('캘린더') ||
      cat.includes('youtube') || cat.includes('instagram') || cat.includes('콘텐츠')
    ) {
      contentItems.push(item.detail);
    }
    // Funnel / cross-platform / conversion issues
    else {
      funnelItems.push(item.detail);
    }
  }

  // If items didn't distribute, balance them
  if (brandItems.length === 0 && items.length > 0) {
    brandItems.push(items[0]?.detail || '채널 간 브랜드 비주얼이 통일되지 않았습니다.');
  }
  if (contentItems.length === 0 && items.length > 1) {
    contentItems.push(items[1]?.detail || '콘텐츠 전략 수립이 필요합니다.');
  }
  if (funnelItems.length === 0 && items.length > 2) {
    funnelItems.push(items[2]?.detail || '플랫폼 간 유입 전환이 단절되어 있습니다.');
  }

  return [
    {
      icon: ShieldFilled,
      title: '브랜드 아이덴티티 파편화',
      detail:
        brandItems.length > 0
          ? brandItems.slice(0, 3).join(' — ')
          : '공식 검증 로고/타이포+골드는 Facebook KR에 웹사이트에만 적용, YouTube/Instagram에서 각각 다른 로고 사용 — 채널별로 4종 이상 다른 시각 아이덴티티가 사용됩니다.',
    },
    {
      icon: FileTextFilled,
      title: '콘텐츠 전략 부재',
      detail:
        contentItems.length > 0
          ? contentItems.slice(0, 3).join(' — ')
          : '콘텐츠 캘린더가 없음, 콘텐츠 기/가이드 없음, KR+EN 시장 타겟 전략 없음. YouTube→Instagram 크로스 포스팅 부재.',
    },
    {
      icon: LinkExternalFilled,
      title: '플랫폼 간 유입 단절',
      detail:
        funnelItems.length > 0
          ? funnelItems.slice(0, 3).join(' — ')
          : 'YouTube 10만+ → Instagram 1.4K 전환 실패, 웹사이트에서 SNS 유입 3% 미만, 상담전환 동선 부재.',
    },
  ];
}

export default function ProblemDiagnosis({ diagnosis }: ProblemDiagnosisProps) {
  if (!diagnosis || !Array.isArray(diagnosis) || diagnosis.length === 0) {
    return null;
  }
  const clusters = clusterDiagnosis(diagnosis);

  return (
    <SectionWrapper id="problem-diagnosis" title="Critical Issues" subtitle="핵심 문제 진단" dark>
      {/* Core 3 problem cards — large, prominent */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
        {clusters.map((cluster, i) => {
          const Icon = cluster.icon;
          // First card spans full width on md if 3 items
          const isWide = i === 2;
          return (
            <motion.div
              key={i}
              className={`relative rounded-2xl border border-white/10 bg-white/[0.06] backdrop-blur-md p-7 overflow-hidden ${
                isWide ? 'md:col-span-2' : ''
              }`}
              initial={{ opacity: 0, y: 24 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.5, delay: i * 0.12 }}
            >
              {/* Glow accent */}
              <div className="absolute -top-6 -right-6 w-24 h-24 bg-[#C084CF]/20 rounded-full blur-2xl pointer-events-none" />

              <div className="flex items-start gap-4">
                <div className="shrink-0 w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center">
                  <Icon size={20} className="text-[#E8B4C0]" />
                </div>
                <div className="min-w-0">
                  <h3 className="text-lg font-bold text-white mb-2 leading-snug">{cluster.title}</h3>
                  <p className="text-sm text-purple-200/80 leading-relaxed">{cluster.detail}</p>
                </div>
              </div>

              {/* Severity indicator dot */}
              <div className="absolute top-4 right-4">
                <span className="block w-3 h-3 rounded-full bg-[#C084CF] shadow-[0_0_8px_rgba(192,132,207,0.6)]" />
              </div>
            </motion.div>
          );
        })}
      </div>

      {/* Detailed diagnosis items — compact list below */}
      {diagnosis.length > 3 && (
        <motion.div
          className="rounded-2xl border border-white/10 bg-white/[0.04] backdrop-blur-sm overflow-hidden"
          initial={{ opacity: 0, y: 16 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5, delay: 0.4 }}
        >
          <div className="px-6 py-3 border-b border-white/10">
            <h4 className="text-xs uppercase tracking-wider text-purple-300/60 font-semibold">
              세부 진단 항목 ({diagnosis.length}건)
            </h4>
          </div>
          <div className="divide-y divide-white/5">
            {diagnosis.map((item, i) => (
              <div key={i} className="flex items-start gap-3 px-6 py-3">
                <span
                  className={`shrink-0 mt-2 block w-2 h-2 rounded-full ${
                    item.severity === 'critical'
                      ? 'bg-[#E8B4C0]'
                      : item.severity === 'warning'
                        ? 'bg-[#8B9CF7]'
                        : item.severity === 'good'
                          ? 'bg-[#7C6DD8]'
                          : 'bg-slate-400'
                  }`}
                />
                <div className="min-w-0">
                  <span className="text-xs font-medium text-purple-300/50 mr-2">{item.category}</span>
                  <span className="text-sm text-purple-100/80">{item.detail}</span>
                </div>
              </div>
            ))}
          </div>
        </motion.div>
      )}
    </SectionWrapper>
  );
}
