// components/sections/ServiceDetailBlock.tsx
// Single-service deep-dive review block with radar chart, ratings, pros/cons
// 5 themes: default, warm, professional, ocean, forest
'use client';

import React from 'react';
import Link from 'next/link';
import { getLinkAttributes, type LinkTarget, type LinkRel } from '@/lib/puck/linkHelpers';
import { CheckCircle, AlertCircle, Pencil } from 'lucide-react';

// --- Radar Chart  SVG ---
interface RadarChartProps {
  labels: string[];
  values: number[];
  maxValue?: number;
  size?: number;
  fillColor?: string;
  strokeColor?: string;
  gridColor?: string;
  labelColor?: string;
}

function RadarChart({
  labels,
  values,
  maxValue = 5,
  size = 200,
  fillColor = 'rgba(239,68,68,0.25)',
  strokeColor = 'rgb(239,68,68)',
  gridColor = '#e2e8f0',
  labelColor = '#475569',
}: RadarChartProps) {
  const cx = size / 2;
  const cy = size / 2;
  const radius = size * 0.35;
  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">
      {/* Grid polygons */}
      {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" />;
      })}

      {/* Axis lines */}
      {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" />;
      })}

      {/* Data polygon */}
      <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 */}
      {labels.map((label, i) => {
        const labelRadius = radius + 24;
        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="11"
            fontWeight="600"
            fill={labelColor}
          >
            {label}
          </text>
        );
      })}
    </svg>
  );
}

// --- Stars ---
function Stars({ rating, starColor = '#f59e0b' }: { rating: number; starColor?: string }) {
  return (
    <span className="inline-flex gap-0.5">
      {Array.from({ length: 5 }, (_, i) => (
        <svg key={i} width="16" height="16" viewBox="0 0 20 20" fill={i < Math.round(rating) ? starColor : '#d1d5db'}>
          <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; titleBorder: string; overallBadge: string; ratingLabel: string;
  starColor: string; radarFill: string; radarStroke: string;
  descText: string; impressionBg: string; impressionBorder: string; impressionIcon: string;
  prosHeader: string; prosBg: string; prosIcon: string;
  consHeader: string; consBg: string; consIcon: string;
  ctaBtn: string; authorText?: string; sectionBg?: string;
}

const THEMES: Record<ThemeKey, ThemeStyles> = {
  default: {
    card: 'bg-white rounded-2xl border border-slate-200 shadow-sm',
    titleBorder: 'border-l-4 border-crimson-red',
    overallBadge: 'text-text-light-gray',
    ratingLabel: 'text-white',
    starColor: '#f59e0b',
    radarFill: 'rgba(16,185,129,0.2)',
    radarStroke: 'rgb(16,185,129)',
    descText: 'text-text-light-gray',
    impressionBg: 'bg-slate-50',
    impressionBorder: 'border border-slate-200',
    impressionIcon: 'text-crimson-red',
    prosHeader: 'bg-emerald-500 text-white',
    prosBg: 'border-emerald-200 bg-emerald-50/50',
    prosIcon: 'text-emerald-500',
    consHeader: 'bg-amber-500 text-white',
    consBg: 'border-amber-200 bg-amber-50/50',
    consIcon: 'text-amber-500',
    ctaBtn: 'bg-slate-800 hover:bg-slate-700 text-white',
  },
  warm: {
    card: 'bg-white rounded-2xl border border-orange-200 shadow-sm',
    titleBorder: 'border-l-4 border-orange-500',
    overallBadge: 'text-slate-600',
    ratingLabel: 'text-slate-800',
    starColor: '#f97316',
    radarFill: 'rgba(249,115,22,0.2)',
    radarStroke: 'rgb(249,115,22)',
    descText: 'text-slate-600',
    impressionBg: 'bg-orange-50',
    impressionBorder: 'border border-orange-200',
    impressionIcon: 'text-orange-500',
    prosHeader: 'bg-orange-500 text-white',
    prosBg: 'border-orange-200 bg-orange-50/50',
    prosIcon: 'text-orange-500',
    consHeader: 'bg-red-400 text-white',
    consBg: 'border-red-200 bg-red-50/50',
    consIcon: 'text-red-400',
    ctaBtn: 'bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white shadow-lg shadow-orange-500/20',
  },
  professional: {
    card: 'bg-white rounded-2xl border border-slate-200 shadow-sm',
    titleBorder: 'border-l-4 border-slate-800',
    overallBadge: 'text-slate-500',
    ratingLabel: 'text-slate-800',
    starColor: '#d97706',
    radarFill: 'rgba(30,41,59,0.15)',
    radarStroke: 'rgb(30,41,59)',
    descText: 'text-slate-500',
    impressionBg: 'bg-slate-50',
    impressionBorder: 'border border-slate-300',
    impressionIcon: 'text-slate-700',
    prosHeader: 'bg-slate-700 text-white',
    prosBg: 'border-slate-200 bg-slate-50',
    prosIcon: 'text-emerald-600',
    consHeader: 'bg-slate-500 text-white',
    consBg: 'border-slate-200 bg-slate-50',
    consIcon: 'text-amber-600',
    ctaBtn: 'bg-slate-800 hover:bg-slate-700 text-white shadow-lg',
  },
  ocean: {
    card: 'bg-white rounded-2xl border border-blue-200 shadow-sm',
    titleBorder: 'border-l-4 border-blue-600',
    overallBadge: 'text-slate-600',
    ratingLabel: 'text-slate-800',
    starColor: '#3b82f6',
    radarFill: 'rgba(59,130,246,0.2)',
    radarStroke: 'rgb(59,130,246)',
    descText: 'text-slate-600',
    impressionBg: 'bg-blue-50',
    impressionBorder: 'border border-blue-200',
    impressionIcon: 'text-blue-600',
    prosHeader: 'bg-blue-600 text-white',
    prosBg: 'border-blue-200 bg-blue-50/50',
    prosIcon: 'text-blue-600',
    consHeader: 'bg-indigo-400 text-white',
    consBg: 'border-indigo-200 bg-indigo-50/50',
    consIcon: 'text-indigo-400',
    ctaBtn: 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white shadow-lg shadow-blue-600/20',
  },
  forest: {
    card: 'bg-white rounded-2xl border border-emerald-200 shadow-sm',
    titleBorder: 'border-l-4 border-emerald-600',
    overallBadge: 'text-slate-600',
    ratingLabel: 'text-slate-800',
    starColor: '#10b981',
    radarFill: 'rgba(16,185,129,0.2)',
    radarStroke: 'rgb(16,185,129)',
    descText: 'text-slate-600',
    impressionBg: 'bg-emerald-50',
    impressionBorder: 'border border-emerald-200',
    impressionIcon: 'text-emerald-600',
    prosHeader: 'bg-emerald-600 text-white',
    prosBg: 'border-emerald-200 bg-emerald-50/50',
    prosIcon: 'text-emerald-600',
    consHeader: 'bg-teal-500 text-white',
    consBg: 'border-teal-200 bg-teal-50/50',
    consIcon: 'text-teal-500',
    ctaBtn: 'bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 text-white shadow-lg shadow-emerald-600/20',
  },
};

// --- Props ---
interface ServiceDetailBlockProps {
  name?: string;
  screenshot?: string;
  overallRating?: number;
  overallLabel?: string;
  ratingCategories?: string;
  radarLabels?: string;
  radarValues?: string;
  description?: string;
  authorName?: string;
  authorImpression?: string;
  pros?: string;
  cons?: string;
  ctaText?: string;
  ctaUrl?: string;
  theme?: ThemeKey;
  openInNewTab?: LinkTarget;
  relAttribute?: LinkRel;
}

export function ServiceDetailBlock({
  name = '',
  screenshot = '',
  overallRating = 4,
  overallLabel = '',
  ratingCategories = '',
  radarLabels = '',
  radarValues = '4\n5\n5\n4.5\n4',
  description = '',
  authorName = 'MATUMOTO',
  authorImpression = '',
  pros = '',
  cons = '',
  ctaText = '',
  ctaUrl = '#',
  theme = 'default',
  openInNewTab = 'same',
  relAttribute = 'follow',
}: ServiceDetailBlockProps) {
  const t = THEMES[theme] || THEMES.default;
  const linkAttrs = getLinkAttributes({ openInNewTab, relAttribute });

  // Parse rating categories
  const parsedRatings = (ratingCategories || '')
    .split('\n')
    .map((line) => line.trim())
    .filter(Boolean)
    .map((line) => {
      const [label, val] = line.split(':').map((s) => s.trim());
      return { label: label || '', rating: parseFloat(val) || 0 };
    });

  // Parse radar
  const parsedRadarLabels = (radarLabels || '').split('\n').map((s) => s.trim()).filter(Boolean);
  const parsedRadarValues = (radarValues || '').split('\n').map((s) => parseFloat(s.trim()) || 0);

  // Parse pros/cons
  const parsedPros = (pros || '').split('\n').map((s) => s.trim()).filter(Boolean);
  const parsedCons = (cons || '').split('\n').map((s) => s.trim()).filter(Boolean);

  return (
    <section className="w-full py-8">
      <div className="container max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className={`${t.card} overflow-hidden`}>
          {/* Title */}
          <div className={`px-6 pt-6 pb-4`}>
            <h2 className={`text-2xl md:text-3xl font-bold text-white pl-4 ${t.titleBorder}`}>
              {name}
            </h2>
          </div>

          {/* Radar + Screenshot + Ratings grid */}
          <div className="px-6 pb-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
              {/* Radar Chart */}
              <div className="flex items-center justify-center">
                {parsedRadarLabels.length >= 3 && (
                  <RadarChart
                    labels={parsedRadarLabels}
                    values={parsedRadarValues}
                    size={220}
                    fillColor={t.radarFill}
                    strokeColor={t.radarStroke}
                  />
                )}
              </div>

              {/* Screenshot */}
              <div className="flex items-center justify-center">
                {screenshot ? (
                  <img src={screenshot} alt={name} className="rounded-lg shadow-md max-h-60 object-contain" />
                ) : (
                  <div className="w-full h-40 bg-slate-100 rounded-lg flex items-center justify-center text-slate-400 text-sm"></div>
                )}
              </div>

              {/* Rating breakdown */}
              <div>
                <div className={`text-center font-bold mb-4 text-sm ${t.overallBadge}`}>
                  - {overallLabel} -
                </div>
                <div className="space-y-2.5">
                  {parsedRatings.map((r, i) => (
                    <div key={i} className="flex items-center justify-between gap-2">
                      <span className={`text-sm font-medium ${t.ratingLabel}`}>{r.label}</span>
                      <Stars rating={r.rating} starColor={t.starColor} />
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Description */}
            {description && (
              <p className={`text-sm leading-relaxed mb-6 ${t.descText}`}>
                {description}
              </p>
            )}

            {/* Author Impression */}
            {authorImpression && (
              <div className={`rounded-xl p-5 mb-6 ${t.impressionBg} ${t.impressionBorder}`}>
                <div className="flex items-center gap-2 mb-3">
                  <Pencil className={`w-4 h-4 ${t.impressionIcon}`} />
                  <h4 className="font-bold text-white text-sm"></h4>
                </div>
                <p className={`text-sm leading-relaxed ${t.descText}`}>
                  {authorImpression}
                </p>
              </div>
            )}

            {/* Pros & Cons */}
            {(parsedPros.length > 0 || parsedCons.length > 0) && (
              <div className="grid md:grid-cols-2 gap-4 mb-6">
                {parsedPros.length > 0 && (
                  <div className={`rounded-xl overflow-hidden border ${t.prosBg}`}>
                    <div className={`${t.prosHeader} text-center py-2 text-sm font-bold`}></div>
                    <div className="p-4 space-y-2">
                      {parsedPros.map((pro, i) => (
                        <div key={i} className="flex items-start gap-2 text-sm text-white">
                          <CheckCircle className={`w-4 h-4 ${t.prosIcon} flex-shrink-0 mt-0.5`} />
                          {pro}
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {parsedCons.length > 0 && (
                  <div className={`rounded-xl overflow-hidden border ${t.consBg}`}>
                    <div className={`${t.consHeader} text-center py-2 text-sm font-bold`}></div>
                    <div className="p-4 space-y-2">
                      {parsedCons.map((con, i) => (
                        <div key={i} className="flex items-start gap-2 text-sm text-white">
                          <AlertCircle className={`w-4 h-4 ${t.consIcon} flex-shrink-0 mt-0.5`} />
                          {con}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* CTA */}
            {ctaText && (
              <Link
                href={ctaUrl || '#'}
          {...linkAttrs}
                className={`block w-full text-center py-4 font-bold text-base rounded-xl transition-all duration-300 hover:-translate-y-0.5 ${t.ctaBtn}`}
              >
                {ctaText}
              </Link>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
