import { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Phone, Shield, CheckCircle2, XCircle, AlertTriangle,
  Wifi, WifiOff, Hash, Send, Lock, LogOut, RefreshCw,
  Radio, Users, MessageSquare, Settings, Star, Calendar,
  ChevronRight, Save, Loader2, Image, Gift,
} from 'lucide-react';
import {
  characters, userbot, system, telegramManagement, images,
} from '../../api/client';

/* ── Types ── */
interface CharacterInfo {
  id: string;
  identity: { name: string; [k: string]: unknown };
}

interface UserbotStatus {
  connected: boolean;
  phoneNumber?: string;
}

interface TelegramEntity {
  id: string;
  characterId: string;
  telegramChatId: number;
  type: 'group' | 'supergroup' | 'channel';
  isVip: boolean;
  title: string;
  description?: string;
  inviteLink?: string;
  memberCount?: number;
  starPrice?: number;
  profilePhotoPath?: string;
  createdAt: string;
  updatedAt: string;
}

interface TelegramEntityMember {
  telegramUserId: number;
  name: string;
  username?: string;
  role: 'admin' | 'member';
  joinedAt?: string;
}

interface CharacterImage {
  id: string;
  url?: string;
  path?: string;
  prompt?: string;
  createdAt?: string;
}

type LoginStep = 'idle' | 'code_sent' | 'needs_password' | 'connected';
type ActiveSection = 'session' | 'groups' | 'entities' | 'publish' | 'gifts';

/* ── Shared styles ── */
const card = 'rounded-2xl border border-white/[0.06] bg-white/[0.02]';
const inputCls =
  'w-full rounded-xl border border-white/[0.08] bg-white/[0.04] px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-indigo-500/50 focus:ring-1 focus:ring-indigo-500/30 transition-all';
const btnPrimary =
  'flex items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-indigo-500 to-violet-600 px-5 py-3 text-sm font-medium text-white shadow-lg shadow-indigo-500/20 hover:shadow-indigo-500/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer';
const btnDanger =
  'flex items-center justify-center gap-2 rounded-xl border border-red-500/20 bg-red-500/10 px-5 py-3 text-sm font-medium text-red-400 hover:bg-red-500/20 transition-all disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer';
const btnSecondary =
  'flex items-center justify-center gap-2 rounded-xl border border-white/[0.08] bg-white/[0.04] px-5 py-3 text-sm font-medium text-slate-300 hover:bg-white/[0.08] transition-all disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer';

/* ── Section tabs (extensible for future tasks) ── */
const SECTIONS: { key: ActiveSection; label: string; icon: typeof Phone }[] = [
  { key: 'session', label: 'Oturum', icon: Radio },
  { key: 'groups', label: 'Gruplar & Kanallar', icon: Users },
  { key: 'entities', label: 'Entity Listesi', icon: MessageSquare },
  { key: 'publish', label: 'Yayınla', icon: Send },
  { key: 'gifts', label: 'Hediye Kataloğu', icon: Gift },
];

/* ══════════════════════════════════════════════════════════════════
   Main Component
   ══════════════════════════════════════════════════════════════════ */

const TelegramManagement: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  /* ── State ── */
  const [character, setCharacter] = useState<CharacterInfo | null>(null);
  const [status, setStatus] = useState<UserbotStatus | null>(null);
  const [entityCount, setEntityCount] = useState(0);
  const [apiConfigOk, setApiConfigOk] = useState<boolean | null>(null);
  const [loading, setLoading] = useState(true);

  // Login flow
  const [step, setStep] = useState<LoginStep>('idle');
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [password, setPassword] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [msg, setMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // Section tabs
  const [activeSection, setActiveSection] = useState<ActiveSection>('session');

  // Group creation form
  const [groupTitle, setGroupTitle] = useState('');
  const [groupDesc, setGroupDesc] = useState('');
  const [groupType, setGroupType] = useState<'normal' | 'supergroup'>('normal');
  const [groupSubmitting, setGroupSubmitting] = useState(false);
  const [groupMsg, setGroupMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // Channel creation form
  const [channelTitle, setChannelTitle] = useState('');
  const [channelDesc, setChannelDesc] = useState('');
  const [channelType, setChannelType] = useState<'public' | 'vip'>('public');
  const [starPrice, setStarPrice] = useState<number>(0);
  const [channelSubmitting, setChannelSubmitting] = useState(false);
  const [channelMsg, setChannelMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // Entity list & editing state
  const [entities, setEntities] = useState<TelegramEntity[]>([]);
  const [entitiesLoading, setEntitiesLoading] = useState(false);
  const [selectedEntityId, setSelectedEntityId] = useState<string | null>(null);
  const [editTitle, setEditTitle] = useState('');
  const [editDesc, setEditDesc] = useState('');
  const [editIsVip, setEditIsVip] = useState(false);
  const [editStarPrice, setEditStarPrice] = useState<number>(0);
  const [entitySaving, setEntitySaving] = useState(false);
  const [entityMsg, setEntityMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // Members state
  const [members, setMembers] = useState<TelegramEntityMember[]>([]);
  const [membersLoading, setMembersLoading] = useState(false);
  const [entitiesLoaded, setEntitiesLoaded] = useState(false);

  // Publish form state
  const [publishEntityId, setPublishEntityId] = useState('');
  const [publishText, setPublishText] = useState('');
  const [publishImageUrl, setPublishImageUrl] = useState('');
  const [publishStarAmount, setPublishStarAmount] = useState<number | ''>('');
  const [publishSubmitting, setPublishSubmitting] = useState(false);
  const [publishMsg, setPublishMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [characterImages, setCharacterImages] = useState<CharacterImage[]>([]);
  const [imagesLoading, setImagesLoading] = useState(false);
  const [publishEntitiesLoaded, setPublishEntitiesLoaded] = useState(false);

  // Gift catalog state
  const [starGifts, setStarGifts] = useState<Array<{
    id: string;
    stars: number;
    limited: boolean;
    soldOut: boolean;
    availabilityRemains?: number;
    availabilityTotal?: number;
    convertStars: number;
    stickerId?: string;
  }>>([]);
  const [giftsLoading, setGiftsLoading] = useState(false);
  const [giftsLoaded, setGiftsLoaded] = useState(false);
  const [giftsError, setGiftsError] = useState<string | null>(null);
  const [giftFilter, setGiftFilter] = useState<'all' | 'available' | 'limited' | 'soldOut'>('all');
  const [giftSort, setGiftSort] = useState<'price-asc' | 'price-desc'>('price-asc');

  // Gift sending state
  const [selectedGift, setSelectedGift] = useState<{
    id: string;
    stars: number;
    limited: boolean;
    soldOut: boolean;
  } | null>(null);
  const [giftRecipient, setGiftRecipient] = useState('');
  const [giftMessage, setGiftMessage] = useState('');
  const [giftSending, setGiftSending] = useState(false);
  const [giftSendMsg, setGiftSendMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  /* ── Data loaders ── */
  const loadCharacter = useCallback(async () => {
    if (!id) return;
    try {
      const res = await characters.get(id);
      setCharacter(res.data?.data ?? res.data?.character ?? res.data);
    } catch {
      /* silent */
    }
  }, [id]);

  const loadStatus = useCallback(async () => {
    if (!id) return;
    try {
      const res = await userbot.getStatus(id);
      const data = res.data?.data ?? res.data;
      setStatus(data);
      if (data?.connected) {
        setStep('connected');
        if (data.phoneNumber) setPhone(data.phoneNumber);
      }
    } catch {
      setStatus({ connected: false });
    }
  }, [id]);

  const loadEntityCount = useCallback(async () => {
    if (!id) return;
    try {
      const res = await telegramManagement.listEntities(id);
      const list = res.data?.data ?? res.data?.entities ?? res.data ?? [];
      setEntityCount(Array.isArray(list) ? list.length : 0);
    } catch {
      setEntityCount(0);
    }
  }, [id]);

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

  const loadEntities = useCallback(async () => {
    if (!id) return;
    setEntitiesLoading(true);
    try {
      const res = await telegramManagement.listEntities(id);
      const list = res.data?.data ?? res.data?.entities ?? res.data ?? [];
      setEntities(Array.isArray(list) ? list : []);
      setEntityCount(Array.isArray(list) ? list.length : 0);
    } catch {
      setEntities([]);
    }
    setEntitiesLoading(false);
    setEntitiesLoaded(true);
  }, [id]);

  const loadMembers = useCallback(async (entityId: string) => {
    if (!id) return;
    setMembersLoading(true);
    try {
      const res = await telegramManagement.getMembers(id, entityId);
      const list = res.data?.data ?? res.data?.members ?? res.data ?? [];
      setMembers(Array.isArray(list) ? list : []);
    } catch {
      setMembers([]);
    }
    setMembersLoading(false);
  }, [id]);

  const loadCharacterImages = useCallback(async () => {
    if (!id) return;
    setImagesLoading(true);
    try {
      const res = await images.list(id);
      const list = res.data?.data ?? res.data?.images ?? res.data ?? [];
      setCharacterImages(Array.isArray(list) ? list : []);
    } catch {
      setCharacterImages([]);
    }
    setImagesLoading(false);
  }, [id]);

  const loadStarGifts = useCallback(async () => {
    if (!id) return;
    setGiftsLoading(true);
    setGiftsError(null);
    try {
      const res = await telegramManagement.getStarGifts(id);
      const list = res.data?.data ?? res.data ?? [];
      setStarGifts(Array.isArray(list) ? list : []);
    } catch (err: any) {
      const errMsg = err?.response?.data?.error || 'Hediye kataloğu yüklenemedi.';
      setGiftsError(errMsg);
      setStarGifts([]);
    }
    setGiftsLoading(false);
    setGiftsLoaded(true);
  }, [id]);

  const handleSendGift = async () => {
    if (!id || !selectedGift || !giftRecipient.trim()) return;
    setGiftSending(true);
    setGiftSendMsg(null);
    try {
      const data: { giftId: string; recipientId?: string; recipientUsername?: string; message?: string } = { giftId: selectedGift.id };
      const recipient = giftRecipient.trim();
      // If starts with @ or is not a number, treat as username
      if (recipient.startsWith('@') || isNaN(Number(recipient))) {
        data.recipientUsername = recipient.replace(/^@/, '');
      } else {
        data.recipientId = recipient;
      }
      if (giftMessage.trim()) data.message = giftMessage.trim();
      await telegramManagement.sendGift(id, data);
      setGiftSendMsg({ type: 'success', text: `⭐ ${selectedGift.stars} Stars değerinde hediye başarıyla gönderildi!` });
      setSelectedGift(null);
      setGiftRecipient('');
      setGiftMessage('');
    } catch (err: any) {
      const errText = err?.response?.data?.error || 'Hediye gönderilemedi.';
      setGiftSendMsg({ type: 'error', text: errText });
    }
    setGiftSending(false);
  };

  const loadAll = useCallback(async () => {
    setLoading(true);
    await Promise.allSettled([loadCharacter(), loadStatus(), loadEntityCount(), checkApiConfig()]);
    setLoading(false);
  }, [loadCharacter, loadStatus, loadEntityCount, checkApiConfig]);

  useEffect(() => {
    loadAll();
  }, [loadAll]);

  // Load entities when tab is first activated
  useEffect(() => {
    if (activeSection === 'entities' && !entitiesLoaded) {
      loadEntities();
    }
  }, [activeSection, entitiesLoaded, loadEntities]);

  // Load entities and images when publish tab is activated
  useEffect(() => {
    if (activeSection === 'publish' && !publishEntitiesLoaded) {
      loadEntities();
      loadCharacterImages();
      setPublishEntitiesLoaded(true);
    }
  }, [activeSection, publishEntitiesLoaded, loadEntities, loadCharacterImages]);

  // Load gifts when gifts tab is activated
  useEffect(() => {
    if (activeSection === 'gifts' && !giftsLoaded) {
      loadStarGifts();
    }
  }, [activeSection, giftsLoaded, loadStarGifts]);

  // When selecting an entity, populate edit fields and load members
  const handleSelectEntity = useCallback((entity: TelegramEntity) => {
    if (selectedEntityId === entity.id) {
      setSelectedEntityId(null);
      setMembers([]);
      setEntityMsg(null);
      return;
    }
    setSelectedEntityId(entity.id);
    setEditTitle(entity.title);
    setEditDesc(entity.description ?? '');
    setEditIsVip(entity.isVip);
    setEditStarPrice(entity.starPrice ?? 0);
    setEntityMsg(null);
    loadMembers(entity.id);
  }, [selectedEntityId, loadMembers]);

  /* ── Entity update handler ── */
  const [entityRetryFn, setEntityRetryFn] = useState<(() => void) | null>(null);
  const handleUpdateEntity = async () => {
    if (!id || !selectedEntityId) return;
    setEntitySaving(true);
    setEntityMsg(null);
    setEntityRetryFn(null);
    try {
      const selectedEntity = entities.find(e => e.id === selectedEntityId);
      const data: Record<string, unknown> = {
        title: editTitle.trim(),
        description: editDesc.trim() || undefined,
      };
      if (selectedEntity?.type === 'channel') {
        data.isVip = editIsVip;
        if (editIsVip) {
          data.starPrice = editStarPrice;
        }
      }
      await telegramManagement.updateEntity(id, selectedEntityId, data);
      setEntityMsg({ type: 'success', text: 'Ayarlar başarıyla güncellendi!' });
      await loadEntities();
    } catch (err: any) {
      const errText = err?.response?.data?.error || 'Güncelleme başarısız.';
      setEntityMsg({ type: 'error', text: errText });
      if (isRetryableError(err)) {
        setEntityRetryFn(() => () => handleUpdateEntity());
      }
    }
    setEntitySaving(false);
  };

  /* ── Login handlers ── */
  const handleStartLogin = async () => {
    if (!id || !phone.trim()) return;
    setSubmitting(true);
    setMsg(null);
    try {
      await userbot.startLogin({ characterId: id, phoneNumber: phone.trim() });
      setStep('code_sent');
      setMsg({ type: 'success', text: 'Doğrulama kodu gönderildi! Telefonunuzu kontrol edin.' });
    } catch (err: any) {
      setMsg({ type: 'error', text: err?.response?.data?.error || 'Giriş başlatılamadı.' });
    }
    setSubmitting(false);
  };

  const handleVerify = async () => {
    if (!id) return;
    setSubmitting(true);
    setMsg(null);
    try {
      const payload: { characterId: string; code?: string; password?: string } = { characterId: id };
      if (step === 'needs_password') {
        payload.password = password;
      } else {
        payload.code = code;
      }
      const res = await userbot.verifyLogin(payload);
      const data = res.data?.data ?? res.data;
      if (data?.needsPassword) {
        setStep('needs_password');
        setMsg({ type: 'success', text: '2FA şifresi gerekli. Lütfen şifrenizi girin.' });
      } else {
        setStep('connected');
        setMsg({ type: 'success', text: 'Giriş başarılı! Userbot aktif.' });
        await loadStatus();
        await loadEntityCount();
      }
    } catch (err: any) {
      const errMsg = err?.response?.data?.error || 'Doğrulama başarısız.';
      if (errMsg.toLowerCase().includes('password') || errMsg.toLowerCase().includes('2fa')) {
        setStep('needs_password');
        setMsg({ type: 'success', text: '2FA şifresi gerekli.' });
      } else {
        setMsg({ type: 'error', text: errMsg });
      }
    }
    setSubmitting(false);
  };

  const handleLogout = async () => {
    if (!id || !window.confirm('Bağlantıyı kesmek istediğinize emin misiniz?')) return;
    setSubmitting(true);
    setMsg(null);
    try {
      await userbot.logout({ characterId: id });
      setStep('idle');
      setStatus({ connected: false });
      setCode('');
      setPassword('');
      setMsg({ type: 'success', text: 'Bağlantı kesildi.' });
    } catch (err: any) {
      setMsg({ type: 'error', text: err?.response?.data?.error || 'Çıkış yapılamadı.' });
    }
    setSubmitting(false);
  };

  /* ── Retryable error helper ── */
  const isRetryableError = (err: any): boolean => {
    return err?.response?.status === 502 || err?.response?.data?.retryable === true;
  };

  /* ── Group creation handler ── */
  const [groupRetryFn, setGroupRetryFn] = useState<(() => void) | null>(null);
  const handleCreateGroup = async () => {
    if (!id || !groupTitle.trim()) return;
    setGroupSubmitting(true);
    setGroupMsg(null);
    setGroupRetryFn(null);
    try {
      await telegramManagement.createGroup(id, {
        title: groupTitle.trim(),
        description: groupDesc.trim() || undefined,
        groupType,
      });
      setGroupMsg({ type: 'success', text: `"${groupTitle.trim()}" grubu başarıyla oluşturuldu!` });
      setGroupTitle('');
      setGroupDesc('');
      setGroupType('normal');
      await loadEntityCount();
    } catch (err: any) {
      const errText = err?.response?.data?.error || 'Grup oluşturulamadı.';
      setGroupMsg({ type: 'error', text: errText });
      if (isRetryableError(err)) {
        setGroupRetryFn(() => () => handleCreateGroup());
      }
    }
    setGroupSubmitting(false);
  };

  /* ── Channel creation handler ── */
  const [channelRetryFn, setChannelRetryFn] = useState<(() => void) | null>(null);
  const [starPriceError, setStarPriceError] = useState<string | null>(null);
  const handleCreateChannel = async () => {
    if (!id || !channelTitle.trim()) return;
    // VIP channel starPrice validation
    if (channelType === 'vip' && (!starPrice || starPrice <= 0)) {
      setStarPriceError('VIP kanal için Stars fiyatı 0\'dan büyük olmalıdır.');
      return;
    }
    setStarPriceError(null);
    setChannelSubmitting(true);
    setChannelMsg(null);
    setChannelRetryFn(null);
    try {
      await telegramManagement.createChannel(id, {
        title: channelTitle.trim(),
        description: channelDesc.trim() || undefined,
        channelType,
        starPrice: channelType === 'vip' ? starPrice : undefined,
      });
      setChannelMsg({ type: 'success', text: `"${channelTitle.trim()}" kanalı başarıyla oluşturuldu!` });
      setChannelTitle('');
      setChannelDesc('');
      setChannelType('public');
      setStarPrice(0);
      await loadEntityCount();
    } catch (err: any) {
      const errText = err?.response?.data?.error || 'Kanal oluşturulamadı.';
      setChannelMsg({ type: 'error', text: errText });
      if (isRetryableError(err)) {
        setChannelRetryFn(() => () => handleCreateChannel());
      }
    }
    setChannelSubmitting(false);
  };

  /* ── Publish handler ── */
  const [publishRetryFn, setPublishRetryFn] = useState<(() => void) | null>(null);
  const handlePublish = async () => {
    if (!id || !publishEntityId || (!publishText.trim() && !publishImageUrl.trim())) return;
    setPublishSubmitting(true);
    setPublishMsg(null);
    setPublishRetryFn(null);
    try {
      const data: Record<string, unknown> = {};
      if (publishText.trim()) data.text = publishText.trim();
      if (publishImageUrl.trim()) data.imageUrl = publishImageUrl.trim();
      if (publishStarAmount && Number(publishStarAmount) > 0) data.starAmount = Number(publishStarAmount);
      await telegramManagement.publishContent(id, publishEntityId, data);
      setPublishMsg({ type: 'success', text: 'İçerik başarıyla yayınlandı!' });
      setPublishText('');
      setPublishImageUrl('');
      setPublishStarAmount('');
    } catch (err: any) {
      const errText = err?.response?.data?.error || 'Yayınlama başarısız.';
      setPublishMsg({ type: 'error', text: errText });
      if (isRetryableError(err)) {
        setPublishRetryFn(() => () => handlePublish());
      }
    }
    setPublishSubmitting(false);
  };

  /* ── Loading state ── */
  if (loading) {
    return (
      <div className="flex min-h-[60vh] items-center justify-center">
        <div className="h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
      </div>
    );
  }

  const charName = character?.identity?.name ?? 'Karakter';
  const isConnected = step === 'connected' || status?.connected;
  const selectedEntity = entities.find(e => e.id === selectedEntityId);

  /* ── Render ── */
  return (
    <div className="max-w-[1000px] mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight">Telegram Yönetimi</h1>
          <p className="text-sm text-slate-500 mt-1">{charName} — Oturum ve bağlantı yönetimi</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => navigate(`/characters/${id}`)}
            className={btnSecondary}
          >
            Karaktere Dön
          </button>
          <button onClick={() => loadAll()} className="p-2 rounded-lg text-slate-500 hover:text-slate-300 hover:bg-white/[0.04] transition-all cursor-pointer">
            <RefreshCw className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Section tabs */}
      <div className="flex gap-1 mb-6 p-1 rounded-xl bg-white/[0.03] border border-white/[0.06] w-fit">
        {SECTIONS.map((s) => {
          const Icon = s.icon;
          const active = activeSection === s.key;
          return (
            <button
              key={s.key}
              onClick={() => setActiveSection(s.key)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg text-[13px] font-medium transition-all cursor-pointer ${
                active
                  ? 'bg-white/[0.08] text-white shadow-sm'
                  : 'text-slate-500 hover:text-slate-300 hover:bg-white/[0.03]'
              }`}
            >
              <Icon className="w-4 h-4" />
              {s.label}
            </button>
          );
        })}
      </div>

      {/* Session section */}
      {activeSection === 'session' && (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-5">

          {/* API Config Warning */}
          {apiConfigOk === false && (
            <motion.div
              initial={{ opacity: 0, scale: 0.98 }}
              animate={{ opacity: 1, scale: 1 }}
              className="rounded-2xl border border-amber-500/20 bg-amber-500/5 p-5"
            >
              <div className="flex items-start gap-3">
                <div className="w-10 h-10 rounded-xl bg-amber-500/20 flex items-center justify-center shrink-0">
                  <AlertTriangle className="w-5 h-5 text-amber-400" />
                </div>
                <div className="flex-1">
                  <h3 className="text-[14px] font-semibold text-amber-300 mb-1">API Yapılandırması Eksik</h3>
                  <p className="text-[13px] text-amber-400/80 mb-3">
                    Telegram API ID ve API Hash bilgileri tanımlanmamış. Telefon bağlama işlemi için önce API yapılandırmasını tamamlayın.
                  </p>
                  <Link
                    to="/settings/api"
                    className="inline-flex items-center gap-2 rounded-lg bg-amber-500/20 px-4 py-2 text-[13px] font-medium text-amber-300 hover:bg-amber-500/30 transition-all"
                  >
                    <Settings className="w-4 h-4" />
                    API Ayarlarına Git
                  </Link>
                </div>
              </div>
            </motion.div>
          )}

          {/* Session Status Card */}
          <div className={`${card} p-6`}>
            <div className="flex items-center gap-3 mb-5">
              <div className={`w-11 h-11 rounded-xl flex items-center justify-center shadow-lg ${
                isConnected ? 'bg-emerald-500' : 'bg-slate-600'
              }`}>
                {isConnected ? <Wifi className="w-5 h-5 text-white" /> : <WifiOff className="w-5 h-5 text-white" />}
              </div>
              <div>
                <h2 className="text-[15px] font-semibold text-white">Oturum Durumu</h2>
                <p className="text-[13px] text-slate-500">Userbot bağlantı bilgileri</p>
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              {/* Connection status */}
              <div className="rounded-xl bg-white/[0.03] border border-white/[0.06] p-4">
                <div className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-2">Durum</div>
                <div className="flex items-center gap-2">
                  <div className={`w-2.5 h-2.5 rounded-full ${isConnected ? 'bg-emerald-400 animate-pulse' : 'bg-slate-500'}`} />
                  <span className={`text-[14px] font-medium ${isConnected ? 'text-emerald-400' : 'text-slate-400'}`}>
                    {isConnected ? 'Bağlı' : 'Bağlı Değil'}
                  </span>
                </div>
              </div>

              {/* Phone number */}
              <div className="rounded-xl bg-white/[0.03] border border-white/[0.06] p-4">
                <div className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-2">Telefon</div>
                <div className="flex items-center gap-2">
                  <Phone className="w-4 h-4 text-slate-500" />
                  <span className="text-[14px] font-medium text-slate-300">
                    {status?.phoneNumber || phone || '—'}
                  </span>
                </div>
              </div>

              {/* Entity count */}
              <div className="rounded-xl bg-white/[0.03] border border-white/[0.06] p-4">
                <div className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-2">Aktif Entity</div>
                <div className="flex items-center gap-2">
                  <Hash className="w-4 h-4 text-slate-500" />
                  <span className="text-[14px] font-medium text-slate-300">{entityCount}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Phone Binding Flow */}
          <div className={`${card} p-6`}>
            <div className="flex items-center gap-3 mb-5">
              <div className="w-11 h-11 rounded-xl bg-indigo-500 flex items-center justify-center shadow-lg">
                <Shield className="w-5 h-5 text-white" />
              </div>
              <div>
                <h2 className="text-[15px] font-semibold text-white">Telefon Bağlama</h2>
                <p className="text-[13px] text-slate-500">Userbot oturumu başlatma ve doğrulama</p>
              </div>
            </div>

            {/* Message banner */}
            <AnimatePresence>
              {msg && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  exit={{ opacity: 0, height: 0 }}
                  className={`mb-4 rounded-xl px-4 py-3 text-[13px] font-medium ${
                    msg.type === 'success'
                      ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
                      : 'bg-red-500/10 text-red-400 border border-red-500/20'
                  }`}
                >
                  <div className="flex items-center gap-2">
                    {msg.type === 'success' ? <CheckCircle2 className="w-4 h-4 shrink-0" /> : <XCircle className="w-4 h-4 shrink-0" />}
                    {msg.text}
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            {/* Connected state */}
            {isConnected && (
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
                <div className="flex items-center gap-3 rounded-xl bg-emerald-500/10 border border-emerald-500/20 p-4">
                  <CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
                  <div>
                    <p className="text-[13px] font-medium text-emerald-300">Userbot aktif ve bağlı</p>
                    <p className="text-[12px] text-emerald-400/70 mt-0.5">
                      {status?.phoneNumber || phone} numarası ile oturum açık
                    </p>
                  </div>
                </div>
                <button onClick={handleLogout} disabled={submitting} className={btnDanger}>
                  <LogOut className="w-4 h-4" />
                  {submitting ? 'İşleniyor...' : 'Bağlantıyı Kes'}
                </button>
              </motion.div>
            )}

            {/* Step 1: Phone number input */}
            {!isConnected && step === 'idle' && (
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
                <div>
                  <label className="block text-[12px] font-medium text-slate-400 mb-2">Telefon Numarası</label>
                  <div className="flex gap-3">
                    <input
                      type="tel"
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      placeholder="+90 5XX XXX XX XX"
                      className={inputCls}
                      disabled={apiConfigOk === false}
                    />
                    <button
                      onClick={handleStartLogin}
                      disabled={submitting || !phone.trim() || apiConfigOk === false}
                      className={btnPrimary + ' shrink-0'}
                    >
                      <Send className="w-4 h-4" />
                      {submitting ? 'Gönderiliyor...' : 'Kod Gönder'}
                    </button>
                  </div>
                  <p className="text-[11px] text-slate-600 mt-2">
                    Uluslararası formatta girin (örn: +905321234567)
                  </p>
                </div>
              </motion.div>
            )}

            {/* Step 2: SMS code verification */}
            {!isConnected && step === 'code_sent' && (
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
                <div>
                  <label className="block text-[12px] font-medium text-slate-400 mb-2">SMS Doğrulama Kodu</label>
                  <div className="flex gap-3">
                    <input
                      type="text"
                      value={code}
                      onChange={(e) => setCode(e.target.value)}
                      placeholder="12345"
                      maxLength={6}
                      className={inputCls}
                    />
                    <button
                      onClick={handleVerify}
                      disabled={submitting || !code.trim()}
                      className={btnPrimary + ' shrink-0'}
                    >
                      <CheckCircle2 className="w-4 h-4" />
                      {submitting ? 'Doğrulanıyor...' : 'Doğrula'}
                    </button>
                  </div>
                  <p className="text-[11px] text-slate-600 mt-2">
                    Telegram uygulamanıza veya SMS olarak gelen kodu girin
                  </p>
                </div>
                <button
                  onClick={() => { setStep('idle'); setCode(''); setMsg(null); }}
                  className="text-[12px] text-slate-500 hover:text-slate-300 transition-colors cursor-pointer"
                >
                  ← Telefon numarasını değiştir
                </button>
              </motion.div>
            )}

            {/* Step 3: 2FA password */}
            {!isConnected && step === 'needs_password' && (
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
                <div>
                  <label className="block text-[12px] font-medium text-slate-400 mb-2">İki Faktörlü Doğrulama Şifresi</label>
                  <div className="flex gap-3">
                    <input
                      type="password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      placeholder="2FA şifreniz"
                      className={inputCls}
                    />
                    <button
                      onClick={handleVerify}
                      disabled={submitting || !password.trim()}
                      className={btnPrimary + ' shrink-0'}
                    >
                      <Lock className="w-4 h-4" />
                      {submitting ? 'Giriş yapılıyor...' : 'Giriş Yap'}
                    </button>
                  </div>
                  <p className="text-[11px] text-slate-600 mt-2">
                    Telegram hesabınızda tanımlı 2FA şifresini girin
                  </p>
                </div>
                <button
                  onClick={() => { setStep('idle'); setPassword(''); setCode(''); setMsg(null); }}
                  className="text-[12px] text-slate-500 hover:text-slate-300 transition-colors cursor-pointer"
                >
                  ← Baştan başla
                </button>
              </motion.div>
            )}
          </div>
        </motion.div>
      )}

      {/* Groups & Channels section */}
      {activeSection === 'groups' && (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-5">

          {/* Not connected warning */}
          {!isConnected && (
            <div className="rounded-2xl border border-amber-500/20 bg-amber-500/5 p-5">
              <div className="flex items-start gap-3">
                <div className="w-10 h-10 rounded-xl bg-amber-500/20 flex items-center justify-center shrink-0">
                  <AlertTriangle className="w-5 h-5 text-amber-400" />
                </div>
                <div className="flex-1">
                  <h3 className="text-[14px] font-semibold text-amber-300 mb-1">Önce userbot oturumu başlatın</h3>
                  <p className="text-[13px] text-amber-400/80">
                    Grup ve kanal oluşturmak için önce Oturum sekmesinden userbot bağlantısını kurun.
                  </p>
                </div>
              </div>
            </div>
          )}

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
            {/* ── Group Creation Form ── */}
            <div className={`${card} p-6`}>
              <div className="flex items-center gap-3 mb-5">
                <div className="w-11 h-11 rounded-xl bg-indigo-500 flex items-center justify-center shadow-lg">
                  <Users className="w-5 h-5 text-white" />
                </div>
                <div>
                  <h2 className="text-[15px] font-semibold text-white">Yeni Grup Oluştur</h2>
                  <p className="text-[13px] text-slate-500">Telegram grubu oluşturun</p>
                </div>
              </div>

              {/* Group message banner */}
              <AnimatePresence>
                {groupMsg && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    className={`mb-4 rounded-xl px-4 py-3 text-[13px] font-medium ${
                      groupMsg.type === 'success'
                        ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
                        : 'bg-red-500/10 text-red-400 border border-red-500/20'
                    }`}
                  >
                    <div className="flex items-center gap-2">
                      {groupMsg.type === 'success' ? <CheckCircle2 className="w-4 h-4 shrink-0" /> : <XCircle className="w-4 h-4 shrink-0" />}
                      <span className="flex-1">{groupMsg.text}</span>
                    </div>
                    {groupRetryFn && groupMsg.type === 'error' && (
                      <button
                        onClick={groupRetryFn}
                        className="mt-2 flex items-center gap-1.5 rounded-lg bg-red-500/20 px-3 py-1.5 text-[12px] font-medium text-red-300 hover:bg-red-500/30 transition-all cursor-pointer"
                      >
                        <RefreshCw className="w-3 h-3" />
                        Yeniden Dene
                      </button>
                    )}
                  </motion.div>
                )}
              </AnimatePresence>

              <div className="space-y-4">
                <div>
                  <label className="block text-[12px] font-medium text-slate-400 mb-2">Grup Adı *</label>
                  <input
                    type="text"
                    value={groupTitle}
                    onChange={(e) => setGroupTitle(e.target.value)}
                    placeholder="Grup adını girin"
                    className={inputCls}
                    disabled={!isConnected}
                  />
                </div>

                <div>
                  <label className="block text-[12px] font-medium text-slate-400 mb-2">Açıklama</label>
                  <textarea
                    value={groupDesc}
                    onChange={(e) => setGroupDesc(e.target.value)}
                    placeholder="Grup açıklaması (isteğe bağlı)"
                    rows={3}
                    className={inputCls + ' resize-none'}
                    disabled={!isConnected}
                  />
                </div>

                <div>
                  <label className="block text-[12px] font-medium text-slate-400 mb-2">Grup Türü</label>
                  <select
                    value={groupType}
                    onChange={(e) => setGroupType(e.target.value as 'normal' | 'supergroup')}
                    className={inputCls}
                    disabled={!isConnected}
                  >
                    <option value="normal">Normal Grup</option>
                    <option value="supergroup">Süper Grup</option>
                  </select>
                </div>

                <button
                  onClick={handleCreateGroup}
                  disabled={groupSubmitting || !groupTitle.trim() || !isConnected}
                  className={btnPrimary + ' w-full'}
                >
                  <Users className="w-4 h-4" />
                  {groupSubmitting ? 'Oluşturuluyor...' : 'Grup Oluştur'}
                </button>
              </div>
            </div>

            {/* ── Channel Creation Form ── */}
            <div className={`${card} p-6`}>
              <div className="flex items-center gap-3 mb-5">
                <div className="w-11 h-11 rounded-xl bg-violet-500 flex items-center justify-center shadow-lg">
                  <Radio className="w-5 h-5 text-white" />
                </div>
                <div>
                  <h2 className="text-[15px] font-semibold text-white">Yeni Kanal Oluştur</h2>
                  <p className="text-[13px] text-slate-500">Telegram kanalı oluşturun</p>
                </div>
              </div>

              {/* Channel message banner */}
              <AnimatePresence>
                {channelMsg && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    className={`mb-4 rounded-xl px-4 py-3 text-[13px] font-medium ${
                      channelMsg.type === 'success'
                        ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
                        : 'bg-red-500/10 text-red-400 border border-red-500/20'
                    }`}
                  >
                    <div className="flex items-center gap-2">
                      {channelMsg.type === 'success' ? <CheckCircle2 className="w-4 h-4 shrink-0" /> : <XCircle className="w-4 h-4 shrink-0" />}
                      <span className="flex-1">{channelMsg.text}</span>
                    </div>
                    {channelRetryFn && channelMsg.type === 'error' && (
                      <button
                        onClick={channelRetryFn}
                        className="mt-2 flex items-center gap-1.5 rounded-lg bg-red-500/20 px-3 py-1.5 text-[12px] font-medium text-red-300 hover:bg-red-500/30 transition-all cursor-pointer"
                      >
                        <RefreshCw className="w-3 h-3" />
                        Yeniden Dene
                      </button>
                    )}
                  </motion.div>
                )}
              </AnimatePresence>

              <div className="space-y-4">
                <div>
                  <label className="block text-[12px] font-medium text-slate-400 mb-2">Kanal Adı *</label>
                  <input
                    type="text"
                    value={channelTitle}
                    onChange={(e) => setChannelTitle(e.target.value)}
                    placeholder="Kanal adını girin"
                    className={inputCls}
                    disabled={!isConnected}
                  />
                </div>

                <div>
                  <label className="block text-[12px] font-medium text-slate-400 mb-2">Açıklama</label>
                  <textarea
                    value={channelDesc}
                    onChange={(e) => setChannelDesc(e.target.value)}
                    placeholder="Kanal açıklaması (isteğe bağlı)"
                    rows={3}
                    className={inputCls + ' resize-none'}
                    disabled={!isConnected}
                  />
                </div>

                <div>
                  <label className="block text-[12px] font-medium text-slate-400 mb-2">Kanal Türü</label>
                  <select
                    value={channelType}
                    onChange={(e) => setChannelType(e.target.value as 'public' | 'vip')}
                    className={inputCls}
                    disabled={!isConnected}
                  >
                    <option value="public">Genel Kanal</option>
                    <option value="vip">VIP Kanal</option>
                  </select>
                </div>

                {/* Stars price — only shown when VIP selected */}
                {channelType === 'vip' && (
                  <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }}>
                    <label className="block text-[12px] font-medium text-slate-400 mb-2">Stars Fiyatı *</label>
                    <input
                      type="number"
                      value={starPrice}
                      onChange={(e) => {
                        setStarPrice(Math.max(0, Number(e.target.value)));
                        setStarPriceError(null);
                      }}
                      placeholder="0"
                      min={1}
                      className={`${inputCls} ${starPriceError ? 'border-red-500/50 focus:border-red-500/50 focus:ring-red-500/30' : ''}`}
                      disabled={!isConnected}
                    />
                    {starPriceError && (
                      <p className="text-[11px] text-red-400 mt-1">{starPriceError}</p>
                    )}
                    {!starPriceError && (
                      <p className="text-[11px] text-slate-600 mt-1">
                        VIP kanala erişim için gereken Stars miktarı (en az 1)
                      </p>
                    )}
                  </motion.div>
                )}

                <button
                  onClick={handleCreateChannel}
                  disabled={channelSubmitting || !channelTitle.trim() || !isConnected}
                  className={btnPrimary + ' w-full'}
                >
                  <Radio className="w-4 h-4" />
                  {channelSubmitting ? 'Oluşturuluyor...' : 'Kanal Oluştur'}
                </button>
              </div>
            </div>
          </div>
        </motion.div>
      )}

      {/* Entities section */}
      {activeSection === 'entities' && (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-5">

          {/* Loading spinner */}
          {entitiesLoading && (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-6 h-6 animate-spin text-indigo-400" />
            </div>
          )}

          {/* Empty state */}
          {!entitiesLoading && entities.length === 0 && (
            <div className={`${card} p-10 text-center`}>
              <div className="w-12 h-12 rounded-xl bg-white/[0.06] flex items-center justify-center mx-auto mb-4">
                <MessageSquare className="w-6 h-6 text-slate-500" />
              </div>
              <p className="text-[14px] text-slate-400 font-medium">Henüz entity yok</p>
              <p className="text-[12px] text-slate-600 mt-1">Gruplar & Kanallar sekmesinden yeni oluşturabilirsiniz</p>
            </div>
          )}

          {/* Entity grid */}
          {!entitiesLoading && entities.length > 0 && (
            <div className="space-y-5">
              <div className="flex items-center justify-between">
                <h2 className="text-[15px] font-semibold text-white">Gruplar & Kanallar ({entities.length})</h2>
                <button onClick={loadEntities} className="p-2 rounded-lg text-slate-500 hover:text-slate-300 hover:bg-white/[0.04] transition-all cursor-pointer">
                  <RefreshCw className="w-4 h-4" />
                </button>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                {entities.map((entity) => {
                  const isSelected = selectedEntityId === entity.id;
                  const isChannel = entity.type === 'channel';
                  return (
                    <button
                      key={entity.id}
                      onClick={() => handleSelectEntity(entity)}
                      className={`${card} p-4 text-left transition-all cursor-pointer hover:bg-white/[0.04] ${
                        isSelected ? 'border-indigo-500/50 bg-indigo-500/5' : ''
                      }`}
                    >
                      <div className="flex items-start gap-3">
                        <div className={`w-10 h-10 rounded-xl flex items-center justify-center shrink-0 ${
                          isChannel ? 'bg-violet-500/20' : 'bg-indigo-500/20'
                        }`}>
                          {isChannel ? <Radio className="w-5 h-5 text-violet-400" /> : <Users className="w-5 h-5 text-indigo-400" />}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="text-[14px] font-medium text-white truncate">{entity.title}</span>
                            {entity.isVip && (
                              <span className="flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-amber-500/20 text-[10px] font-semibold text-amber-400 shrink-0">
                                <Star className="w-3 h-3" /> VIP
                              </span>
                            )}
                          </div>
                          <div className="flex items-center gap-2 flex-wrap">
                            <span className="text-[11px] px-2 py-0.5 rounded-md bg-white/[0.06] text-slate-400 font-medium">
                              {entity.type === 'channel' ? 'Kanal' : entity.type === 'supergroup' ? 'Süper Grup' : 'Grup'}
                            </span>
                            {typeof entity.memberCount === 'number' && (
                              <span className="flex items-center gap-1 text-[11px] text-slate-500">
                                <Users className="w-3 h-3" />
                                {entity.memberCount} üye
                              </span>
                            )}
                            <span className="flex items-center gap-1 text-[11px] text-slate-600">
                              <Calendar className="w-3 h-3" />
                              {new Date(entity.createdAt).toLocaleDateString('tr-TR')}
                            </span>
                          </div>
                        </div>
                        <ChevronRight className={`w-4 h-4 text-slate-600 shrink-0 transition-transform ${isSelected ? 'rotate-90' : ''}`} />
                      </div>
                    </button>
                  );
                })}
              </div>

              {/* Selected entity detail */}
              <AnimatePresence>
                {selectedEntity && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    className="space-y-5"
                  >
                    {/* Settings editing */}
                    <div className={`${card} p-6`}>
                      <div className="flex items-center gap-3 mb-5">
                        <div className="w-11 h-11 rounded-xl bg-indigo-500 flex items-center justify-center shadow-lg">
                          <Settings className="w-5 h-5 text-white" />
                        </div>
                        <div>
                          <h2 className="text-[15px] font-semibold text-white">Ayarları Düzenle</h2>
                          <p className="text-[13px] text-slate-500">{selectedEntity.title}</p>
                        </div>
                      </div>

                      {/* Entity message banner */}
                      <AnimatePresence>
                        {entityMsg && (
                          <motion.div
                            initial={{ opacity: 0, height: 0 }}
                            animate={{ opacity: 1, height: 'auto' }}
                            exit={{ opacity: 0, height: 0 }}
                            className={`mb-4 rounded-xl px-4 py-3 text-[13px] font-medium ${
                              entityMsg.type === 'success'
                                ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
                                : 'bg-red-500/10 text-red-400 border border-red-500/20'
                            }`}
                          >
                            <div className="flex items-center gap-2">
                              {entityMsg.type === 'success' ? <CheckCircle2 className="w-4 h-4 shrink-0" /> : <XCircle className="w-4 h-4 shrink-0" />}
                              <span className="flex-1">{entityMsg.text}</span>
                            </div>
                            {entityRetryFn && entityMsg.type === 'error' && (
                              <button
                                onClick={entityRetryFn}
                                className="mt-2 flex items-center gap-1.5 rounded-lg bg-red-500/20 px-3 py-1.5 text-[12px] font-medium text-red-300 hover:bg-red-500/30 transition-all cursor-pointer"
                              >
                                <RefreshCw className="w-3 h-3" />
                                Yeniden Dene
                              </button>
                            )}
                          </motion.div>
                        )}
                      </AnimatePresence>

                      <div className="space-y-4">
                        <div>
                          <label className="block text-[12px] font-medium text-slate-400 mb-2">Başlık</label>
                          <input
                            type="text"
                            value={editTitle}
                            onChange={(e) => setEditTitle(e.target.value)}
                            placeholder="Entity başlığı"
                            className={inputCls}
                          />
                        </div>

                        <div>
                          <label className="block text-[12px] font-medium text-slate-400 mb-2">Açıklama</label>
                          <textarea
                            value={editDesc}
                            onChange={(e) => setEditDesc(e.target.value)}
                            placeholder="Açıklama (isteğe bağlı)"
                            rows={3}
                            className={inputCls + ' resize-none'}
                          />
                        </div>

                        {/* VIP toggle — channels only */}
                        {selectedEntity.type === 'channel' && (
                          <>
                            <div className="flex items-center justify-between rounded-xl bg-white/[0.03] border border-white/[0.06] p-4">
                              <div>
                                <p className="text-[13px] font-medium text-slate-300">VIP Durumu</p>
                                <p className="text-[11px] text-slate-600 mt-0.5">Stars ile erişim kontrolü</p>
                              </div>
                              <button
                                onClick={() => setEditIsVip(!editIsVip)}
                                className={`relative w-11 h-6 rounded-full transition-colors cursor-pointer ${
                                  editIsVip ? 'bg-indigo-500' : 'bg-white/[0.1]'
                                }`}
                              >
                                <div className={`absolute top-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${
                                  editIsVip ? 'translate-x-[22px]' : 'translate-x-0.5'
                                }`} />
                              </button>
                            </div>

                            {editIsVip && (
                              <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }}>
                                <label className="block text-[12px] font-medium text-slate-400 mb-2">Stars Fiyatı</label>
                                <input
                                  type="number"
                                  value={editStarPrice}
                                  onChange={(e) => setEditStarPrice(Math.max(0, Number(e.target.value)))}
                                  placeholder="0"
                                  min={0}
                                  className={inputCls}
                                />
                                <p className="text-[11px] text-slate-600 mt-1">
                                  VIP kanala erişim için gereken Stars miktarı
                                </p>
                              </motion.div>
                            )}
                          </>
                        )}

                        <button
                          onClick={handleUpdateEntity}
                          disabled={entitySaving || !editTitle.trim()}
                          className={btnPrimary + ' w-full'}
                        >
                          {entitySaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                          {entitySaving ? 'Kaydediliyor...' : 'Kaydet'}
                        </button>
                      </div>
                    </div>

                    {/* Members section */}
                    <div className={`${card} p-6`}>
                      <div className="flex items-center gap-3 mb-5">
                        <div className="w-11 h-11 rounded-xl bg-violet-500 flex items-center justify-center shadow-lg">
                          <Users className="w-5 h-5 text-white" />
                        </div>
                        <div>
                          <h2 className="text-[15px] font-semibold text-white">Üyeler</h2>
                          <p className="text-[13px] text-slate-500">{selectedEntity.title}</p>
                        </div>
                      </div>

                      {membersLoading && (
                        <div className="flex items-center justify-center py-8">
                          <Loader2 className="w-5 h-5 animate-spin text-indigo-400" />
                        </div>
                      )}

                      {!membersLoading && members.length === 0 && (
                        <div className="rounded-xl bg-white/[0.03] border border-white/[0.06] p-6 text-center">
                          <Users className="w-8 h-8 text-slate-600 mx-auto mb-2" />
                          <p className="text-[13px] text-slate-500">Henüz üye yok</p>
                        </div>
                      )}

                      {!membersLoading && members.length > 0 && (
                        <div className="space-y-2">
                          {members.map((member) => (
                            <div
                              key={member.telegramUserId}
                              className="flex items-center justify-between rounded-xl bg-white/[0.03] border border-white/[0.06] p-3"
                            >
                              <div className="flex items-center gap-3">
                                <div className="w-8 h-8 rounded-lg bg-white/[0.06] flex items-center justify-center">
                                  <span className="text-[12px] font-semibold text-slate-400">
                                    {member.name.charAt(0).toUpperCase()}
                                  </span>
                                </div>
                                <div>
                                  <p className="text-[13px] font-medium text-slate-200">
                                    {member.name}
                                    {member.username && <span className="text-slate-500 ml-1">@{member.username}</span>}
                                  </p>
                                  {member.joinedAt && (
                                    <p className="text-[11px] text-slate-600">
                                      Katılım: {new Date(member.joinedAt).toLocaleDateString('tr-TR')}
                                    </p>
                                  )}
                                </div>
                              </div>
                              <span className={`text-[11px] px-2 py-0.5 rounded-md font-medium ${
                                member.role === 'admin'
                                  ? 'bg-amber-500/20 text-amber-400'
                                  : 'bg-white/[0.06] text-slate-400'
                              }`}>
                                {member.role === 'admin' ? 'Yönetici' : 'Üye'}
                              </span>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          )}
        </motion.div>
      )}

      {/* Content Publishing section */}
      {activeSection === 'publish' && (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-5">

          {/* Not connected warning */}
          {!isConnected && (
            <div className="rounded-2xl border border-amber-500/20 bg-amber-500/5 p-5">
              <div className="flex items-start gap-3">
                <div className="w-10 h-10 rounded-xl bg-amber-500/20 flex items-center justify-center shrink-0">
                  <AlertTriangle className="w-5 h-5 text-amber-400" />
                </div>
                <div className="flex-1">
                  <h3 className="text-[14px] font-semibold text-amber-300 mb-1">Önce userbot oturumu başlatın</h3>
                  <p className="text-[13px] text-amber-400/80">
                    İçerik yayınlamak için önce Oturum sekmesinden userbot bağlantısını kurun.
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Publish form card */}
          <div className={`${card} p-6`}>
            <div className="flex items-center gap-3 mb-5">
              <div className="w-11 h-11 rounded-xl bg-indigo-500 flex items-center justify-center shadow-lg">
                <Send className="w-5 h-5 text-white" />
              </div>
              <div>
                <h2 className="text-[15px] font-semibold text-white">İçerik Yayınla</h2>
                <p className="text-[13px] text-slate-500">Seçilen gruba veya kanala içerik gönderin</p>
              </div>
            </div>

            {/* Publish message banner */}
            <AnimatePresence>
              {publishMsg && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  exit={{ opacity: 0, height: 0 }}
                  className={`mb-4 rounded-xl px-4 py-3 text-[13px] font-medium ${
                    publishMsg.type === 'success'
                      ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
                      : 'bg-red-500/10 text-red-400 border border-red-500/20'
                  }`}
                >
                  <div className="flex items-center gap-2">
                    {publishMsg.type === 'success' ? <CheckCircle2 className="w-4 h-4 shrink-0" /> : <XCircle className="w-4 h-4 shrink-0" />}
                    <span className="flex-1">{publishMsg.text}</span>
                  </div>
                  {publishRetryFn && publishMsg.type === 'error' && (
                    <button
                      onClick={publishRetryFn}
                      className="mt-2 flex items-center gap-1.5 rounded-lg bg-red-500/20 px-3 py-1.5 text-[12px] font-medium text-red-300 hover:bg-red-500/30 transition-all cursor-pointer"
                    >
                      <RefreshCw className="w-3 h-3" />
                      Yeniden Dene
                    </button>
                  )}
                </motion.div>
              )}
            </AnimatePresence>

            <div className="space-y-4">
              {/* Target entity selection */}
              <div>
                <label className="block text-[12px] font-medium text-slate-400 mb-2">Hedef Grup / Kanal *</label>
                {entitiesLoading ? (
                  <div className="flex items-center gap-2 py-3">
                    <Loader2 className="w-4 h-4 animate-spin text-indigo-400" />
                    <span className="text-[13px] text-slate-500">Yükleniyor...</span>
                  </div>
                ) : entities.length === 0 ? (
                  <div className="rounded-xl bg-white/[0.03] border border-white/[0.06] p-4 text-center">
                    <p className="text-[13px] text-slate-500">Henüz grup veya kanal yok.</p>
                    <p className="text-[11px] text-slate-600 mt-1">Gruplar & Kanallar sekmesinden oluşturabilirsiniz.</p>
                  </div>
                ) : (
                  <select
                    value={publishEntityId}
                    onChange={(e) => setPublishEntityId(e.target.value)}
                    className={inputCls}
                    disabled={!isConnected}
                  >
                    <option value="">Seçiniz...</option>
                    {entities.map((entity) => (
                      <option key={entity.id} value={entity.id}>
                        {entity.title} — {entity.type === 'channel' ? 'Kanal' : entity.type === 'supergroup' ? 'Süper Grup' : 'Grup'}{entity.isVip ? ' ⭐ VIP' : ''}
                      </option>
                    ))}
                  </select>
                )}
              </div>

              {/* VIP Stars paywall badge */}
              {(() => {
                const selectedPublishEntity = entities.find(e => e.id === publishEntityId);
                if (selectedPublishEntity?.isVip) {
                  return (
                    <motion.div
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: 'auto' }}
                      className="flex items-center gap-2 rounded-xl bg-amber-500/10 border border-amber-500/20 px-4 py-3"
                    >
                      <Star className="w-4 h-4 text-amber-400 shrink-0" />
                      <div className="flex-1">
                        <span className="text-[13px] font-medium text-amber-300">Stars Paywall Aktif</span>
                        <p className="text-[11px] text-amber-400/70 mt-0.5">
                          Bu VIP kanala yayınlanan içerik Stars paywall arkasında gösterilecektir
                          {selectedPublishEntity.starPrice ? ` (${selectedPublishEntity.starPrice} Stars)` : ''}.
                        </p>
                      </div>
                      <span className="flex items-center gap-1 px-2 py-1 rounded-lg bg-amber-500/20 text-[11px] font-semibold text-amber-400 shrink-0">
                        <Star className="w-3 h-3" />
                        {selectedPublishEntity.starPrice ?? 0} Stars
                      </span>
                    </motion.div>
                  );
                }
                return null;
              })()}

              {/* Text content */}
              <div>
                <label className="block text-[12px] font-medium text-slate-400 mb-2">Mesaj Metni</label>
                <textarea
                  value={publishText}
                  onChange={(e) => setPublishText(e.target.value)}
                  placeholder="Yayınlanacak mesaj metnini girin..."
                  rows={5}
                  className={inputCls + ' resize-none'}
                  disabled={!isConnected}
                />
              </div>

              {/* Image URL input */}
              <div>
                <label className="block text-[12px] font-medium text-slate-400 mb-2">Görsel URL (isteğe bağlı)</label>
                <input
                  type="text"
                  value={publishImageUrl}
                  onChange={(e) => setPublishImageUrl(e.target.value)}
                  placeholder="https://... veya aşağıdan mevcut görsel seçin"
                  className={inputCls}
                  disabled={!isConnected}
                />
              </div>

              {/* Image preview */}
              {publishImageUrl.trim() && (
                <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-3">
                  <p className="text-[11px] font-medium text-slate-500 uppercase tracking-wider mb-2">Önizleme</p>
                  <img
                    src={publishImageUrl}
                    alt="Önizleme"
                    className="max-h-48 rounded-lg object-contain"
                    onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
                  />
                </motion.div>
              )}

              {/* Select from existing character images */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <label className="block text-[12px] font-medium text-slate-400">Mevcut Görsellerden Seç</label>
                  <button
                    onClick={loadCharacterImages}
                    disabled={imagesLoading}
                    className="text-[11px] text-indigo-400 hover:text-indigo-300 transition-colors cursor-pointer flex items-center gap-1"
                  >
                    <RefreshCw className={`w-3 h-3 ${imagesLoading ? 'animate-spin' : ''}`} />
                    Yenile
                  </button>
                </div>

                {imagesLoading && (
                  <div className="flex items-center gap-2 py-3">
                    <Loader2 className="w-4 h-4 animate-spin text-indigo-400" />
                    <span className="text-[13px] text-slate-500">Görseller yükleniyor...</span>
                  </div>
                )}

                {!imagesLoading && characterImages.length === 0 && (
                  <div className="rounded-xl bg-white/[0.03] border border-white/[0.06] p-4 text-center">
                    <Image className="w-6 h-6 text-slate-600 mx-auto mb-1" />
                    <p className="text-[12px] text-slate-500">Karakter için üretilmiş görsel bulunamadı.</p>
                  </div>
                )}

                {!imagesLoading && characterImages.length > 0 && (
                  <div className="grid grid-cols-4 sm:grid-cols-6 gap-2">
                    {characterImages.map((img) => {
                      const imgUrl = img.url || img.path || '';
                      const isSelected = publishImageUrl === imgUrl;
                      return (
                        <button
                          key={img.id}
                          onClick={() => setPublishImageUrl(isSelected ? '' : imgUrl)}
                          className={`relative aspect-square rounded-lg overflow-hidden border-2 transition-all cursor-pointer ${
                            isSelected
                              ? 'border-indigo-500 ring-2 ring-indigo-500/30'
                              : 'border-white/[0.06] hover:border-white/[0.15]'
                          }`}
                          disabled={!isConnected}
                        >
                          <img
                            src={imgUrl}
                            alt="Karakter görseli"
                            className="w-full h-full object-cover"
                            onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
                          />
                          {isSelected && (
                            <div className="absolute inset-0 bg-indigo-500/20 flex items-center justify-center">
                              <CheckCircle2 className="w-5 h-5 text-white" />
                            </div>
                          )}
                        </button>
                      );
                    })}
                  </div>
                )}
              </div>

              {/* Stars Amount for Paid Media — only for channels */}
              {(() => {
                const selEntity = entities.find(e => e.id === publishEntityId);
                const isChannel = selEntity?.type === 'channel';
                return (
                  <div>
                    <label className="block text-[12px] font-medium text-slate-400 mb-2">⭐ Stars Miktarı (Ücretli İçerik)</label>
                    <input
                      type="number"
                      min="1"
                      max="25000"
                      placeholder="Boş bırakırsan ücretsiz gönderilir"
                      value={publishStarAmount}
                      onChange={(e) => setPublishStarAmount(e.target.value ? Number(e.target.value) : '')}
                      className={inputCls}
                      disabled={!isConnected || !isChannel}
                    />
                    <p className="text-[11px] text-slate-600 mt-1">
                      {isChannel
                        ? '1-25000 arası bir değer gir. Görsel Stars ile kilitli olarak gönderilir.'
                        : '⚠️ Stars ile kilitli içerik sadece kanallarda desteklenir, gruplarda kullanılamaz.'}
                    </p>
                  </div>
                );
              })()}

              {/* Publish button */}
              <button
                onClick={handlePublish}
                disabled={publishSubmitting || !publishEntityId || (!publishText.trim() && !publishImageUrl.trim()) || !isConnected}
                className={btnPrimary + ' w-full'}
              >
                {publishSubmitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                {publishSubmitting ? 'Yayınlanıyor...' : 'Yayınla'}
              </button>
            </div>
          </div>
        </motion.div>
      )}

      {/* Gifts Catalog section */}
      {activeSection === 'gifts' && (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-5">

          {/* Not connected warning */}
          {!isConnected && (
            <div className="rounded-2xl border border-amber-500/20 bg-amber-500/5 p-5">
              <div className="flex items-start gap-3">
                <div className="w-10 h-10 rounded-xl bg-amber-500/20 flex items-center justify-center shrink-0">
                  <AlertTriangle className="w-5 h-5 text-amber-400" />
                </div>
                <div className="flex-1">
                  <h3 className="text-[14px] font-semibold text-amber-300 mb-1">Önce userbot oturumu başlatın</h3>
                  <p className="text-[13px] text-amber-400/80">
                    Hediye kataloğunu görüntülemek için önce Oturum sekmesinden userbot bağlantısını kurun.
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Header */}
          <div className={`${card} p-6`}>
            <div className="flex items-center justify-between mb-5">
              <div className="flex items-center gap-3">
                <div className="w-11 h-11 rounded-xl bg-gradient-to-br from-yellow-500 to-orange-500 flex items-center justify-center shadow-lg">
                  <Gift className="w-5 h-5 text-white" />
                </div>
                <div>
                  <h2 className="text-[15px] font-semibold text-white">Telegram Hediye Kataloğu</h2>
                  <p className="text-[13px] text-slate-500">
                    {starGifts.length > 0 ? `${starGifts.length} hediye mevcut` : 'Hediyeleri yükleyin'}
                  </p>
                </div>
              </div>
              <button
                onClick={loadStarGifts}
                disabled={giftsLoading || !isConnected}
                className={btnSecondary + ' shrink-0'}
              >
                <RefreshCw className={`w-4 h-4 ${giftsLoading ? 'animate-spin' : ''}`} />
                {giftsLoading ? 'Yükleniyor...' : 'Yenile'}
              </button>
            </div>

            {/* Filters & Sort */}
            {starGifts.length > 0 && (
              <div className="flex flex-wrap items-center gap-3 mb-5">
                <div className="flex gap-1 p-1 rounded-xl bg-white/[0.03] border border-white/[0.06]">
                  {([
                    { key: 'all', label: 'Tümü' },
                    { key: 'available', label: 'Mevcut' },
                    { key: 'limited', label: 'Sınırlı' },
                    { key: 'soldOut', label: 'Tükenmiş' },
                  ] as const).map((f) => (
                    <button
                      key={f.key}
                      onClick={() => setGiftFilter(f.key)}
                      className={`px-3 py-1.5 rounded-lg text-[12px] font-medium transition-all cursor-pointer ${
                        giftFilter === f.key
                          ? 'bg-white/[0.08] text-white'
                          : 'text-slate-500 hover:text-slate-300'
                      }`}
                    >
                      {f.label}
                    </button>
                  ))}
                </div>
                <div className="flex gap-1 p-1 rounded-xl bg-white/[0.03] border border-white/[0.06]">
                  <button
                    onClick={() => setGiftSort('price-asc')}
                    className={`px-3 py-1.5 rounded-lg text-[12px] font-medium transition-all cursor-pointer ${
                      giftSort === 'price-asc' ? 'bg-white/[0.08] text-white' : 'text-slate-500 hover:text-slate-300'
                    }`}
                  >
                    ⭐ Ucuzdan Pahalıya
                  </button>
                  <button
                    onClick={() => setGiftSort('price-desc')}
                    className={`px-3 py-1.5 rounded-lg text-[12px] font-medium transition-all cursor-pointer ${
                      giftSort === 'price-desc' ? 'bg-white/[0.08] text-white' : 'text-slate-500 hover:text-slate-300'
                    }`}
                  >
                    ⭐ Pahalıdan Ucuza
                  </button>
                </div>
              </div>
            )}

            {/* Error */}
            {giftsError && (
              <div className="mb-4 rounded-xl px-4 py-3 text-[13px] font-medium bg-red-500/10 text-red-400 border border-red-500/20">
                <div className="flex items-center gap-2">
                  <XCircle className="w-4 h-4 shrink-0" />
                  {giftsError}
                </div>
              </div>
            )}

            {/* Loading */}
            {giftsLoading && (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="w-6 h-6 animate-spin text-indigo-400" />
                <span className="ml-3 text-[13px] text-slate-500">Hediye kataloğu yükleniyor...</span>
              </div>
            )}

            {/* Empty state */}
            {!giftsLoading && giftsLoaded && starGifts.length === 0 && !giftsError && (
              <div className="text-center py-12">
                <Gift className="w-10 h-10 text-slate-600 mx-auto mb-3" />
                <p className="text-[14px] text-slate-400 mb-1">Hediye bulunamadı</p>
                <p className="text-[12px] text-slate-600">Telegram API'den hediye kataloğu alınamadı.</p>
              </div>
            )}

            {/* Gift grid */}
            {!giftsLoading && starGifts.length > 0 && (
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
                {starGifts
                  .filter((g) => {
                    if (giftFilter === 'available') return !g.soldOut;
                    if (giftFilter === 'limited') return g.limited && !g.soldOut;
                    if (giftFilter === 'soldOut') return g.soldOut;
                    return true;
                  })
                  .sort((a, b) => giftSort === 'price-asc' ? a.stars - b.stars : b.stars - a.stars)
                  .map((gift) => (
                    <motion.div
                      key={gift.id}
                      initial={{ opacity: 0, scale: 0.95 }}
                      animate={{ opacity: 1, scale: 1 }}
                      onClick={() => { if (!gift.soldOut) setSelectedGift(prev => prev?.id === gift.id ? null : gift); }}
                      className={`relative rounded-xl border p-4 text-center transition-all ${
                        gift.soldOut
                          ? 'border-white/[0.04] bg-white/[0.01] opacity-50'
                          : selectedGift?.id === gift.id
                            ? 'border-indigo-500/50 bg-indigo-500/5 cursor-pointer'
                            : 'border-white/[0.08] bg-white/[0.03] hover:border-indigo-500/30 hover:bg-white/[0.05] cursor-pointer'
                      }`}
                    >
                      {/* Selected checkmark */}
                      {selectedGift?.id === gift.id && (
                        <div className="absolute top-2 left-2">
                          <CheckCircle2 className="w-4 h-4 text-indigo-400" />
                        </div>
                      )}
                      {/* Badges */}
                      <div className="absolute top-2 right-2 flex flex-col gap-1">
                        {gift.limited && !gift.soldOut && (
                          <span className="px-1.5 py-0.5 rounded text-[9px] font-bold bg-amber-500/20 text-amber-400 uppercase">
                            Sınırlı
                          </span>
                        )}
                        {gift.soldOut && (
                          <span className="px-1.5 py-0.5 rounded text-[9px] font-bold bg-red-500/20 text-red-400 uppercase">
                            Tükenmiş
                          </span>
                        )}
                      </div>

                      {/* Gift icon placeholder */}
                      <div className="w-16 h-16 mx-auto mb-3 rounded-xl bg-gradient-to-br from-yellow-500/20 to-orange-500/20 flex items-center justify-center">
                        <span className="text-3xl">🎁</span>
                      </div>

                      {/* Price */}
                      <div className="flex items-center justify-center gap-1 mb-1">
                        <Star className="w-3.5 h-3.5 text-yellow-400 fill-yellow-400" />
                        <span className="text-[15px] font-bold text-white">{gift.stars.toLocaleString()}</span>
                      </div>

                      {/* Convert value */}
                      <p className="text-[11px] text-slate-500 mb-2">
                        Dönüştürme: ⭐ {gift.convertStars.toLocaleString()}
                      </p>

                      {/* Availability */}
                      {gift.limited && gift.availabilityTotal && (
                        <div className="mt-2">
                          <div className="w-full h-1.5 rounded-full bg-white/[0.06] overflow-hidden">
                            <div
                              className="h-full rounded-full bg-gradient-to-r from-indigo-500 to-violet-500 transition-all"
                              style={{
                                width: `${Math.max(2, ((gift.availabilityRemains ?? 0) / gift.availabilityTotal) * 100)}%`,
                              }}
                            />
                          </div>
                          <p className="text-[10px] text-slate-600 mt-1">
                            {(gift.availabilityRemains ?? 0).toLocaleString()} / {gift.availabilityTotal.toLocaleString()} kaldı
                          </p>
                        </div>
                      )}

                      {/* Gift ID */}
                      <p className="text-[9px] text-slate-700 mt-2 font-mono">#{gift.id}</p>
                    </motion.div>
                  ))}
              </div>
            )}

            {/* Send Gift Panel */}
            <AnimatePresence>
              {selectedGift && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  exit={{ opacity: 0, height: 0 }}
                  className="mt-5"
                >
                  <div className={`${card} p-6 border-indigo-500/20`}>
                    <div className="flex items-center gap-3 mb-5">
                      <div className="w-11 h-11 rounded-xl bg-gradient-to-br from-indigo-500 to-violet-600 flex items-center justify-center shadow-lg">
                        <Send className="w-5 h-5 text-white" />
                      </div>
                      <div className="flex-1">
                        <h3 className="text-[15px] font-semibold text-white">Hediye Gönder</h3>
                        <p className="text-[13px] text-slate-500">
                          Seçilen hediye: ⭐ {selectedGift.stars.toLocaleString()} Stars
                          {selectedGift.limited && <span className="ml-2 text-amber-400">(Sınırlı)</span>}
                        </p>
                      </div>
                      <button
                        onClick={() => { setSelectedGift(null); setGiftSendMsg(null); }}
                        className="p-2 rounded-lg text-slate-500 hover:text-slate-300 hover:bg-white/[0.04] transition-all cursor-pointer"
                      >
                        <XCircle className="w-5 h-5" />
                      </button>
                    </div>

                    {/* Send gift message banner */}
                    <AnimatePresence>
                      {giftSendMsg && (
                        <motion.div
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: 'auto' }}
                          exit={{ opacity: 0, height: 0 }}
                          className={`mb-4 rounded-xl px-4 py-3 text-[13px] font-medium ${
                            giftSendMsg.type === 'success'
                              ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
                              : 'bg-red-500/10 text-red-400 border border-red-500/20'
                          }`}
                        >
                          <div className="flex items-center gap-2">
                            {giftSendMsg.type === 'success' ? <CheckCircle2 className="w-4 h-4 shrink-0" /> : <XCircle className="w-4 h-4 shrink-0" />}
                            {giftSendMsg.text}
                          </div>
                        </motion.div>
                      )}
                    </AnimatePresence>

                    <div className="space-y-4">
                      <div>
                        <label className="block text-[12px] font-medium text-slate-400 mb-2">Alıcı *</label>
                        <input
                          type="text"
                          value={giftRecipient}
                          onChange={(e) => setGiftRecipient(e.target.value)}
                          placeholder="@username (önerilen) veya Telegram ID"
                          className={inputCls}
                          disabled={!isConnected}
                        />
                        <p className="text-[11px] text-slate-600 mt-1">
                          @username kullanmanız önerilir. Numeric ID sadece daha önce etkileşim olan kullanıcılar için çalışır.
                        </p>
                      </div>

                      <div>
                        <label className="block text-[12px] font-medium text-slate-400 mb-2">Mesaj (isteğe bağlı)</label>
                        <textarea
                          value={giftMessage}
                          onChange={(e) => setGiftMessage(e.target.value)}
                          placeholder="Hediye ile birlikte gönderilecek mesaj..."
                          rows={3}
                          className={inputCls + ' resize-none'}
                          disabled={!isConnected}
                        />
                      </div>

                      <div className="flex items-center gap-3 rounded-xl bg-amber-500/10 border border-amber-500/20 px-4 py-3">
                        <Star className="w-4 h-4 text-amber-400 shrink-0" />
                        <p className="text-[12px] text-amber-300">
                          Bu hediye hesabınızdan <span className="font-bold">⭐ {selectedGift.stars.toLocaleString()} Stars</span> düşecektir.
                        </p>
                      </div>

                      <button
                        onClick={handleSendGift}
                        disabled={giftSending || !giftRecipient.trim() || !isConnected}
                        className={btnPrimary + ' w-full'}
                      >
                        {giftSending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Gift className="w-4 h-4" />}
                        {giftSending ? 'Gönderiliyor...' : `Hediye Gönder (⭐ ${selectedGift.stars.toLocaleString()})`}
                      </button>
                    </div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            {/* Stats summary */}
            {!giftsLoading && starGifts.length > 0 && (
              <div className="mt-5 grid grid-cols-2 sm:grid-cols-4 gap-3">
                <div className="rounded-xl bg-white/[0.03] border border-white/[0.06] p-3 text-center">
                  <p className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Toplam</p>
                  <p className="text-[18px] font-bold text-white">{starGifts.length}</p>
                </div>
                <div className="rounded-xl bg-white/[0.03] border border-white/[0.06] p-3 text-center">
                  <p className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Mevcut</p>
                  <p className="text-[18px] font-bold text-emerald-400">{starGifts.filter(g => !g.soldOut).length}</p>
                </div>
                <div className="rounded-xl bg-white/[0.03] border border-white/[0.06] p-3 text-center">
                  <p className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Sınırlı</p>
                  <p className="text-[18px] font-bold text-amber-400">{starGifts.filter(g => g.limited && !g.soldOut).length}</p>
                </div>
                <div className="rounded-xl bg-white/[0.03] border border-white/[0.06] p-3 text-center">
                  <p className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Fiyat Aralığı</p>
                  <p className="text-[14px] font-bold text-white">
                    ⭐ {Math.min(...starGifts.map(g => g.stars)).toLocaleString()} - {Math.max(...starGifts.map(g => g.stars)).toLocaleString()}
                  </p>
                </div>
              </div>
            )}
          </div>
        </motion.div>
      )}
    </div>
  );
};

export default TelegramManagement;
