/**
 * WorkspaceHeader — ReportHeader 와 동일한 비주얼 톤(파스텔 그라데이션 + 보라색
 * 세리프 eyebrow + 네이비 굵은 세리프 타이틀 + white/60 backdrop-blur 메타 칩)
 * 으로 클리닉 컨텍스트의 시각적 일관성을 유지합니다.
 */
import { Link } from 'react-router';
import { motion } from 'motion/react';
import {
  Calendar,
  MapPin,
  Plus,
  TrendingUp,
  TrendingDown,
  Minus,
} from 'lucide-react';
import type { WorkspaceClinicProfile, WorkspaceRun } from '../types/workspace';
import { PageContainer } from '@/shared/ui/page-container';
import { ChannelLinkButtons, type ChannelHandles } from '@/shared/ui/channel-link-buttons';
import { ScoreRing } from '@/features/report/components/ui/ScoreRing';

interface WorkspaceHeaderProps {
  clinic: WorkspaceClinicProfile;
  latestRun?: WorkspaceRun;
  previousRun?: WorkspaceRun;
}

function trend(latest?: number | null, prev?: number | null) {
  if (latest == null || prev == null) return { dir: 'flat' as const, diff: 0 };
  const diff = Math.round(latest - prev);
  if (diff > 0) return { dir: 'up' as const, diff };
  if (diff < 0) return { dir: 'down' as const, diff };
  return { dir: 'flat' as const, diff: 0 };
}

function formatDate(iso?: string | null) {
  if (!iso) return '—';
  try {
    return new Date(iso).toLocaleDateString('ko-KR', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  } catch {
    return iso;
  }
}

export function WorkspaceHeader({
  clinic,
  latestRun,
  previousRun,
}: WorkspaceHeaderProps) {
  const score = latestRun?.overallScore ?? null;
  const t = trend(latestRun?.overallScore, previousRun?.overallScore);
  const TrendIcon = t.dir === 'up' ? TrendingUp : t.dir === 'down' ? TrendingDown : Minus;
  const trendColor =
    t.dir === 'up'
      ? 'text-emerald-600'
      : t.dir === 'down'
        ? 'text-rose-500'
        : 'text-slate-400';
  const trendValue = t.dir === 'flat' ? null : `${t.diff > 0 ? '+' : ''}${t.diff}`;

  const socialHandles: ChannelHandles = clinic.defaultTargets.reduce<ChannelHandles>(
    (acc, target) => ({ ...acc, [target.platform]: target.handle }),
    {},
  );

  return (
    <section className="relative overflow-hidden bg-[radial-gradient(ellipse_at_top_left,#e0e7ff,transparent_50%),radial-gradient(ellipse_at_bottom_right,#fce7f3,transparent_50%),radial-gradient(ellipse_at_center,#f5f3ff,transparent_60%)] py-20 px-6">
      {/* Animated blobs — ReportHeader 와 동일 패턴 */}
      <motion.div
        className="absolute top-10 left-10 w-72 h-72 rounded-full bg-indigo-200/30 blur-3xl"
        animate={{ x: [0, 30, 0], y: [0, -20, 0] }}
        transition={{ duration: 8, repeat: Infinity, ease: 'easeInOut' }}
        aria-hidden
      />
      <motion.div
        className="absolute bottom-10 right-10 w-96 h-96 rounded-full bg-pink-200/30 blur-3xl"
        animate={{ x: [0, -20, 0], y: [0, 30, 0] }}
        transition={{ duration: 10, repeat: Infinity, ease: 'easeInOut' }}
        aria-hidden
      />
      <motion.div
        className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-80 h-80 rounded-full bg-purple-200/20 blur-3xl"
        animate={{ scale: [1, 1.1, 1] }}
        transition={{ duration: 6, repeat: Infinity, ease: 'easeInOut' }}
        aria-hidden
      />

      <PageContainer className="relative px-0">
        <div className="flex flex-col md:flex-row items-center md:items-start justify-between gap-10">
          {/* Left: identity */}
          <motion.div
            className="flex-1 text-center md:text-left min-w-0"
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.5 }}
          >
            <motion.p
              className="font-serif text-3xl md:text-4xl font-normal text-[#6C5CE7] mb-4 tracking-wide"
              initial={{ opacity: 0, y: 10 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.5, delay: 0.1 }}
            >
              Clinic Workspace
            </motion.p>

            {clinic.logoUrl ? (
              <motion.div
                className="mb-4"
                initial={{ opacity: 0, scale: 0.9 }}
                whileInView={{ opacity: 1, scale: 1 }}
                viewport={{ once: true }}
                transition={{ duration: 0.5, delay: 0.15 }}
              >
                <img
                  src={clinic.logoUrl}
                  alt={clinic.name}
                  className="h-16 md:h-20 w-auto object-contain md:mx-0 mx-auto"
                  onError={(e) => {
                    (e.target as HTMLImageElement).style.display = 'none';
                  }}
                />
              </motion.div>
            ) : null}

            <motion.h1
              className="font-serif text-4xl md:text-5xl font-bold text-[#0A1128] mb-3"
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.5, delay: 0.2 }}
            >
              {clinic.name}
            </motion.h1>

            {clinic.nameEn && (
              <motion.p
                className="text-lg text-slate-600 mb-8"
                initial={{ opacity: 0, y: 20 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{ duration: 0.5, delay: 0.3 }}
              >
                {clinic.nameEn}
              </motion.p>
            )}

            {/* Meta chips — ReportHeader 와 동일 스타일 */}
            <motion.div
              className="flex flex-wrap gap-3 justify-center md:justify-start mb-6"
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.5, delay: 0.4 }}
            >
              <span className="inline-flex items-center gap-2 rounded-full bg-white/60 backdrop-blur-sm border border-white/40 px-3 py-1 text-sm font-medium text-slate-700">
                <Calendar size={14} className="text-slate-400" />
                마지막 분석 {formatDate(latestRun?.completedAt ?? latestRun?.startedAt)}
              </span>
              {clinic.location && (
                <span className="inline-flex items-center gap-2 rounded-full bg-white/60 backdrop-blur-sm border border-white/40 px-3 py-1 text-sm font-medium text-slate-700">
                  <MapPin size={14} className="text-slate-400" />
                  {clinic.location}
                </span>
              )}
            </motion.div>

            {/* 등록된 채널 바로가기 — ReportHeader 와 동일 패턴 */}
            {clinic.defaultTargets.length > 0 && (
              <motion.div
                className="mb-6"
                initial={{ opacity: 0, y: 20 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{ duration: 0.5, delay: 0.5 }}
              >
                <ChannelLinkButtons
                  handles={socialHandles}
                  variant="light"
                  className="justify-center md:justify-start"
                />
              </motion.div>
            )}

            {/* Actions */}
            <motion.div
              className="flex flex-wrap gap-2 justify-center md:justify-start"
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.5, delay: 0.6 }}
            >
              <Link
                to="/report/loading"
                className="inline-flex items-center gap-1.5 px-5 py-2.5 rounded-full text-xs font-semibold text-white bg-gradient-to-r from-[#4F1DA1] to-[#021341] shadow-sm hover:opacity-90 transition-all"
              >
                <Plus size={14} />새 분석 시작
              </Link>
            </motion.div>
          </motion.div>

          {/* Right: stats card — ReportHeader 의 Score card 와 동일 구조 */}
          <motion.div
            className="shrink-0"
            initial={{ opacity: 0, scale: 0.8 }}
            whileInView={{ opacity: 1, scale: 1 }}
            viewport={{ once: true }}
            transition={{ duration: 0.6, delay: 0.3 }}
          >
            <div className="bg-white/60 backdrop-blur-sm border border-white/40 rounded-3xl p-8 shadow-lg">
              <p className="text-xs text-slate-500 uppercase tracking-wide text-center mb-4">
                Overall Score
              </p>
              <ScoreRing score={score != null ? Math.round(score) : 0} size={160} label="종합 점수" />
              <div className={`flex items-center justify-center gap-1 text-xs font-medium ${trendColor} mt-3`}>
                <span className="text-slate-500">이전 대비</span>
                <TrendIcon size={13} />
                {trendValue ?? <span>변동 없음</span>}
              </div>
            </div>
          </motion.div>
        </div>
      </PageContainer>
    </section>
  );
}
