import { useState } from 'react';
import type { FC } from 'react';
import { useNavigate } from 'react-router-dom';
import { characters } from '../api/client';
import { motion, AnimatePresence } from 'framer-motion';
import { CheckCircle2, ChevronRight, ChevronLeft } from 'lucide-react';

const MBTI_TYPES = [
  'INTJ', 'INTP', 'ENTJ', 'ENTP', 'INFJ', 'INFP', 'ENFJ', 'ENFP',
  'ISTJ', 'ISFJ', 'ESTJ', 'ESFJ', 'ISTP', 'ISFP', 'ESTP', 'ESFP',
];

const PRESET_STYLES = [
  { value: 'tipik_turk_kizi', label: 'Tipik Türk Kızı' }, { value: 'tripli', label: 'Tripli' },
  { value: 'alingan', label: 'Alıngan' }, { value: 'neseli', label: 'Neşeli' },
  { value: 'gizemli', label: 'Gizemli' }, { value: 'soguk', label: 'Soğuk' },
  { value: 'ilgili', label: 'İlgili' }, { value: 'oyuncu', label: 'Oyuncu' },
  { value: 'custom', label: 'Özel (Custom)' },
];

const REFERENCE_ANGLES = [
  'Master Portre (Ön yüz)', 'Sağ 45°', 'Sol 45°', 'Tam Profil (Yan)',
  'Kuş Bakışı (Üstten)', 'Tam Vücut', 'Arka Görünüm',
];

const STEP_TITLES = ['DNA Formu', 'Referans Görseller', 'Konuşma Profili', 'Telegram Kurulum'];

interface FormData {
  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; 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; 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 };
  conversationProfile: { style: string; customStyleDescription: string; formality: string; emoji_frequency: string; message_length: string; humor_level: string; flirtation_level: string };
  telegram: { bot_token: string };
}

const initialFormData: FormData = {
  identity: { name: '', age: 22, nationality: 'Türk', city: 'İstanbul', occupation: '', personality_tags: '', mbti: 'ENFP', backstory: '' },
  physicalMeasurements: { height_cm: 165, weight_kg: 55, body_type: 'slim', bust: 85, waist: 62, hips: 90 },
  skinMap: { base: '#f5d0a9', shadow: '#c8956c', highlight: '#fde8d0' },
  faceAnatomy: { eye_shape: 'almond', eye_color: '#6b4226', eyebrow_shape: 'arched', nose_type: 'straight', lip_shape: 'full', cheekbones: 'high', jawline: 'soft', distinctive_marks: '' },
  hairDNA: { style: 'wavy', length: 'long', texture: 'silky', root_color: '#2c1810', mid_color: '#4a2c1a', highlight_color: '#8b6914' },
  bodyBiometrics: { body_type_detail: 'mesomorph', posture: 'upright', skin_texture: 'smooth' },
  profileView: { best_angle: 'left 45', signature_pose: 'hand on hip' },
  expressionMotion: { default_expression: 'soft smile', smile_type: 'closed lip', gaze_style: 'direct' },
  makeupStyle: { philosophy: 'natural glam', skin_finish: 'dewy', primary: '#c44569', secondary: '#e17055', accent: '#fdcb6e' },
  fashionStyle: { aesthetic: 'casual chic', main_colors: ['#2d3436', '#dfe6e9', '#e17055'], signature_pieces: '' },
  technicalSettings: { camera_body: 'Sony A7IV', portrait_lens: '85mm f/1.4', full_body_lens: '35mm f/1.8', film_stock: 'Kodak Portra 400' },
  conversationProfile: { style: 'neseli', customStyleDescription: '', formality: 'casual', emoji_frequency: 'medium', message_length: 'medium', humor_level: 'subtle', flirtation_level: 'subtle' },
  telegram: { bot_token: '' },
};

const inputClass = 'w-full rounded-xl border border-white/[0.06] bg-white/[0.03] px-4 py-2.5 text-sm text-slate-100 placeholder-slate-500 outline-none transition-all focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/20 backdrop-blur-xl';
const selectClass = 'w-full rounded-xl border border-white/[0.06] bg-white/[0.03] px-4 py-2.5 text-sm text-slate-100 outline-none transition-all focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/20 backdrop-blur-xl';
const textareaClass = 'w-full rounded-xl border border-white/[0.06] bg-white/[0.03] px-4 py-2.5 text-sm text-slate-100 placeholder-slate-500 outline-none transition-all focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/20 min-h-[80px] resize-y backdrop-blur-xl';
const sectionClass = 'rounded-2xl border border-white/[0.06] bg-white/[0.03] backdrop-blur-xl p-6 mb-5';
const sectionTitleClass = 'bg-gradient-to-r from-indigo-400 to-violet-400 bg-clip-text text-transparent font-semibold text-base mb-5 pb-3 border-b border-white/[0.06]';

const stepVariants = {
  enter: (dir: number) => ({ x: dir > 0 ? 60 : -60, opacity: 0 }),
  center: { x: 0, opacity: 1 },
  exit: (dir: number) => ({ x: dir > 0 ? -60 : 60, opacity: 0 }),
};

const CharacterCreate: FC = () => {
  const navigate = useNavigate();
  const [step, setStep] = useState(1);
  const [direction, setDirection] = useState(1);
  const [form, setForm] = useState<FormData>(initialFormData);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  const updateIdentity = (key: string, value: string | number) => setForm(f => ({ ...f, identity: { ...f.identity, [key]: value } }));
  const updatePhysical = (key: string, value: string | number) => setForm(f => ({ ...f, physicalMeasurements: { ...f.physicalMeasurements, [key]: value } }));
  const updateSkin = (key: string, value: string) => setForm(f => ({ ...f, skinMap: { ...f.skinMap, [key]: value } }));
  const updateFace = (key: string, value: string) => setForm(f => ({ ...f, faceAnatomy: { ...f.faceAnatomy, [key]: value } }));
  const updateHair = (key: string, value: string) => setForm(f => ({ ...f, hairDNA: { ...f.hairDNA, [key]: value } }));
  const updateBody = (key: string, value: string) => setForm(f => ({ ...f, bodyBiometrics: { ...f.bodyBiometrics, [key]: value } }));
  const updateProfile = (key: string, value: string) => setForm(f => ({ ...f, profileView: { ...f.profileView, [key]: value } }));
  const updateExpression = (key: string, value: string) => setForm(f => ({ ...f, expressionMotion: { ...f.expressionMotion, [key]: value } }));
  const updateMakeup = (key: string, value: string) => setForm(f => ({ ...f, makeupStyle: { ...f.makeupStyle, [key]: value } }));
  const updateFashion = (key: string, value: string | string[]) => setForm(f => ({ ...f, fashionStyle: { ...f.fashionStyle, [key]: value } }));
  const updateTech = (key: string, value: string) => setForm(f => ({ ...f, technicalSettings: { ...f.technicalSettings, [key]: value } }));
  const updateConvo = (key: string, value: string) => setForm(f => ({ ...f, conversationProfile: { ...f.conversationProfile, [key]: value } }));
  const updateTelegram = (key: string, value: string) => setForm(f => ({ ...f, telegram: { ...f.telegram, [key]: value } }));

  const validateStep1 = (): boolean => {
    const errs: Record<string, string> = {};
    if (!form.identity.name.trim()) errs.name = 'Karakter adı zorunludur';
    setErrors(errs);
    return Object.keys(errs).length === 0;
  };

  const handleNext = () => { if (step === 1 && !validateStep1()) return; setDirection(1); setStep(s => Math.min(s + 1, 4)); };
  const handlePrev = () => { setDirection(-1); setStep(s => Math.max(s - 1, 1)); };

  const buildPayload = () => {
    const { identity, physicalMeasurements, skinMap, faceAnatomy, hairDNA, bodyBiometrics, profileView, expressionMotion, makeupStyle, fashionStyle, technicalSettings, conversationProfile, telegram } = form;
    return {
      identity: { ...identity, personality_tags: identity.personality_tags.split(',').map(t => t.trim()).filter(Boolean) },
      physicalMeasurements: { height_cm: physicalMeasurements.height_cm, weight_kg: physicalMeasurements.weight_kg, body_type: physicalMeasurements.body_type, measurements: { bust: physicalMeasurements.bust, waist: physicalMeasurements.waist, hips: physicalMeasurements.hips } },
      skinMap, faceAnatomy: { ...faceAnatomy, distinctive_marks: faceAnatomy.distinctive_marks.split(',').map(t => t.trim()).filter(Boolean) },
      hairDNA, bodyBiometrics, profileView, expressionMotion,
      makeupStyle: { philosophy: makeupStyle.philosophy, skin_finish: makeupStyle.skin_finish, colors: { primary: makeupStyle.primary, secondary: makeupStyle.secondary, accent: makeupStyle.accent } },
      fashionStyle: { aesthetic: fashionStyle.aesthetic, main_colors: fashionStyle.main_colors, signature_pieces: fashionStyle.signature_pieces.split(',').map(t => t.trim()).filter(Boolean) },
      technicalSettings,
      conversationProfile: { style: conversationProfile.style, customStyleDescription: conversationProfile.style === 'custom' ? conversationProfile.customStyleDescription : undefined, toneOfVoice: { formality: conversationProfile.formality, emoji_frequency: conversationProfile.emoji_frequency, message_length: conversationProfile.message_length, humor_level: conversationProfile.humor_level, flirtation_level: conversationProfile.flirtation_level } },
      botToken: telegram.bot_token || undefined,
    };
  };

  const handleSubmit = async () => {
    setSubmitting(true); setSubmitError(null);
    try {
      const payload = buildPayload();
      const { conversationProfile, botToken, ...dna } = payload;
      const res = await characters.create({ dna, profile: conversationProfile });
      const id = res.data?.data?.id ?? res.data?.id ?? res.data?.character?.id;
      navigate(id ? `/characters/${id}` : '/characters');
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : 'Karakter oluşturulurken bir hata oluştu.';
      setSubmitError(msg);
    } finally { setSubmitting(false); }
  };

  const renderField = (label: string, value: string | number, onChange: (v: string) => void, type = 'text', errorKey?: string) => (
    <div className="mb-3">
      <label className="block text-sm font-medium text-slate-400 mb-1.5">{label}</label>
      <input className={inputClass} type={type} value={value} onChange={e => onChange(e.target.value)} />
      {errorKey && errors[errorKey] && <div className="text-red-400 text-xs mt-1.5">{errors[errorKey]}</div>}
    </div>
  );

  const renderColor = (label: string, value: string, onChange: (v: string) => void) => (
    <div className="mb-3">
      <label className="block text-sm font-medium text-slate-400 mb-1.5">{label}</label>
      <div className="flex items-center gap-3">
        <input type="color" value={value} onChange={e => onChange(e.target.value)} className="h-10 w-14 cursor-pointer rounded-lg border border-white/[0.06] bg-transparent p-0.5" />
        <input className="w-28 rounded-xl border border-white/[0.06] bg-white/[0.03] px-3 py-2 text-sm text-slate-100 outline-none transition-all focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/20" value={value} onChange={e => onChange(e.target.value)} />
        <div className="h-8 w-8 rounded-lg shadow-inner" style={{ backgroundColor: value }} />
      </div>
    </div>
  );

  const renderSelect = (label: string, value: string, options: { value: string; label: string }[], onChange: (v: string) => void) => (
    <div className="mb-3">
      <label className="block text-sm font-medium text-slate-400 mb-1.5">{label}</label>
      <select className={selectClass} value={value} onChange={e => onChange(e.target.value)}>
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
    </div>
  );

  const renderTextarea = (label: string, value: string, onChange: (v: string) => void) => (
    <div className="mb-3">
      <label className="block text-sm font-medium text-slate-400 mb-1.5">{label}</label>
      <textarea className={textareaClass} value={value} onChange={e => onChange(e.target.value)} />
    </div>
  );

  const renderStep1 = () => (
    <>
      <div className={sectionClass}><div className={sectionTitleClass}>🪪 Temel Kimlik</div>
        <div className="grid grid-cols-2 gap-4">
          {renderField('İsim *', form.identity.name, v => updateIdentity('name', v), 'text', 'name')}
          {renderField('Yaş', form.identity.age, v => updateIdentity('age', parseInt(v) || 0), 'number')}
          {renderField('Milliyet', form.identity.nationality, v => updateIdentity('nationality', v))}
          {renderField('Şehir', form.identity.city, v => updateIdentity('city', v))}
          {renderField('Meslek', form.identity.occupation, v => updateIdentity('occupation', v))}
          {renderSelect('MBTI', form.identity.mbti, MBTI_TYPES.map(t => ({ value: t, label: t })), v => updateIdentity('mbti', v))}
        </div>
        {renderField('Kişilik Etiketleri (virgülle ayırın)', form.identity.personality_tags, v => updateIdentity('personality_tags', v))}
        {renderTextarea('Arka Hikaye', form.identity.backstory, v => updateIdentity('backstory', v))}
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>📏 Fiziksel Ölçüler</div>
        <div className="grid grid-cols-3 gap-4">
          {renderField('Boy (cm)', form.physicalMeasurements.height_cm, v => updatePhysical('height_cm', parseInt(v) || 0), 'number')}
          {renderField('Kilo (kg)', form.physicalMeasurements.weight_kg, v => updatePhysical('weight_kg', parseInt(v) || 0), 'number')}
          {renderField('Vücut Tipi', form.physicalMeasurements.body_type, v => updatePhysical('body_type', v))}
        </div>
        <div className="grid grid-cols-3 gap-4">
          {renderField('Göğüs (cm)', form.physicalMeasurements.bust, v => updatePhysical('bust', parseInt(v) || 0), 'number')}
          {renderField('Bel (cm)', form.physicalMeasurements.waist, v => updatePhysical('waist', parseInt(v) || 0), 'number')}
          {renderField('Kalça (cm)', form.physicalMeasurements.hips, v => updatePhysical('hips', parseInt(v) || 0), 'number')}
        </div>
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>🎨 Cilt Haritası</div>
        <div className="grid grid-cols-3 gap-4">
          {renderColor('Baz Renk', form.skinMap.base, v => updateSkin('base', v))}
          {renderColor('Gölge', form.skinMap.shadow, v => updateSkin('shadow', v))}
          {renderColor('Parlak', form.skinMap.highlight, v => updateSkin('highlight', v))}
        </div>
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>👤 Yüz Anatomisi</div>
        <div className="grid grid-cols-2 gap-4">
          {renderField('Göz Şekli', form.faceAnatomy.eye_shape, v => updateFace('eye_shape', v))}
          {renderColor('Göz Rengi', form.faceAnatomy.eye_color, v => updateFace('eye_color', v))}
          {renderField('Kaş Şekli', form.faceAnatomy.eyebrow_shape, v => updateFace('eyebrow_shape', v))}
          {renderField('Burun Tipi', form.faceAnatomy.nose_type, v => updateFace('nose_type', v))}
          {renderField('Dudak Şekli', form.faceAnatomy.lip_shape, v => updateFace('lip_shape', v))}
          {renderField('Elmacık Kemikleri', form.faceAnatomy.cheekbones, v => updateFace('cheekbones', v))}
          {renderField('Çene Hattı', form.faceAnatomy.jawline, v => updateFace('jawline', v))}
        </div>
        {renderField('Ayırt Edici İşaretler (virgülle ayırın)', form.faceAnatomy.distinctive_marks, v => updateFace('distinctive_marks', v))}
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>💇 Saç DNA</div>
        <div className="grid grid-cols-3 gap-4">
          {renderField('Stil', form.hairDNA.style, v => updateHair('style', v))}
          {renderField('Uzunluk', form.hairDNA.length, v => updateHair('length', v))}
          {renderField('Doku', form.hairDNA.texture, v => updateHair('texture', v))}
        </div>
        <div className="grid grid-cols-3 gap-4">
          {renderColor('Kök Rengi', form.hairDNA.root_color, v => updateHair('root_color', v))}
          {renderColor('Orta Renk', form.hairDNA.mid_color, v => updateHair('mid_color', v))}
          {renderColor('Parlak Renk', form.hairDNA.highlight_color, v => updateHair('highlight_color', v))}
        </div>
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>🏋️ Vücut Biyometrisi</div>
        <div className="grid grid-cols-3 gap-4">
          {renderField('Vücut Tipi Detay', form.bodyBiometrics.body_type_detail, v => updateBody('body_type_detail', v))}
          {renderField('Duruş', form.bodyBiometrics.posture, v => updateBody('posture', v))}
          {renderField('Cilt Dokusu', form.bodyBiometrics.skin_texture, v => updateBody('skin_texture', v))}
        </div>
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>📸 Profil Görünümü</div>
        <div className="grid grid-cols-2 gap-4">
          {renderField('En İyi Açı', form.profileView.best_angle, v => updateProfile('best_angle', v))}
          {renderField('İmza Pozu', form.profileView.signature_pose, v => updateProfile('signature_pose', v))}
        </div>
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>😊 İfade & Hareket</div>
        <div className="grid grid-cols-3 gap-4">
          {renderField('Varsayılan İfade', form.expressionMotion.default_expression, v => updateExpression('default_expression', v))}
          {renderField('Gülümseme Tipi', form.expressionMotion.smile_type, v => updateExpression('smile_type', v))}
          {renderField('Bakış Stili', form.expressionMotion.gaze_style, v => updateExpression('gaze_style', v))}
        </div>
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>💄 Makyaj Stili</div>
        <div className="grid grid-cols-2 gap-4">
          {renderField('Felsefe', form.makeupStyle.philosophy, v => updateMakeup('philosophy', v))}
          {renderField('Cilt Finişi', form.makeupStyle.skin_finish, v => updateMakeup('skin_finish', v))}
        </div>
        <div className="grid grid-cols-3 gap-4">
          {renderColor('Ana Renk', form.makeupStyle.primary, v => updateMakeup('primary', v))}
          {renderColor('İkincil Renk', form.makeupStyle.secondary, v => updateMakeup('secondary', v))}
          {renderColor('Aksan Renk', form.makeupStyle.accent, v => updateMakeup('accent', v))}
        </div>
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>👗 Moda Stili</div>
        {renderField('Estetik', form.fashionStyle.aesthetic, v => updateFashion('aesthetic', v))}
        <div className="mb-3">
          <label className="block text-sm font-medium text-slate-400 mb-1.5">Ana Renkler</label>
          <div className="flex gap-3 flex-wrap items-center">
            {form.fashionStyle.main_colors.map((c, i) => (
              <div key={i} className="flex items-center gap-2 rounded-xl border border-white/[0.06] bg-white/[0.03] p-2">
                <input type="color" value={c} onChange={e => { const updated = [...form.fashionStyle.main_colors]; updated[i] = e.target.value; updateFashion('main_colors', updated); }} className="h-8 w-10 cursor-pointer rounded-md border border-white/[0.06] bg-transparent p-0.5" />
                <button type="button" onClick={() => updateFashion('main_colors', form.fashionStyle.main_colors.filter((_, idx) => idx !== i))} className="flex h-6 w-6 items-center justify-center rounded-full bg-red-500/10 text-red-400 text-xs transition-colors hover:bg-red-500/20">×</button>
              </div>
            ))}
            <button type="button" onClick={() => updateFashion('main_colors', [...form.fashionStyle.main_colors, '#000000'])} className="rounded-xl border border-white/[0.06] bg-white/[0.03] px-4 py-2 text-xs font-medium text-slate-300 transition-all hover:bg-white/[0.06]">+ Renk Ekle</button>
          </div>
        </div>
        {renderField('İmza Parçaları (virgülle ayırın)', form.fashionStyle.signature_pieces, v => updateFashion('signature_pieces', v))}
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>📷 Teknik Ayarlar</div>
        <div className="grid grid-cols-2 gap-4">
          {renderField('Kamera Gövdesi', form.technicalSettings.camera_body, v => updateTech('camera_body', v))}
          {renderField('Portre Lensi', form.technicalSettings.portrait_lens, v => updateTech('portrait_lens', v))}
          {renderField('Tam Vücut Lensi', form.technicalSettings.full_body_lens, v => updateTech('full_body_lens', v))}
          {renderField('Film Stoku', form.technicalSettings.film_stock, v => updateTech('film_stock', v))}
        </div>
      </div>
    </>
  );

  const renderStep2 = () => (
    <div className={sectionClass}><div className={sectionTitleClass}>🖼️ Referans Görseller</div>
      <div className="mb-5 rounded-xl border border-indigo-500/20 bg-indigo-500/5 p-4 text-sm text-indigo-300">
        Karakter oluşturulduktan sonra, DNA bilgilerine göre 7 farklı açıdan referans görseller otomatik olarak üretilecektir.
      </div>
      <div className="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-4">
        {REFERENCE_ANGLES.map((angle, i) => (
          <motion.div key={i} whileHover={{ y: -2, scale: 1.03 }}
            className="group rounded-xl border border-white/[0.06] bg-white/[0.03] p-4 transition-all hover:border-indigo-500/20 hover:bg-indigo-500/5">
            <div className="mb-2 text-2xl">📐</div>
            <div className="text-sm font-medium text-slate-200">{i + 1}. {angle}</div>
          </motion.div>
        ))}
      </div>
    </div>
  );

  const renderStep3 = () => (
    <>
      <div className={sectionClass}><div className={sectionTitleClass}>💬 Konuşma Profili</div>
        <div className="mb-3">
          <label className="block text-sm font-medium text-slate-400 mb-2">Konuşma Tarzı</label>
          <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
            {PRESET_STYLES.map(ps => (
              <motion.div key={ps.value} whileHover={{ scale: 1.01 }} whileTap={{ scale: 0.99 }}
                className={`flex cursor-pointer items-center gap-3 rounded-xl border p-3 transition-all ${
                  form.conversationProfile.style === ps.value
                    ? 'border-indigo-500/50 bg-indigo-500/10 ring-1 ring-indigo-500/20'
                    : 'border-white/[0.06] bg-white/[0.03] hover:border-white/[0.1]'
                }`}
                onClick={() => updateConvo('style', ps.value)}>
                <input type="radio" name="convoStyle" checked={form.conversationProfile.style === ps.value} onChange={() => updateConvo('style', ps.value)} className="accent-indigo-500" />
                <span className="text-sm font-medium text-slate-200">{ps.label}</span>
              </motion.div>
            ))}
          </div>
        </div>
        {form.conversationProfile.style === 'custom' && renderTextarea('Özel Tarz Açıklaması', form.conversationProfile.customStyleDescription, v => updateConvo('customStyleDescription', v))}
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>🎛️ Ton Ayarları</div>
        <div className="grid grid-cols-2 gap-4">
          {renderSelect('Resmiyet', form.conversationProfile.formality, [{ value: 'casual', label: 'Rahat (Casual)' }, { value: 'semi-formal', label: 'Yarı Resmi' }], v => updateConvo('formality', v))}
          {renderSelect('Emoji Sıklığı', form.conversationProfile.emoji_frequency, [{ value: 'low', label: 'Düşük' }, { value: 'medium', label: 'Orta' }, { value: 'high', label: 'Yüksek' }], v => updateConvo('emoji_frequency', v))}
          {renderSelect('Mesaj Uzunluğu', form.conversationProfile.message_length, [{ value: 'short', label: 'Kısa' }, { value: 'medium', label: 'Orta' }, { value: 'long', label: 'Uzun' }], v => updateConvo('message_length', v))}
          {renderSelect('Mizah Seviyesi', form.conversationProfile.humor_level, [{ value: 'none', label: 'Yok' }, { value: 'subtle', label: 'Hafif' }, { value: 'frequent', label: 'Sık' }], v => updateConvo('humor_level', v))}
          {renderSelect('Flört Seviyesi', form.conversationProfile.flirtation_level, [{ value: 'none', label: 'Yok' }, { value: 'subtle', label: 'Hafif' }, { value: 'moderate', label: 'Orta' }, { value: 'high', label: 'Yüksek' }], v => updateConvo('flirtation_level', v))}
        </div>
      </div>
    </>
  );

  const renderStep4 = () => (
    <>
      <div className={sectionClass}><div className={sectionTitleClass}>📱 Telegram Hesap Kurulumu</div>
        <div className="mb-5 rounded-xl border border-indigo-500/20 bg-indigo-500/5 p-4 text-sm text-indigo-300">
          Karakter için kullanılacak Telegram hesabının telefon numarasını girin. Karakter oluşturulduktan sonra, karakter detay sayfasından giriş yapabilirsiniz.
        </div>
        <div className="mb-3">
          <label className="block text-sm font-medium text-slate-400 mb-1.5">Telefon Numarası (opsiyonel)</label>
          <input className={inputClass} type="tel" placeholder="+905551234567" value={form.telegram.bot_token} onChange={e => updateTelegram('bot_token', e.target.value)} />
          <p className="text-xs text-slate-500 mt-1.5">Uluslararası formatta girin. Giriş işlemi karakter oluşturulduktan sonra yapılacaktır.</p>
        </div>
      </div>
      <div className={sectionClass}><div className={sectionTitleClass}>🤖 Bot Token (Opsiyonel)</div>
        <div className="mb-5 rounded-xl border border-amber-500/20 bg-amber-500/5 p-4 text-sm text-amber-300">
          Stars ödemeleri ve kanal yönetimi için bir bot token'ı da ekleyebilirsiniz. Bu opsiyoneldir — ana mesajlaşma userbot üzerinden yapılır.
        </div>
      </div>
    </>
  );

  return (
    <div className="mx-auto max-w-4xl px-4 py-6">
      <motion.h1 initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}
        className="mb-2 text-2xl font-bold bg-gradient-to-r from-indigo-400 via-violet-400 to-purple-400 bg-clip-text text-transparent">
        Yeni Karakter Oluştur
      </motion.h1>

      {/* Step Indicator */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }} className="mb-8 mt-6">
        <div className="flex items-center justify-between">
          {[1, 2, 3, 4].map((s, i) => (
            <div key={s} className="flex flex-1 items-center">
              <div className="flex flex-col items-center gap-1.5">
                <motion.div whileHover={{ scale: 1.1 }}
                  className={`flex h-10 w-10 items-center justify-center rounded-full text-sm font-bold transition-all ${
                    s === step ? 'bg-gradient-to-br from-indigo-500 to-violet-500 text-white shadow-lg shadow-indigo-500/30'
                      : s < step ? 'bg-emerald-500 text-white shadow-lg shadow-emerald-500/20'
                        : 'border border-white/[0.06] bg-white/[0.03] text-slate-500'
                  }`}>
                  {s < step ? <CheckCircle2 size={18} /> : s}
                </motion.div>
                <span className={`text-xs font-medium ${s === step ? 'text-indigo-400' : s < step ? 'text-emerald-400' : 'text-slate-500'}`}>{STEP_TITLES[s - 1]}</span>
              </div>
              {i < 3 && <div className={`mx-2 h-px flex-1 ${s < step ? 'bg-emerald-500/50' : 'bg-white/[0.06]'}`} />}
            </div>
          ))}
        </div>
        <div className="mt-3 text-center text-sm text-slate-500">Adım {step}/4 — {STEP_TITLES[step - 1]}</div>
      </motion.div>

      {/* Step Content with AnimatePresence */}
      <AnimatePresence mode="wait" custom={direction}>
        <motion.div key={step} custom={direction} variants={stepVariants}
          initial="enter" animate="center" exit="exit"
          transition={{ duration: 0.3, ease: 'easeInOut' }}>
          {step === 1 && renderStep1()}
          {step === 2 && renderStep2()}
          {step === 3 && renderStep3()}
          {step === 4 && renderStep4()}
        </motion.div>
      </AnimatePresence>

      {/* Submit Error */}
      {submitError && <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}
        className="mt-3 rounded-xl border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-300">{submitError}</motion.div>}

      {/* Navigation */}
      <div className="mt-8 flex justify-between">
        <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} type="button"
          className={`flex items-center gap-2 rounded-xl border border-white/[0.06] bg-white/[0.03] px-5 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.06] ${step === 1 ? 'invisible' : ''}`}
          onClick={handlePrev}>
          <ChevronLeft size={16} /> Önceki
        </motion.button>
        {step < 4 ? (
          <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} type="button"
            className="flex items-center gap-2 rounded-xl bg-gradient-to-r from-indigo-500 to-violet-500 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-indigo-500/25"
            onClick={handleNext}>
            Sonraki <ChevronRight size={16} />
          </motion.button>
        ) : (
          <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} type="button"
            className={`rounded-xl bg-gradient-to-r from-emerald-500 to-teal-500 px-6 py-2.5 text-sm font-semibold text-white shadow-lg shadow-emerald-500/25 ${submitting ? 'opacity-50 cursor-not-allowed' : ''}`}
            disabled={submitting} onClick={handleSubmit}>
            {submitting ? 'Oluşturuluyor...' : 'Karakter Oluştur ✓'}
          </motion.button>
        )}
      </div>
    </div>
  );
};

export default CharacterCreate;