// components/sections/DetailedServiceCard.tsx
// Comprehensive multi-panel service review card
// 5 themes: default, warm, professional, ocean, forest
'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { getLinkAttributes, type LinkTarget, type LinkRel } from '@/lib/puck/linkHelpers';
import { CheckCircle, Shield, Copy, ChevronDown, ChevronUp } from 'lucide-react';

// --- Radar Chart  SVG ---
function RadarChart({
  labels,
  values,
  maxValue = 5,
  size = 180,
  fillColor = 'rgba(16,185,129,0.2)',
  strokeColor = 'rgb(16,185,129)',
  gridColor = '#e2e8f0',
  labelColor = '#475569',
}: {
  labels: string[];
  values: number[];
  maxValue?: number;
  size?: number;
  fillColor?: string;
  strokeColor?: string;
  gridColor?: string;
  labelColor?: string;
}) {
  const cx = size / 2;
  const cy = size / 2;
  const radius = size * 0.32;
  const n = labels.length;
  if (n < 3) return null;

  const angleStep = (2 * Math.PI) / n;
  const startAngle = -Math.PI / 2;
  const getPoint = (i: number, r: number) => ({
    x: cx + r * Math.cos(startAngle + i * angleStep),
    y: cy + r * Math.sin(startAngle + i * angleStep),
  });

  const gridLevels = [0.2, 0.4, 0.6, 0.8, 1.0];
  const dataPoints = values.map((v, i) => {
    const ratio = Math.min(v, maxValue) / maxValue;
    return getPoint(i, radius * ratio);
  });
  const dataPath = dataPoints.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x},${p.y}`).join(' ') + ' Z';

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="mx-auto">
      {gridLevels.map((level) => {
        const pts = Array.from({ length: n }, (_, i) => getPoint(i, radius * level));
        const path = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x},${p.y}`).join(' ') + ' Z';
        return <path key={level} d={path} fill="none" stroke={gridColor} strokeWidth="1" />;
      })}
      {Array.from({ length: n }, (_, i) => {
        const p = getPoint(i, radius);
        return <line key={i} x1={cx} y1={cy} x2={p.x} y2={p.y} stroke={gridColor} strokeWidth="1" />;
      })}
      <path d={dataPath} fill={fillColor} stroke={strokeColor} strokeWidth="2" />
      {dataPoints.map((p, i) => (
        <circle key={i} cx={p.x} cy={p.y} r="3" fill={strokeColor} />
      ))}
      {labels.map((label, i) => {
        const labelRadius = radius + 22;
        const pt = getPoint(i, labelRadius);
        const anchor = pt.x < cx - 5 ? 'end' : pt.x > cx + 5 ? 'start' : 'middle';
        return (
          <text key={i} x={pt.x} y={pt.y} textAnchor={anchor} dominantBaseline="central"
            fontSize="10" fontWeight="600" fill={labelColor}>
            {label}
          </text>
        );
      })}
    </svg>
  );
}

// --- Stars ---
function Stars({ rating, max = 5, color = '#f59e0b' }: { rating: number; max?: number; color?: string }) {
  return (
    <span className="inline-flex gap-0.5">
      {Array.from({ length: max }, (_, i) => {
        const filled = i < Math.floor(rating);
        const half = !filled && i < rating;
        return (
          <svg key={i} width="14" height="14" viewBox="0 0 20 20" fill={filled ? color : half ? color : '#d1d5db'} opacity={half ? 0.5 : 1}>
            <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.286 3.957a1 1 0 00.95.69h4.162c.969 0 1.371 1.24.588 1.81l-3.37 2.448a1 1 0 00-.364 1.118l1.287 3.957c.3.921-.755 1.688-1.54 1.118l-3.37-2.448a1 1 0 00-1.176 0l-3.37 2.448c-.783.57-1.838-.197-1.539-1.118l1.287-3.957a1 1 0 00-.364-1.118L2.065 9.384c-.783-.57-.38-1.81.588-1.81h4.162a1 1 0 00.95-.69l1.284-3.957z" />
          </svg>
        );
      })}
    </span>
  );
}

// --- Theme System ---
type ThemeKey = 'default' | 'warm' | 'professional' | 'ocean' | 'forest';

interface ThemeStyles {
  card: string; headerBar: string; headerText: string; taglineBar: string;
  bonusLabel: string; bonusValue: string; bonusTableBg: string; bonusTableBorder: string;
  codeBg: string; codeText: string; featureDot: string; primaryCta: string;
  secondaryLink: string; sectionTitle: string; sectionIcon: string;
  radarFill: string; radarStroke: string; starColor: string;
  trustIcon: string; trustBar: string; badgeBg: string; badgeIcon: string; toggleBtn: string;
}

const THEMES: Record<ThemeKey, ThemeStyles> = {
  default: {
    card: 'bg-white rounded-2xl border border-slate-200 shadow-sm',
    headerBar: 'bg-slate-800',
    headerText: 'text-white',
    taglineBar: 'bg-emerald-500 text-white text-xs py-1 px-4 font-bold',
    bonusLabel: 'text-text-light-gray text-xs font-bold',
    bonusValue: 'text-emerald-600 font-bold text-lg',
    bonusTableBg: 'bg-slate-50',
    bonusTableBorder: 'border-slate-200',
    codeBg: 'bg-amber-50 border-amber-300',
    codeText: 'text-amber-700 font-mono font-bold text-sm',
    featureDot: 'text-emerald-500',
    primaryCta: 'bg-emerald-600 hover:bg-emerald-700 text-white font-bold',
    secondaryLink: 'text-emerald-600 hover:text-emerald-700',
    sectionTitle: 'text-white',
    sectionIcon: 'text-emerald-500',
    radarFill: 'rgba(16,185,129,0.2)',
    radarStroke: 'rgb(16,185,129)',
    starColor: '#f59e0b',
    trustIcon: 'text-emerald-500',
    trustBar: 'bg-emerald-500',
    badgeBg: 'bg-slate-50 border-slate-200',
    badgeIcon: 'text-emerald-500',
    toggleBtn: 'text-text-light-gray hover:text-white',
  },
  warm: {
    card: 'bg-white rounded-2xl border border-orange-200 shadow-sm',
    headerBar: 'bg-gradient-to-r from-orange-600 to-red-600',
    headerText: 'text-white',
    taglineBar: 'bg-orange-500 text-white text-xs py-1 px-4 font-bold',
    bonusLabel: 'text-slate-500 text-xs font-bold',
    bonusValue: 'text-orange-600 font-bold text-lg',
    bonusTableBg: 'bg-orange-50/50',
    bonusTableBorder: 'border-orange-200',
    codeBg: 'bg-orange-50 border-orange-300',
    codeText: 'text-orange-700 font-mono font-bold text-sm',
    featureDot: 'text-orange-500',
    primaryCta: 'bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white font-bold shadow-lg shadow-orange-500/20',
    secondaryLink: 'text-orange-600 hover:text-orange-700',
    sectionTitle: 'text-slate-800',
    sectionIcon: 'text-orange-500',
    radarFill: 'rgba(249,115,22,0.2)',
    radarStroke: 'rgb(249,115,22)',
    starColor: '#f97316',
    trustIcon: 'text-orange-500',
    trustBar: 'bg-orange-500',
    badgeBg: 'bg-orange-50 border-orange-200',
    badgeIcon: 'text-orange-500',
    toggleBtn: 'text-slate-500 hover:text-slate-700',
  },
  professional: {
    card: 'bg-white rounded-2xl border border-slate-200 shadow-sm',
    headerBar: 'bg-slate-900',
    headerText: 'text-white',
    taglineBar: 'bg-amber-500 text-slate-900 text-xs py-1 px-4 font-bold',
    bonusLabel: 'text-slate-500 text-xs font-bold',
    bonusValue: 'text-slate-800 font-bold text-lg',
    bonusTableBg: 'bg-slate-50',
    bonusTableBorder: 'border-slate-200',
    codeBg: 'bg-amber-50 border-amber-400',
    codeText: 'text-slate-800 font-mono font-bold text-sm',
    featureDot: 'text-amber-500',
    primaryCta: 'bg-slate-800 hover:bg-slate-700 text-white font-bold shadow-lg',
    secondaryLink: 'text-slate-600 hover:text-slate-800',
    sectionTitle: 'text-slate-800',
    sectionIcon: 'text-slate-600',
    radarFill: 'rgba(30,41,59,0.15)',
    radarStroke: 'rgb(30,41,59)',
    starColor: '#d97706',
    trustIcon: 'text-emerald-600',
    trustBar: 'bg-slate-700',
    badgeBg: 'bg-slate-50 border-slate-200',
    badgeIcon: 'text-amber-500',
    toggleBtn: 'text-slate-500 hover:text-slate-700',
  },
  ocean: {
    card: 'bg-white rounded-2xl border border-blue-200 shadow-sm',
    headerBar: 'bg-gradient-to-r from-blue-700 to-indigo-700',
    headerText: 'text-white',
    taglineBar: 'bg-cyan-500 text-white text-xs py-1 px-4 font-bold',
    bonusLabel: 'text-slate-500 text-xs font-bold',
    bonusValue: 'text-blue-600 font-bold text-lg',
    bonusTableBg: 'bg-blue-50/50',
    bonusTableBorder: 'border-blue-200',
    codeBg: 'bg-blue-50 border-blue-300',
    codeText: 'text-blue-700 font-mono font-bold text-sm',
    featureDot: 'text-blue-500',
    primaryCta: 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-bold shadow-lg shadow-blue-600/20',
    secondaryLink: 'text-blue-600 hover:text-blue-700',
    sectionTitle: 'text-slate-800',
    sectionIcon: 'text-blue-500',
    radarFill: 'rgba(59,130,246,0.2)',
    radarStroke: 'rgb(59,130,246)',
    starColor: '#3b82f6',
    trustIcon: 'text-blue-500',
    trustBar: 'bg-blue-500',
    badgeBg: 'bg-blue-50 border-blue-200',
    badgeIcon: 'text-blue-500',
    toggleBtn: 'text-slate-500 hover:text-slate-700',
  },
  forest: {
    card: 'bg-white rounded-2xl border border-emerald-200 shadow-sm',
    headerBar: 'bg-gradient-to-r from-emerald-700 to-teal-700',
    headerText: 'text-white',
    taglineBar: 'bg-green-500 text-white text-xs py-1 px-4 font-bold',
    bonusLabel: 'text-slate-500 text-xs font-bold',
    bonusValue: 'text-emerald-600 font-bold text-lg',
    bonusTableBg: 'bg-emerald-50/50',
    bonusTableBorder: 'border-emerald-200',
    codeBg: 'bg-green-50 border-green-300',
    codeText: 'text-green-700 font-mono font-bold text-sm',
    featureDot: 'text-emerald-500',
    primaryCta: 'bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 text-white font-bold shadow-lg shadow-emerald-600/20',
    secondaryLink: 'text-emerald-600 hover:text-emerald-700',
    sectionTitle: 'text-slate-800',
    sectionIcon: 'text-emerald-500',
    radarFill: 'rgba(16,185,129,0.2)',
    radarStroke: 'rgb(16,185,129)',
    starColor: '#10b981',
    trustIcon: 'text-emerald-500',
    trustBar: 'bg-emerald-500',
    badgeBg: 'bg-emerald-50 border-emerald-200',
    badgeIcon: 'text-emerald-500',
    toggleBtn: 'text-slate-500 hover:text-slate-700',
  },
};

// --- Props ---
interface DetailedServiceCardProps {
  rank?: number;
  name?: string;
  tagline?: string;
  logo?: string;
  overallRating?: number;
  bonusTitle?: string;
  bonusAmount?: string;
  bonusCondition?: string;
  bonusSpeed?: string;
  bonusCode?: string;
  features?: string;
  primaryCtaText?: string;
  primaryCtaUrl?: string;
  secondaryCtaText?: string;
  secondaryCtaUrl?: string;
  expertTitle?: string;
  expertDescription?: string;
  expertAuthor?: string;
  radarLabels?: string;
  radarValues?: string;
  trustStatus?: string;
  licenseRating?: number;
  licenseName?: string;
  gameTypes?: string;
  paymentMethods?: string;
  supportInfo?: string;
  serviceBadges?: string;
  theme?: ThemeKey;
  forceExpanded?: boolean;
  openInNewTab?: LinkTarget;
  relAttribute?: LinkRel;
}

export function DetailedServiceCard({
  rank = 1,
  name = '',
  tagline = '',
  logo = '',
  overallRating = 4.6,
  bonusTitle = '',
  bonusAmount = '',
  bonusCondition = '',
  bonusSpeed = '',
  bonusCode = '',
  features = '',
  primaryCtaText = '',
  primaryCtaUrl = '#',
  secondaryCtaText = '',
  secondaryCtaUrl = '#',
  expertTitle = '',
  expertDescription = '',
  expertAuthor = '',
  radarLabels = '',
  radarValues = '5\n4.4\n5\n3.8\n4.2\n5',
  trustStatus = '',
  licenseRating = 4,
  licenseName = '',
  gameTypes = '',
  paymentMethods = '',
  supportInfo = '',
  serviceBadges = '',
  theme = 'default',
  forceExpanded = false,
  openInNewTab = 'new',
  relAttribute = 'sponsored',
}: DetailedServiceCardProps) {
  const t = THEMES[theme] || THEMES.default;
  const linkAttrs = getLinkAttributes({ openInNewTab, relAttribute });
  const [expanded, setExpanded] = useState(forceExpanded);

  // Parse delimited fields
  const parsedFeatures = (features || '').split('\n').map(s => s.trim()).filter(Boolean);
  const parsedRadarLabels = (radarLabels || '').split('\n').map(s => s.trim()).filter(Boolean);
  const parsedRadarValues = (radarValues || '').split('\n').map(s => parseFloat(s.trim()) || 0);
  const parsedGameTypes = (gameTypes || '').split(',').map(s => s.trim()).filter(Boolean);
  const parsedPayments = (paymentMethods || '').split(',').map(s => s.trim()).filter(Boolean);
  const parsedSupport = (supportInfo || '').split('\n').map(s => s.trim()).filter(Boolean);
  const parsedBadges = (serviceBadges || '').split(',').map(s => s.trim()).filter(Boolean);

  return (
    <section className="w-full py-4">
      <div className="container max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className={`${t.card} overflow-hidden`}>
          {/* Tagline bar */}
          {tagline && (
            <div className={t.taglineBar}>{tagline}</div>
          )}

          {/* Header bar */}
          <div className={`${t.headerBar} px-6 py-4 flex items-center gap-3`}>
            <span className={`text-2xl font-black ${t.headerText}`}>{rank || '?'}</span>
            <h2 className={`text-xl md:text-2xl font-bold ${t.headerText}`}>{name || ''}</h2>
          </div><div className="p-6">
            <div className="flex flex-col md:flex-row gap-6">
              {/* Logo */}
              <div className="flex-shrink-0 flex flex-col items-center gap-3">
                {logo ? (
                  <div className="w-52 rounded-xl overflow-hidden border border-slate-200 shadow-sm">
                    <img src={logo} alt={name || ''} className="w-full object-contain" />
                  </div>
                ) : (
                  <div className="w-52 h-40 bg-slate-100 rounded-xl flex items-center justify-center text-slate-400"></div>
                )}
                <div className="flex items-center gap-1.5">
                  <span className="text-sm font-bold text-white">{overallRating}</span>
                  <Stars rating={overallRating} color={t.starColor} />
                </div>
              </div>

              {/* Bonus section */}
              <div className="flex-1">
                <h3 className={`text-sm font-bold mb-4 flex items-center gap-2 ${t.sectionTitle}`}>
                  <Shield className={`w-4 h-4 ${t.sectionIcon}`} />
                  {bonusTitle}
                </h3>

                {/* Bonus table */}
                <div className={`rounded-xl border ${t.bonusTableBorder} ${t.bonusTableBg} p-4 mb-4`}>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
                    <div>
                      <div className={t.bonusLabel}></div>
                      <div className={t.bonusValue}>{bonusAmount}</div>
                    </div>
                    <div>
                      <div className={t.bonusLabel}></div>
                      <div className="font-bold text-white">{bonusCondition}</div>
                    </div>
                    <div>
                      <div className={t.bonusLabel}></div>
                      <div className="font-bold text-white">{bonusSpeed}</div>
                    </div>
                    {bonusCode && (
                      <div>
                        <div className={t.bonusLabel}></div>
                        <div className={`inline-flex items-center gap-1 px-2 py-1 rounded border ${t.codeBg}`}>
                          <span className={t.codeText}>{bonusCode}</span>
                          <Copy className="w-3 h-3 text-slate-400 cursor-pointer hover:text-slate-600" />
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                {/* Feature bullets */}
                {parsedFeatures.length > 0 && (
                  <div className="space-y-1.5 mb-5">
                    {parsedFeatures.map((f, i) => (
                      <div key={i} className="flex items-start gap-2 text-sm text-text-light-gray">
                        <span className={`mt-1 ${t.featureDot}`}></span>
                        {f}
                      </div>
                    ))}
                  </div>
                )}

                {/* CTAs */}
                <div className="flex flex-col sm:flex-row gap-3">
                  {primaryCtaText && (
                    <Link
                      href={primaryCtaUrl || '#'}
          {...linkAttrs}
                      className={`inline-flex items-center justify-center px-8 py-3 rounded-xl transition-all duration-300 text-sm ${t.primaryCta}`}
                    >
                      {primaryCtaText}
                    </Link>
                  )}
                  {secondaryCtaText && (
                    <Link
                      href={secondaryCtaUrl || '#'}
          {...linkAttrs}
                      className={`inline-flex items-center gap-1 text-sm font-bold underline ${t.secondaryLink}`}
                    ></Link>
                  )}
                </div>
              </div>
            </div>
          </div><div className={`transition-all duration-500 overflow-hidden ${expanded ? 'max-h-[3000px] opacity-100' : 'max-h-0 opacity-0'}`}><div className="px-6 pb-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {/* Expert Review */}
                <div className="border border-slate-200 rounded-xl p-4">
                  <h4 className={`text-sm font-bold mb-2 flex items-center gap-2 ${t.sectionTitle}`}></h4>
                  <div className="flex items-center gap-2 mb-3">
                    <span className="text-sm font-bold"></span>
                    <Stars rating={overallRating} color={t.starColor} />
                  </div>
                  {expertDescription && (
                    <p className="text-xs text-text-light-gray leading-relaxed mb-3">{expertDescription}</p>
                  )}
                  {expertAuthor && (
                    <div className="text-xs text-text-light-gray"></div>
                  )}
                </div>

                {/* Radar Chart */}
                <div className="border border-slate-200 rounded-xl p-4 flex items-center justify-center">
                  {parsedRadarLabels.length >= 3 && (
                    <RadarChart
                      labels={parsedRadarLabels}
                      values={parsedRadarValues}
                      fillColor={t.radarFill}
                      strokeColor={t.radarStroke}
                    />
                  )}
                </div>

                {/* Trust Check */}
                <div className="border border-slate-200 rounded-xl p-4">
                  <h4 className={`text-sm font-bold mb-4 flex items-center gap-2 ${t.sectionTitle}`}></h4>
                  <div className="flex flex-col items-center gap-3 mb-4">
                    <CheckCircle className={`w-10 h-10 ${t.trustIcon}`} />
                    <span className="text-sm font-bold text-white">{trustStatus}</span>
                    <div className={`w-full h-1.5 rounded-full ${t.trustBar}`} />
                  </div>
                  {licenseName && (
                    <div className="text-center">
                      <div className="text-xs font-bold text-text-light-gray mb-1"></div>
                      <div className="flex items-center justify-center gap-2">
                        <Stars rating={licenseRating || 0} color={t.starColor} />
                      </div>
                      <div className="text-xs text-text-light-gray mt-1">{licenseName}</div>
                    </div>
                  )}
                </div>
              </div>
            </div><div className="px-6 pb-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {/* Game Types */}
                {parsedGameTypes.length > 0 && (
                  <div className="border border-slate-200 rounded-xl p-4">
                    <h4 className={`text-sm font-bold mb-3 flex items-center gap-2 ${t.sectionTitle}`}></h4>
                    <div className="flex flex-wrap gap-2">
                      {parsedGameTypes.map((g, i) => (
                        <span key={i} className="inline-flex items-center gap-1 text-xs px-2.5 py-1 rounded-full bg-slate-100 text-text-light-gray">
                          <CheckCircle className={`w-3 h-3 ${t.sectionIcon}`} /> {g}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                {/* Payment Methods */}
                {parsedPayments.length > 0 && (
                  <div className="border border-slate-200 rounded-xl p-4">
                    <h4 className={`text-sm font-bold mb-3 flex items-center gap-2 ${t.sectionTitle}`}></h4>
                    <div className="flex flex-wrap gap-2">
                      {parsedPayments.map((p, i) => (
                        <span key={i} className="text-xs px-2.5 py-1 rounded-lg border border-slate-200 bg-white text-text-light-gray">
                          {p}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                {/* Customer Support */}
                {parsedSupport.length > 0 && (
                  <div className="border border-slate-200 rounded-xl p-4">
                    <h4 className={`text-sm font-bold mb-3 flex items-center gap-2 ${t.sectionTitle}`}></h4>
                    <div className="space-y-2">
                      {parsedSupport.map((s, i) => (
                        <div key={i} className="text-xs text-text-light-gray flex items-start gap-2">
                          <span className={`mt-0.5 ${t.sectionIcon}`}></span> {s}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Zone 4: Service Badges */}
            {parsedBadges.length > 0 && (
              <div className="px-6 pb-6">
                <h4 className={`text-sm font-bold mb-3 flex items-center gap-2 ${t.sectionTitle}`}></h4>
                <div className="flex flex-wrap gap-3">
                  {parsedBadges.map((badge, i) => (
                    <div key={i} className={`inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border text-sm font-medium text-white ${t.badgeBg}`}>
                      <CheckCircle className={`w-4 h-4 ${t.badgeIcon}`} />
                      {badge}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Toggle button */}
          <button
            onClick={() => setExpanded(!expanded)}
            className={`w-full py-3 text-sm font-bold flex items-center justify-center gap-1 border-t border-slate-100 transition-colors ${t.toggleBtn}`}
          >
            {expanded ? (
              <>
                <ChevronUp className="w-4 h-4" /></>
            ) : (
              <>
                <ChevronDown className="w-4 h-4" /></>
            )}
          </button>
        </div>
      </div>
    </section>
  );
}
