/**
 * AuthorProfile — Server component
 *
 * Always fetches the latest blog author from the DB dynamically.
 * The `theme` prop (from the Puck editor) controls visual style only.
 * All author data (name, bio, avatar, socials) comes from the DB,
 * never from static Puck-saved props.
 */
import React from 'react';
import { User, ExternalLink, Twitter, Instagram, Youtube, Globe, Linkedin } from 'lucide-react';
import Image from 'next/image';
import { getLatestAuthorData } from '@/lib/utils/db';

interface AuthorProfileProps {
  /** Visual theme — only styling, not data */
  theme?: string;
  authorProfileUrl?: string;
  /** All other Puck props are intentionally ignored; data comes from DB */
  [key: string]: unknown;
}

export async function AuthorProfile({ theme = 'default', authorProfileUrl }: AuthorProfileProps) {
  // Always fetch from DB — never use Puck-saved static data
  const author = await getLatestAuthorData();

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

  // Use manual URL from prop if provided, otherwise DB, otherwise default relative URL
  const finalProfileUrl = authorProfileUrl || author.authorProfileUrl || (author.authorName ? `/author/${encodeURIComponent(author.authorName)}` : '');

  const themeClasses: Record<
    string,
    {
      bg: string;
      card: string;
      text: string;
      sub: string;
      avatarBg: string;
      border: string;
      socialHover: string;
    }
  > = {
    default: {
      bg: '',
      card: 'bg-white dark:bg-card',
      text: 'text-zen-dark dark:text-white',
      sub: 'text-zen-slate dark:text-gray-400',
      avatarBg: 'bg-zen-frost dark:bg-muted',
      border: 'border-zen-warm dark:border-border',
      socialHover: 'hover:text-primary hover:bg-zen-frost dark:hover:bg-muted',
    },
    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: author.socialTwitter,   icon: Twitter,   label: 'Twitter'   },
    { url: author.socialInstagram, icon: Instagram, label: 'Instagram' },
    { url: author.socialYoutube,   icon: Youtube,   label: 'YouTube'   },
    { url: author.socialLinkedin,  icon: Linkedin,  label: 'LinkedIn'  },
    { url: author.socialWebsite,   icon: Globe,     label: 'Website'   },
  ].filter((s) => s.url);

  return (
    <section className={`w-full py-10 ${t.bg}`}>
      <div className="container max-w-5xl 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`}
            >
              {author.authorAvatar ? (
                <Image
                  src={author.authorAvatar}
                  alt={author.authorName}
                  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}`}>{author.authorName}</h3>

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

              {author.authorBio && (
                <p className={`text-sm leading-relaxed ${t.sub}`}>{author.authorBio}</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>
  );
}
