import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { characters, conversations, stars, channels, images, userbot, system } from '../api/client';
import { motion, AnimatePresence } from 'framer-motion';

/* ── Types ── */
interface CharacterDNA {
  id: string; status: 'active' | 'inactive' | 'creating';
  identity: { name: string; age: number; nationality: string; city: string; occupation: string; personality_tags: string[]; mbti: string; backstory: string };
  physicalMeasurements: { height_cm: number; weight_kg: number; body_type: string; measurements: { bust: number; waist: number; hips: number } };
  skinMap: { base: string; shadow: string; highlight: string };
  faceAnatomy: { eye_shape: string; eye_color: string; eyebrow_shape: string; nose_type: string; lip_shape: string; cheekbones: string; jawline: string; distinctive_marks: string[] };
  hairDNA: { style: string; length: string; texture: string; root_color: string; mid_color: string; highlight_color: string };
  bodyBiometrics: { body_type_detail: string; posture: string; skin_texture: string };
  profileView: { best_angle: string; signature_pose: string };
  expressionMotion: { default_expression: string; smile_type: string; gaze_style: string };
  makeupStyle: { philosophy: string; skin_finish: string; colors: { primary: string; secondary: string; accent: string } };
  fashionStyle: { aesthetic: string; main_colors: string[]; signature_pieces: string[] };
  technicalSettings: { camera_body: string; portrait_lens: string; full_body_lens: string; film_stock: string };
}
interface Conversation { telegramUserId: number; userName?: string; totalMessages: number; lastActivity: string }
interface StarsStats { totalEarned?: number; totalTransactions?: number; conversionRate?: number }
interface StarsTransaction { id: string; type: string; starCount: number; createdAt: string; status: string }
interface ChannelInfo { normal?: { id?: string; title?: string; memberCount?: number }; vip?: { id?: string; title?: string; memberCount?: number } }
interface GeneratedImage { id: string; url?: string; resultUrl?: string; createdAt?: string; qualityScore?: number }
type Tab = 'dna' | 'conversations' | 'stars' | 'channel' | 'images' | 'userbot';

const tabLabels: Record<Tab, string> = { dna: '🧬 DNA', conversations: '💬 Konuşmalar', stars: '⭐ Stars', channel: '📢 Kanal', images: '🖼️ Görseller', userbot: '📱 Userbot' };
const REFERENCE_IMAGE_MAP: { filename: string; label: string }[] = [
  { filename: 'master.jpg', label: 'Master Portre' }, { filename: 'right-45.jpg', label: 'Sağ 45°' },
  { filename: 'left-45.jpg', label: 'Sol 45°' }, { filename: 'full-profile.jpg', label: 'Tam Profil' },
  { filename: 'bird-eye.jpg', label: 'Kuş Bakışı' }, { filename: 'full-body.jpg', label: 'Tam Boy' },
  { filename: 'back-view.jpg', label: 'Arka Görünüm' },
];
const statusColors: Record<string, string> = { active: 'bg-emerald-500', inactive: 'bg-slate-400', creating: 'bg-amber-500' };
const statusLabels: Record<string, string> = { active: 'Aktif', inactive: 'Pasif', creating: 'Oluşturuluyor' };
const dnaSections: { key: keyof CharacterDNA; label: string }[] = [
  { key: 'identity', label: 'Temel Kimlik' }, { key: 'physicalMeasurements', label: 'Fiziksel Ölçüler' },
  { key: 'skinMap', label: 'Cilt Haritası' }, { key: 'faceAnatomy', label: 'Yüz Anatomisi' },
  { key: 'hairDNA', label: 'Saç DNA' }, { key: 'bodyBiometrics', label: 'Vücut Biyometrisi' },
  { key: 'profileView', label: 'Profil Görünümü' }, { key: 'expressionMotion', label: 'İfade & Hareket' },
  { key: 'makeupStyle', label: 'Makyaj Stili' }, { key: 'fashionStyle', label: 'Moda Stili' },
  { key: 'technicalSettings', label: 'Teknik Ayarlar' },
];

function ColorSwatch({ color }: { color: string }) {
  if (!color || !color.startsWith('#')) return <span>{color}</span>;
  return <span className="inline-flex items-center gap-1.5"><span className="inline-block w-4 h-4 rounded-sm border border-slate-500" style={{ background: color }} />{color}</span>;
}
function isHex(v: unknown): v is string { return typeof v === 'string' && /^#[0-9a-fA-F]{6}$/.test(v); }
function renderValue(value: unknown): React.ReactNode {
  if (value == null) return '—';
  if (isHex(value)) return <ColorSwatch color={value} />;
  if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '—';
  if (typeof value === 'object') {
    return (<div className="pl-3 border-l-2 border-slate-600">{Object.entries(value).map(([k, v]) => (
      <div key={k} className="flex gap-2 py-0.5 text-sm"><span className="text-slate-500 min-w-[100px]">{k}:</span><span>{renderValue(v)}</span></div>
    ))}</div>);
  }
  return String(value);
}

const glassCard = 'rounded-2xl border border-white/[0.06] bg-white/[0.03] backdrop-blur-xl';

const CharacterDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [character, setCharacter] = useState<CharacterDNA | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<Tab>('dna');
  const [convos, setConvos] = useState<Conversation[]>([]);
  const [convosLoading, setConvosLoading] = useState(false);
  const [starsStats, setStarsStats] = useState<StarsStats | null>(null);
  const [transactions, setTransactions] = useState<StarsTransaction[]>([]);
  const [starsLoading, setStarsLoading] = useState(false);
  const [channelInfo, setChannelInfo] = useState<ChannelInfo | null>(null);
  const [channelLoading, setChannelLoading] = useState(false);
  const [imageList, setImageList] = useState<GeneratedImage[]>([]);
  const [imagesLoading, setImagesLoading] = useState(false);
  const [selectedAspectRatio, setSelectedAspectRatio] = useState('9:16');
  const [customPrompt, setCustomPrompt] = useState('');
  const [generating, setGenerating] = useState(false);
  const [genMessage, setGenMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [editingSection, setEditingSection] = useState<string | null>(null);
  const [editBuffer, setEditBuffer] = useState<string>('');
  const [saving, setSaving] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);
  const [refImages, setRefImages] = useState<string[]>([]);
  const [refImagesLoading, setRefImagesLoading] = useState(false);
  const [refGenerating, setRefGenerating] = useState(false);
  const [refGenMessage, setRefGenMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [, setUserbotStatus] = useState<{ connected: boolean; phoneNumber?: string } | null>(null);
  const [userbotLoading, setUserbotLoading] = useState(false);
  const [userbotPhone, setUserbotPhone] = useState('');
  const [userbotCode, setUserbotCode] = useState('');
  const [userbotPassword, setUserbotPassword] = useState('');
  const [userbotStep, setUserbotStep] = useState<'idle' | 'code_sent' | 'needs_password' | 'connected'>('idle');
  const [userbotSaving, setUserbotSaving] = useState(false);
  const [userbotMsg, setUserbotMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [apiConfigOk, setApiConfigOk] = useState<boolean | null>(null);
  const [apiConfigLoading, setApiConfigLoading] = useState(false);
  const [headerImgError, setHeaderImgError] = useState(false);
  const [headerImgLoaded, setHeaderImgLoaded] = useState(false);

  const fetchCharacter = useCallback(async () => {
    if (!id) return;
    try { setLoading(true); setError(null); const res = await characters.get(id); setCharacter(res.data?.data ?? res.data?.character ?? res.data); }
    catch { setError('Karakter yüklenirken hata oluştu.'); } finally { setLoading(false); }
  }, [id]);

  const loadRefImages = useCallback(async () => {
    if (!id) return; setRefImagesLoading(true);
    try { const res = await characters.getReferenceImages(id); const imgs = res.data?.data?.images ?? res.data?.images ?? []; setRefImages(Array.isArray(imgs) ? imgs : []); } catch {}
    setRefImagesLoading(false);
  }, [id]);

  useEffect(() => { fetchCharacter(); loadRefImages(); }, [fetchCharacter, loadRefImages]);

  const loadConversations = useCallback(async () => { if (!id) return; setConvosLoading(true); try { const res = await conversations.list(id); const cData = res.data?.data ?? res.data?.conversations ?? []; setConvos(Array.isArray(cData) ? cData : []); } catch {} setConvosLoading(false); }, [id]);
  const loadStars = useCallback(async () => { if (!id) return; setStarsLoading(true); try { const [s, t] = await Promise.all([stars.getStats(id), stars.getTransactions(id)]); setStarsStats(s.data?.data?.stats ?? s.data?.stats ?? s.data?.data ?? null); const tData = t.data?.data?.transactions ?? t.data?.data ?? t.data?.transactions ?? []; setTransactions(Array.isArray(tData) ? tData : []); } catch {} setStarsLoading(false); }, [id]);
  const loadChannel = useCallback(async () => { if (!id) return; setChannelLoading(true); try { const res = await channels.get(id); setChannelInfo(res.data?.data ?? res.data?.channels ?? null); } catch {} setChannelLoading(false); }, [id]);
  const loadImages = useCallback(async () => { if (!id) return; setImagesLoading(true); try { const res = await images.list(id); const raw = res.data; const iData = Array.isArray(raw) ? raw : (raw?.data ?? raw?.images ?? []); setImageList(Array.isArray(iData) ? iData : []); } catch {} setImagesLoading(false); }, [id]);
  const loadUserbotStatus = useCallback(async () => {
    if (!id) return; setUserbotLoading(true);
    try { const res = await userbot.getStatus(id); const data = res.data?.data ?? res.data; setUserbotStatus(data); if (data?.connected) setUserbotStep('connected');
      const sessRes = await userbot.getSessions(); const sessions = sessRes.data?.data ?? sessRes.data ?? []; const sess = Array.isArray(sessions) ? sessions.find((s: any) => s.characterId === id) : null;
      if (sess) { setUserbotPhone(sess.phoneNumber || ''); if (sess.active && data?.connected) setUserbotStep('connected'); }
    } catch {} setUserbotLoading(false);
  }, [id]);

  const checkApiConfig = useCallback(async () => {
    setApiConfigLoading(true);
    try {
      const res = await system.getApiConfig();
      const data = res.data?.data ?? res.data;
      const telegramApiId = data?.telegramApiId ?? '';
      const telegramApiHash = data?.telegramApiHash ?? '';
      setApiConfigOk(telegramApiId !== '' && telegramApiHash !== '');
    } catch {
      setApiConfigOk(false);
    }
    setApiConfigLoading(false);
  }, []);

  const handleGenerateImage = async () => { if (!id || !customPrompt.trim()) return; setGenerating(true); setGenMessage(null); try { await images.generate(id, { prompt: customPrompt.trim(), aspectRatio: selectedAspectRatio }); setGenMessage({ type: 'success', text: 'Görsel üretildi!' }); setCustomPrompt(''); await loadImages(); } catch (err: any) { setGenMessage({ type: 'error', text: err?.response?.data?.error || 'Görsel üretilirken hata oluştu.' }); } setGenerating(false); };

  useEffect(() => {
    if (activeTab === 'conversations') loadConversations();
    else if (activeTab === 'stars') loadStars();
    else if (activeTab === 'channel') loadChannel();
    else if (activeTab === 'images') { loadImages(); }
    else if (activeTab === 'userbot') { loadUserbotStatus(); checkApiConfig(); }
  }, [activeTab, loadConversations, loadStars, loadChannel, loadImages, loadUserbotStatus, checkApiConfig]);

  const handleActivate = async () => { if (!id) return; setActionLoading(true); try { await characters.activate(id); await fetchCharacter(); } catch {} setActionLoading(false); };
  const handleDeactivate = async () => { if (!id) return; setActionLoading(true); try { await characters.deactivate(id); await fetchCharacter(); } catch {} setActionLoading(false); };
  const handleClone = async () => { if (!id) return; setActionLoading(true); try { const res = await characters.clone(id); const newId = res.data?.data?.id ?? res.data?.character?.id ?? res.data?.id; if (newId) navigate(`/characters/${newId}`); } catch {} setActionLoading(false); };
  const handleDelete = async () => { if (!id || !window.confirm('Bu karakteri silmek istediğinize emin misiniz?')) return; setActionLoading(true); try { await characters.delete(id); navigate('/characters'); } catch {} setActionLoading(false); };

  const startEdit = (sectionKey: string) => { if (!character) return; const section = (character as unknown as Record<string, unknown>)[sectionKey]; setEditingSection(sectionKey); setEditBuffer(JSON.stringify(section, null, 2)); };
  const cancelEdit = () => { setEditingSection(null); setEditBuffer(''); };
  const saveEdit = async () => { if (!id || !editingSection) return; setSaving(true); try { const parsed = JSON.parse(editBuffer); await characters.update(id, { [editingSection]: parsed }); await fetchCharacter(); setEditingSection(null); setEditBuffer(''); } catch { alert('Kaydetme başarısız. JSON formatını kontrol edin.'); } setSaving(false); };

  /* Userbot handlers */
  const handleUserbotLogin = async () => { if (!id || !userbotPhone.trim()) return; setUserbotSaving(true); setUserbotMsg(null); try { await userbot.startLogin({ characterId: id, phoneNumber: userbotPhone.trim() }); setUserbotStep('code_sent'); setUserbotMsg({ type: 'success', text: 'Doğrulama kodu gönderildi! Telefonunuzu kontrol edin.' }); } catch (err: any) { setUserbotMsg({ type: 'error', text: err?.response?.data?.error || 'Giriş başlatılamadı.' }); } setUserbotSaving(false); };
  const handleUserbotVerify = async () => { if (!id) return; setUserbotSaving(true); setUserbotMsg(null); try { const payload: { characterId: string; code?: string; password?: string } = { characterId: id }; if (userbotStep === 'needs_password') { payload.password = userbotPassword; } else { payload.code = userbotCode; } const res = await userbot.verifyLogin(payload); const data = res.data?.data ?? res.data; if (data?.needsPassword) { setUserbotStep('needs_password'); setUserbotMsg({ type: 'success', text: '2FA şifresi gerekli. Lütfen şifrenizi girin.' }); } else { setUserbotStep('connected'); setUserbotMsg({ type: 'success', text: 'Giriş başarılı! Userbot aktif.' }); await loadUserbotStatus(); } } catch (err: any) { const errMsg = err?.response?.data?.error || 'Doğrulama başarısız.'; if (errMsg.includes('password') || errMsg.includes('2FA')) { setUserbotStep('needs_password'); setUserbotMsg({ type: 'success', text: '2FA şifresi gerekli.' }); } else { setUserbotMsg({ type: 'error', text: errMsg }); } } setUserbotSaving(false); };
  const handleUserbotLogout = async () => { if (!id || !window.confirm('Userbot bağlantısını kesmek istediğinize emin misiniz?')) return; setUserbotSaving(true); setUserbotMsg(null); try { await userbot.logout({ characterId: id }); setUserbotStep('idle'); setUserbotStatus(null); setUserbotCode(''); setUserbotPassword(''); setUserbotMsg({ type: 'success', text: 'Bağlantı kesildi.' }); } catch (err: any) { setUserbotMsg({ type: 'error', text: err?.response?.data?.error || 'Çıkış yapılamadı.' }); } setUserbotSaving(false); };

  /* Render helpers */
  const renderDNATab = () => {
    if (!character) return null;
    return (
      <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex flex-col gap-4">
        {dnaSections.map(({ key, label }) => {
          const section = (character as unknown as Record<string, unknown>)[key];
          if (section == null || typeof section !== 'object') return null;
          const isEditing = editingSection === key;
          return (
            <motion.div key={key} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className={`${glassCard} p-4`}>
              <div className="flex justify-between items-center mb-3">
                <h3 className="m-0 text-base text-slate-100">{label}</h3>
                {isEditing ? (
                  <div className="flex gap-2">
                    <button onClick={saveEdit} disabled={saving} className="px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs cursor-pointer transition-colors">{saving ? 'Kaydediliyor...' : 'Kaydet'}</button>
                    <button onClick={cancelEdit} className="px-3 py-1.5 rounded-lg bg-white/[0.06] border border-white/[0.06] hover:bg-white/[0.1] text-slate-300 text-xs cursor-pointer transition-colors">İptal</button>
                  </div>
                ) : (
                  <button onClick={() => startEdit(key)} className="px-3 py-1.5 rounded-lg bg-white/[0.06] border border-white/[0.06] hover:bg-white/[0.1] text-slate-300 text-xs cursor-pointer transition-colors">Düzenle</button>
                )}
              </div>
              {isEditing ? (
                <textarea value={editBuffer} onChange={(e) => setEditBuffer(e.target.value)} className="w-full min-h-[150px] font-mono text-xs p-3 border border-white/[0.06] rounded-xl bg-white/[0.03] text-slate-100 resize-y outline-none focus:border-indigo-500/50" />
              ) : (
                <div>{Object.entries(section as Record<string, unknown>).map(([field, val]) => (
                  <div key={field} className="flex gap-2 py-1 text-sm border-b border-white/[0.04]">
                    <span className="text-slate-500 min-w-[140px] shrink-0">{field}:</span>
                    <span className="flex-1 text-slate-200">{renderValue(val)}</span>
                  </div>
                ))}</div>
              )}
            </motion.div>
          );
        })}
      </motion.div>
    );
  };

  const renderConversationsTab = () => {
    if (convosLoading) return <p className="text-slate-400">Yükleniyor...</p>;
    if (convos.length === 0) return <p className="text-slate-400">Henüz konuşma yok.</p>;
    return (<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex flex-col gap-2">
      {convos.map((c) => (<div key={c.telegramUserId} className={`${glassCard} p-4`}>
        <div className="flex justify-between items-center">
          <div><strong className="text-slate-100">{c.userName ?? `Kullanıcı #${c.telegramUserId}`}</strong><div className="text-xs text-slate-400 mt-0.5">💬 {c.totalMessages} mesaj</div></div>
          <span className="text-xs text-slate-400">{c.lastActivity ? new Date(c.lastActivity).toLocaleString('tr-TR') : '—'}</span>
        </div>
      </div>))}
    </motion.div>);
  };

  const renderStarsTab = () => {
    if (starsLoading) return <p className="text-slate-400">Yükleniyor...</p>;
    return (<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
      <div className="grid grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-4 mb-6">
        <div className={`${glassCard} p-4 text-center`}><div className="text-xs text-slate-400">Toplam Kazanç</div><div className="text-xl font-bold text-slate-100">⭐ {starsStats?.totalEarned ?? 0}</div></div>
        <div className={`${glassCard} p-4 text-center`}><div className="text-xs text-slate-400">İşlem Sayısı</div><div className="text-xl font-bold text-slate-100">{starsStats?.totalTransactions ?? 0}</div></div>
        <div className={`${glassCard} p-4 text-center`}><div className="text-xs text-slate-400">Dönüşüm Oranı</div><div className="text-xl font-bold text-slate-100">{starsStats?.conversionRate != null ? `%${(starsStats.conversionRate * 100).toFixed(1)}` : '—'}</div></div>
      </div>
      <h3 className="text-base mb-3 text-slate-100">Son İşlemler</h3>
      {transactions.length === 0 ? <p className="text-slate-400">Henüz işlem yok.</p> : (
        <div className={`${glassCard} overflow-hidden`}>
          <table className="w-full border-collapse">
            <thead><tr><th className="text-left px-3 py-2.5 bg-white/[0.02] text-xs text-slate-400 border-b border-white/[0.06]">Tarih</th><th className="text-left px-3 py-2.5 bg-white/[0.02] text-xs text-slate-400 border-b border-white/[0.06]">Tür</th><th className="text-left px-3 py-2.5 bg-white/[0.02] text-xs text-slate-400 border-b border-white/[0.06]">Miktar</th><th className="text-left px-3 py-2.5 bg-white/[0.02] text-xs text-slate-400 border-b border-white/[0.06]">Durum</th></tr></thead>
            <tbody>{transactions.map((tx) => (<tr key={tx.id}><td className="px-3 py-2 text-sm text-slate-300 border-b border-white/[0.04]">{tx.createdAt ? new Date(tx.createdAt).toLocaleString('tr-TR') : '—'}</td><td className="px-3 py-2 text-sm text-slate-300 border-b border-white/[0.04]">{tx.type}</td><td className="px-3 py-2 text-sm text-slate-300 border-b border-white/[0.04]">⭐ {tx.starCount}</td><td className="px-3 py-2 text-sm text-slate-300 border-b border-white/[0.04]">{tx.status}</td></tr>))}</tbody>
          </table>
        </div>
      )}
    </motion.div>);
  };

  const renderChannelTab = () => {
    if (channelLoading) return <p className="text-slate-400">Yükleniyor...</p>;
    if (!channelInfo) return <p className="text-slate-400">Kanal bilgisi bulunamadı.</p>;
    const renderCh = (label: string, ch?: { id?: string; title?: string; memberCount?: number }) => (
      <div className={`${glassCard} p-4`}><h3 className="m-0 mb-2 text-base text-slate-100">{label}</h3>
        {ch ? (<div className="text-sm flex flex-col gap-1 text-slate-300"><span>Başlık: {ch.title ?? '—'}</span><span>ID: {ch.id ?? '—'}</span><span>Üye: {ch.memberCount ?? 0}</span></div>) : (<p className="text-slate-400 m-0">Oluşturulmamış</p>)}
      </div>
    );
    return (<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex flex-col gap-4">{renderCh('📢 Normal Kanal', channelInfo.normal)}{renderCh('👑 VIP Kanal', channelInfo.vip)}</motion.div>);
  };

  const renderImagesTab = () => {
    const aspectRatios = ['9:16', '1:1', '16:9', '4:3', '3:4'];
    return (<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex flex-col gap-6">
      <div className={`${glassCard} p-5`}>
        <h3 className="m-0 mb-4 text-base text-slate-100"> Görsel Üret</h3>
        <p className="text-xs text-slate-500 mb-3">nano-banana-2 modeli ile üretim yapılır. 7 referans görsel otomatik eklenir.</p>
        <div className="flex flex-col gap-3 mb-4">
          <div className="flex flex-col gap-1.5"><label className="text-xs text-slate-400">Prompt</label>
            <textarea value={customPrompt} onChange={(e) => setCustomPrompt(e.target.value)} placeholder="Üretmek istediğiniz görseli tanımlayın... Örn: casual selfie at a cafe, smiling, natural lighting" rows={3}
              className="w-full px-3 py-2 rounded-lg bg-white/[0.03] border border-white/[0.06] text-slate-100 text-sm focus:outline-none focus:border-indigo-500 placeholder-slate-600 resize-y" />
          </div>
          <div className="flex items-center gap-3">
            <div className="flex flex-col gap-1.5"><label className="text-xs text-slate-400">En-Boy Oranı</label>
              <select value={selectedAspectRatio} onChange={(e) => setSelectedAspectRatio(e.target.value)} className="px-3 py-2 rounded-lg bg-white/[0.03] border border-white/[0.06] text-slate-100 text-sm focus:outline-none focus:border-indigo-500">
                {aspectRatios.map((r) => <option key={r} value={r}>{r}</option>)}
              </select></div>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleGenerateImage} disabled={generating || !customPrompt.trim()}
            className="px-5 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white text-sm font-medium cursor-pointer transition-colors border-none">
            {generating ? ' Üretiliyor...' : ' Üret'}
          </motion.button>
          {genMessage && <span className={`text-sm ${genMessage.type === 'success' ? 'text-emerald-400' : 'text-red-400'}`}>{genMessage.text}</span>}
        </div>
      </div>
      {imagesLoading ? <p className="text-slate-400">Yükleniyor...</p> : imageList.length === 0 ? <p className="text-slate-400">Henüz görsel üretilmemiş.</p> : (
        <div className="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-4">
          {imageList.map((img: any) => (
            <motion.div key={img.imageId || img.id} whileHover={{ y: -2, scale: 1.02 }} className={`${glassCard} p-2 text-center`}>
              {img.url ? <img src={img.url} alt="Üretilen görsel" className="w-full rounded-xl mb-2" /> : <div className="w-full h-[120px] bg-white/[0.03] rounded-xl flex items-center justify-center text-slate-500 mb-2">Görsel yok</div>}
              <div className="text-xs text-slate-400">{img.filename}</div>
            </motion.div>
          ))}
        </div>
      )}
    </motion.div>);
  };

  const handleGenerateRefImages = async () => {
    if (!id || refGenerating) return;
    setRefGenerating(true);
    setRefGenMessage(null);
    try {
      await characters.regenerateReferenceImages(id);
      setRefGenMessage({ type: 'success', text: 'Referans görselleri oluşturma kuyruğa eklendi! Birkaç dakika sürebilir.' });
      // Poll for completion
      setTimeout(async () => { await loadRefImages(); }, 30000);
      setTimeout(async () => { await loadRefImages(); }, 60000);
      setTimeout(async () => { await loadRefImages(); setRefGenerating(false); }, 120000);
    } catch (err: any) {
      setRefGenMessage({ type: 'error', text: err?.response?.data?.error || 'Referans görselleri oluşturulurken hata oluştu.' });
      setRefGenerating(false);
    }
  };

  const renderReferenceImages = () => {
    if (refImagesLoading) return null;
    const hasImages = refImages.length > 0;
    return (<div className="mb-6">
      <div className="flex items-center justify-between mb-3">
        <h2 className="m-0 text-lg text-slate-100">📸 Referans Görseller</h2>
        <div className="flex items-center gap-2">
          {refGenMessage && (
            <span className={`text-xs ${refGenMessage.type === 'success' ? 'text-emerald-400' : 'text-red-400'}`}>{refGenMessage.text}</span>
          )}
          {hasImages && <button onClick={handleGenerateRefImages} disabled={refGenerating} className={`px-3 py-1.5 rounded-lg text-xs border-none transition-all ${refGenerating ? 'bg-amber-600/30 text-amber-300 cursor-wait opacity-70' : 'bg-amber-600/80 text-amber-100 hover:bg-amber-500 cursor-pointer'}`}>{refGenerating ? '⏳ Üretiliyor...' : '🔄 Referans Görselleri Yeniden Üret'}</button>}
        </div>
      </div>
      {hasImages ? (
        <div className="flex gap-3 overflow-x-auto pb-2">
          {REFERENCE_IMAGE_MAP.filter((r) => refImages.includes(r.filename)).map((r) => (
            <div key={r.filename} className="flex-shrink-0 flex flex-col items-center gap-1.5">
              <img src={`/static/characters/${id}/reference-images/${r.filename}`} alt={r.label} className="w-[150px] h-[150px] object-cover rounded-xl border border-white/[0.06]" />
              <span className="text-xs text-slate-400">{r.label}</span>
            </div>
          ))}
        </div>
      ) : (
        <div className={`${glassCard} p-6 text-center`}>
          <p className="text-slate-400 mb-3">Henüz referans görseli oluşturulmamış.</p>
          <button onClick={handleGenerateRefImages} disabled={refGenerating} className={`px-4 py-2 rounded-lg text-sm border-none transition-all ${refGenerating ? 'bg-indigo-600/30 text-indigo-300 cursor-wait opacity-70' : 'bg-indigo-600 text-indigo-100 hover:bg-indigo-500 cursor-pointer'}`}>{refGenerating ? '⏳ Üretiliyor...' : '🎨 Referans Görselleri Üret'}</button>
        </div>
      )}
    </div>);
  };

  const renderUserbotTab = () => {
    if (userbotLoading || apiConfigLoading) return <p className="text-slate-400">Yükleniyor...</p>;
    const inputCls = "flex-1 px-3 py-2 rounded-lg bg-white/[0.03] border border-white/[0.06] text-slate-100 text-sm focus:outline-none focus:border-indigo-500 placeholder-slate-500";
    return (<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex flex-col gap-4">
      {userbotMsg && <div className={`px-4 py-2 rounded-lg text-sm ${userbotMsg.type === 'success' ? 'bg-emerald-900/50 text-emerald-300 border border-emerald-700/50' : 'bg-red-900/50 text-red-300 border border-red-700/50'}`}>{userbotMsg.text}</div>}
      {userbotStep === 'connected' ? (
        <div className={`${glassCard} p-5`}>
          <div className="flex items-center gap-3 mb-4"><h3 className="m-0 text-base text-slate-100">📱 Userbot Durumu</h3><span className="text-xs px-2 py-0.5 rounded-full bg-emerald-500 text-white font-semibold">Bağlı</span></div>
          <div className="flex flex-col gap-2 mb-4">
            {userbotPhone && <div className="flex gap-2 text-sm"><span className="text-slate-500 min-w-[120px]">Telefon:</span><span className="text-slate-200">{userbotPhone}</span></div>}
            <div className="flex gap-2 text-sm"><span className="text-slate-500 min-w-[120px]">Durum:</span><span className="text-emerald-400">Aktif — mesajlara otomatik yanıt veriyor</span></div>
          </div>
          <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleUserbotLogout} disabled={userbotSaving} className="px-4 py-2 rounded-lg bg-red-600 hover:bg-red-500 disabled:opacity-50 text-white text-sm font-medium cursor-pointer transition-colors border-none">{userbotSaving ? 'Çıkış yapılıyor...' : '🔌 Bağlantıyı Kes'}</motion.button>
        </div>
      ) : userbotStep === 'code_sent' ? (
        <div className={`${glassCard} p-5`}>
          <h3 className="m-0 mb-2 text-base text-slate-100">🔐 Doğrulama Kodu</h3>
          <p className="text-sm text-slate-400 mb-4">Telegram'a gelen doğrulama kodunu girin.</p>
          <div className="flex gap-2">
            <input type="text" value={userbotCode} onChange={(e) => setUserbotCode(e.target.value)} placeholder="12345" maxLength={10} className={`${inputCls} text-center tracking-widest text-lg`} />
            <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleUserbotVerify} disabled={userbotSaving || !userbotCode.trim()} className="px-5 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-sm font-medium cursor-pointer transition-colors border-none">{userbotSaving ? 'Doğrulanıyor...' : '✓ Doğrula'}</motion.button>
          </div>
        </div>
      ) : userbotStep === 'needs_password' ? (
        <div className={`${glassCard} p-5`}>
          <h3 className="m-0 mb-2 text-base text-slate-100">🔑 2FA Şifresi</h3>
          <p className="text-sm text-slate-400 mb-4">Bu hesapta iki faktörlü doğrulama aktif. Lütfen şifrenizi girin.</p>
          <div className="flex gap-2">
            <input type="password" value={userbotPassword} onChange={(e) => setUserbotPassword(e.target.value)} placeholder="2FA şifresi" className={inputCls} />
            <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleUserbotVerify} disabled={userbotSaving || !userbotPassword.trim()} className="px-5 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-sm font-medium cursor-pointer transition-colors border-none">{userbotSaving ? 'Doğrulanıyor...' : '✓ Giriş Yap'}</motion.button>
          </div>
        </div>
      ) : apiConfigOk === false ? (
        <div className={`${glassCard} p-5 border-amber-500/30`}>
          <div className="flex items-start gap-3">
            <span className="text-2xl">⚠️</span>
            <div className="flex-1">
              <h3 className="m-0 mb-2 text-base text-amber-300">Telegram API Yapılandırması Gerekli</h3>
              <p className="text-sm text-amber-200/80 mb-4">Telegram API kimlik bilgileri tanımlanmamış. Userbot girişi yapabilmek için önce API ayarlarını yapılandırmanız gerekiyor.</p>
              <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={() => navigate('/settings/api')}
                className="px-5 py-2 rounded-lg bg-amber-600 hover:bg-amber-500 text-white text-sm font-medium cursor-pointer transition-colors border-none">⚙️ API Ayarlarına Git</motion.button>
            </div>
          </div>
        </div>
      ) : (
        <div className={`${glassCard} p-5`}>
          <h3 className="m-0 mb-2 text-base text-slate-100">📱 Userbot Giriş</h3>
          <p className="text-sm text-slate-400 mb-4">Bu karakter için kullanılacak Telegram hesabının telefon numarasını girin. Numara uluslararası formatta olmalı (örn: +905551234567).</p>
          <div className="flex gap-2">
            <input type="tel" value={userbotPhone} onChange={(e) => setUserbotPhone(e.target.value)} placeholder="+905551234567" className={inputCls} />
            <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleUserbotLogin} disabled={userbotSaving || !userbotPhone.trim()} className="px-5 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white text-sm font-medium cursor-pointer transition-colors border-none">{userbotSaving ? 'Gönderiliyor...' : '📲 Kod Gönder'}</motion.button>
          </div>
          <div className="mt-4 rounded-xl border border-amber-500/20 bg-amber-500/5 p-3 text-xs text-amber-300">⚠️ Bu numara ile Telegram'a giriş yapılacak. Numara aktif bir Telegram hesabına ait olmalıdır. Her karakter için farklı bir telefon numarası kullanın.</div>
        </div>
      )}
    </motion.div>);
  };

  /* Main render */
  if (loading) return <div className="p-8 text-center text-slate-400">Yükleniyor...</div>;
  if (error || !character) {
    return (<div className="p-8 text-center">
      <p className="text-red-400">{error ?? 'Karakter bulunamadı.'}</p>
      <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={() => navigate('/characters')}
        className="px-3 py-1.5 rounded-xl bg-white/[0.06] border border-white/[0.06] hover:bg-white/[0.1] text-slate-300 text-sm transition-colors">← Listeye Dön</motion.button>
    </div>);
  }

  return (
    <div>
      {/* Header */}
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="flex justify-between items-center mb-6 flex-wrap gap-3">
        <div className="flex items-center gap-4">
          <motion.button whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} onClick={() => navigate('/characters')}
            className="px-3 py-1.5 rounded-xl bg-white/[0.06] border border-white/[0.06] hover:bg-white/[0.1] text-slate-300 text-sm transition-colors">← Geri</motion.button>
          {headerImgError ? (
            <div className="w-[44px] h-[44px] rounded-full bg-gradient-to-br from-indigo-500/20 to-violet-500/20 border border-indigo-500/20 flex items-center justify-center shrink-0">
              <span className="text-[15px] font-bold text-indigo-300">{(character.identity?.name ?? '?')[0].toUpperCase()}</span>
            </div>
          ) : (
            <div className="relative w-[44px] h-[44px] shrink-0">
              {!headerImgLoaded && (
                <div className="absolute inset-0 rounded-full bg-white/[0.06] animate-pulse" />
              )}
              <img
                src={`/static/characters/${id}/reference-images/master.jpg`}
                alt={character.identity?.name ?? ''}
                className={`w-[44px] h-[44px] rounded-full object-cover border border-white/[0.06] ${!headerImgLoaded ? 'opacity-0' : 'opacity-100'} transition-opacity duration-200`}
                onLoad={() => setHeaderImgLoaded(true)}
                onError={() => setHeaderImgError(true)}
              />
            </div>
          )}
          <h1 className="m-0 text-2xl bg-gradient-to-r from-indigo-400 via-violet-400 to-purple-400 bg-clip-text text-transparent font-bold">{character.identity?.name ?? 'İsimsiz'}</h1>
          <span className={`text-white text-xs px-2 py-0.5 rounded-full font-semibold ${statusColors[character.status] ?? 'bg-slate-400'}`}>{statusLabels[character.status] ?? character.status}</span>
        </div>
        <div className="flex gap-2 flex-wrap">
          {character.status === 'active' ? (
            <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleDeactivate} disabled={actionLoading} className="text-white border-none px-4 py-2 rounded-xl cursor-pointer text-sm transition-colors bg-amber-600 hover:bg-amber-500">Deaktif Et</motion.button>
          ) : (
            <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleActivate} disabled={actionLoading} className="text-white border-none px-4 py-2 rounded-xl cursor-pointer text-sm transition-colors bg-emerald-600 hover:bg-emerald-500">Aktifleştir</motion.button>
          )}
          <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={() => navigate(`/characters/${id}/telegram`)} className="text-white border-none px-4 py-2 rounded-xl cursor-pointer text-sm transition-colors bg-cyan-600 hover:bg-cyan-500"> Telegram Yönetimi</motion.button>
          <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleClone} disabled={actionLoading} className="text-white border-none px-4 py-2 rounded-xl cursor-pointer text-sm transition-colors bg-blue-600 hover:bg-blue-500">Klonla</motion.button>
          <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleDelete} disabled={actionLoading} className="text-white border-none px-4 py-2 rounded-xl cursor-pointer text-sm transition-colors bg-red-600 hover:bg-red-500">Sil</motion.button>
        </div>
      </motion.div>

      {renderReferenceImages()}

      {/* Tabs */}
      <div className="flex gap-1 mb-6 border-b border-white/[0.06] flex-wrap relative">
        {(Object.keys(tabLabels) as Tab[]).map((tab) => (
          <button key={tab} onClick={() => setActiveTab(tab)}
            className={`relative px-4 py-2.5 border-none bg-transparent cursor-pointer text-sm transition-colors ${activeTab === tab ? 'font-semibold text-indigo-400' : 'text-slate-400 hover:text-slate-200'}`}>
            {tab === activeTab && <motion.div layoutId="tabIndicator" className="absolute bottom-0 left-0 right-0 h-0.5 bg-gradient-to-r from-indigo-500 to-violet-500 rounded-full" transition={{ type: 'spring', stiffness: 350, damping: 30 }} />}
            {tabLabels[tab]}
          </button>
        ))}
      </div>

      {/* Tab content */}
      <AnimatePresence mode="wait">
        <motion.div key={activeTab} initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -8 }} transition={{ duration: 0.2 }}>
          {activeTab === 'dna' && renderDNATab()}
          {activeTab === 'conversations' && renderConversationsTab()}
          {activeTab === 'stars' && renderStarsTab()}
          {activeTab === 'channel' && renderChannelTab()}
          {activeTab === 'images' && renderImagesTab()}
          {activeTab === 'userbot' && renderUserbotTab()}
        </motion.div>
      </AnimatePresence>
    </div>
  );
};

export default CharacterDetail;