/**
 * AuthorProfile — Server component
 *
 * Fetches the latest blog author from the DB dynamically,
 * but allows overriding values via Puck editor props.
 */
import React from 'react';
import { User, ExternalLink, AtSign, Camera, Play, Globe, Briefcase } from 'lucide-react';
import Image from 'next/image';
import { getLatestAuthorData } from '@/lib/utils/db';

interface AuthorProfileProps {
  /** Visual theme — only styling, not data */
  theme?: string;
  authorName?: string;
  authorBio?: string;
  authorAvatar?: string;
  authorRole?: string;
  authorProfileUrl?: string;
  socialTwitter?: string;
  socialInstagram?: string;
  socialYoutube?: string;
  socialLinkedin?: string;
  socialWebsite?: string;
  [key: string]: unknown;
}

export async function AuthorProfile({
  theme = 'default',
  authorName,
  authorBio,
  authorAvatar,
  authorRole,
  authorProfileUrl,
  socialTwitter,
  socialInstagram,
  socialYoutube,
  socialLinkedin,
  socialWebsite,
}: AuthorProfileProps) {
  // Always fetch from DB as a fallback
  const dbAuthor = await getLatestAuthorData();

  // Prefer manually entered props over DB data if provided
  const finalName = authorName || dbAuthor?.authorName;
  const finalBio = authorBio || dbAuthor?.authorBio;
  const finalAvatar = authorAvatar || dbAuthor?.authorAvatar;
  const finalRole = authorRole || dbAuthor?.authorRole;

  // Nothing to show if no author info exists yet
  if (!finalName) return null;

  // Always use the relative URL to ensure navigation stays on the current website's author page.
  // Ignore DB's authorProfileUrl as it might contain an absolute URL to a different shared site.
  // Prefer the prop if explicitly given.
  const finalProfileUrl = authorProfileUrl || `/author/${encodeURIComponent(finalName)}`;

  const themeClasses: Record<
    string,
    {
      bg: string;
      card: string;
      text: string;
      sub: string;
      avatarBg: string;
      border: string;
      socialHover: string;
    }
  > = {
    default: {
      bg: '',
      card: 'bg-dark-gray',
      text: 'text-white',
      sub: 'text-light-gray',
      avatarBg: 'bg-soft-dark',
      border: 'border-soft-gray-border',
      socialHover: 'hover:text-primary hover:bg-soft-dark',
    },
    warm: {
      bg: '',
      card: 'bg-orange-50',
      text: 'text-slate-800',
      sub: 'text-slate-500',
      avatarBg: 'bg-orange-100',
      border: 'border-orange-200',
      socialHover: 'hover:text-orange-600 hover:bg-orange-100',
    },
    professional: {
      bg: 'bg-slate-900',
      card: 'bg-slate-800',
      text: 'text-white',
      sub: 'text-slate-300',
      avatarBg: 'bg-slate-700',
      border: 'border-slate-600',
      socialHover: 'hover:text-blue-400 hover:bg-slate-700',
    },
    ocean: {
      bg: '',
      card: 'bg-blue-50',
      text: 'text-slate-800',
      sub: 'text-slate-500',
      avatarBg: 'bg-blue-100',
      border: 'border-blue-200',
      socialHover: 'hover:text-blue-600 hover:bg-blue-100',
    },
    forest: {
      bg: '',
      card: 'bg-emerald-50',
      text: 'text-slate-800',
      sub: 'text-slate-500',
      avatarBg: 'bg-emerald-100',
      border: 'border-emerald-200',
      socialHover: 'hover:text-emerald-600 hover:bg-emerald-100',
    },
  };
  const t = themeClasses[theme] ?? themeClasses.default;

  const socials = [
    { url: socialTwitter || dbAuthor?.socialTwitter, icon: AtSign, label: 'AtSign' },
    { url: socialInstagram || dbAuthor?.socialInstagram, icon: Camera, label: 'Camera' },
    { url: socialYoutube || dbAuthor?.socialYoutube, icon: Play, label: 'YouTube' },
    { url: socialLinkedin || dbAuthor?.socialLinkedin, icon: Briefcase, label: 'LinkedIn' },
    { url: socialWebsite || dbAuthor?.socialWebsite, icon: Globe, label: 'Website' },
  ].filter((s) => s.url);

  return (
    <section className={`w-full py-10 ${t.bg}`}>
      <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className={`${t.card} border ${t.border} rounded-2xl p-8 shadow-sm`}>
          <div className="flex flex-col sm:flex-row items-center sm:items-start gap-6">

            {/* Avatar */}
            <div
              className={`w-24 h-24 rounded-full ${t.avatarBg} flex items-center justify-center overflow-hidden shrink-0`}
            >
              {finalAvatar ? (
                <Image
                  src={finalAvatar}
                  alt={finalName}
                  width={96}
                  height={96}
                  className="w-full h-full object-cover"
                />
              ) : (
                <User
                  className={`w-10 h-10 ${theme === 'professional' ? 'text-slate-400' : 'text-primary'
                    }`}
                />
              )}
            </div>

            {/* Info */}
            <div className="flex-1 text-center sm:text-left">
              <h3 className={`text-xl font-bold mb-1 ${t.text}`}>{finalName}</h3>

              {finalRole && (
                <span
                  className={`text-xs font-medium uppercase tracking-wider ${t.sub} block mb-3`}
                >
                  {finalRole}
                </span>
              )}

              {finalBio && (
                <p className={`text-sm leading-relaxed ${t.sub}`}>{finalBio}</p>
              )}

              {/* Social Links */}
              {socials.length > 0 && (
                <div className="flex items-center justify-center sm:justify-start gap-2 mt-4">
                  {socials.map(({ url, icon: Icon, label }) => (
                    <a
                      key={label}
                      href={url}
                      target="_blank"
                      rel="noopener noreferrer"
                      title={label}
                      className={`w-9 h-9 rounded-full flex items-center justify-center ${t.sub} ${t.socialHover} transition-all duration-200`}
                    >
                      <Icon className="w-4 h-4" />
                    </a>
                  ))}
                </div>
              )}

              {/* Link to author's article list */}
              {finalProfileUrl && (
                <a
                  href={finalProfileUrl}
                  className={`inline-flex items-center gap-1.5 text-sm font-medium mt-4 ${theme === 'professional'
                      ? 'text-blue-400 hover:text-blue-300'
                      : 'text-primary hover:underline'
                    } transition-colors`}
                >
                  記事一覧を見る <ExternalLink className="w-3.5 h-3.5" />
                </a>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
