// ============================================
// GUILD CREATION WIZARD V2 - Ultimate Premium Experience
// With Perks, Events, Achievements & More Gamification
// ============================================

const { useState, useEffect, useRef } = React;

// ============================================
// CONSTANTS
// ============================================
const GUILD_CREATION_COST = 10000; // 100 coins in cents

const GUILD_CATEGORIES = [
  { id: 'competitive', name: 'Competitive', desc: 'Rankings & guild wars', icon: 'trophy', bonus: '+10% War XP' },
  { id: 'social', name: 'Social', desc: 'Fun & friendship focused', icon: 'users', bonus: '+5 Max Members' },
  { id: 'trading', name: 'Trading', desc: 'Economy & strategies', icon: 'coins', bonus: '+5% Treasury Bonus' },
  { id: 'highroller', name: 'High Roller', desc: 'Big bets, big wins', icon: 'diamond', bonus: 'VIP Perks Unlocked' },
];

// Extended color palette with text color for contrast
const GUILD_COLORS = [
  { color: '#5bffb2', name: 'Emerald', textColor: '#000' },
  { color: '#8b5cf6', name: 'Royal Purple', textColor: '#fff' },
  { color: '#f59e0b', name: 'Gold', textColor: '#000' },
  { color: '#ef4444', name: 'Crimson', textColor: '#fff' },
  { color: '#3b82f6', name: 'Sapphire', textColor: '#fff' },
  { color: '#ec4899', name: 'Hot Pink', textColor: '#fff' },
  { color: '#14b8a6', name: 'Teal', textColor: '#000' },
  { color: '#f97316', name: 'Orange', textColor: '#000' },
  { color: '#6366f1', name: 'Indigo', textColor: '#fff' },
  { color: '#84cc16', name: 'Lime', textColor: '#000' },
  { color: '#06b6d4', name: 'Cyan', textColor: '#000' },
  { color: '#a855f7', name: 'Violet', textColor: '#fff' },
  { color: '#f43f5e', name: 'Rose', textColor: '#fff' },
  { color: '#22c55e', name: 'Green', textColor: '#000' },
  { color: '#eab308', name: 'Yellow', textColor: '#000' },
  { color: '#0ea5e9', name: 'Sky Blue', textColor: '#000' },
];

// Gradient options for emblem backgrounds
const GUILD_GRADIENTS = [
  { id: 'emerald-purple', colors: ['#5bffb2', '#8b5cf6'], name: 'Emerald Purple', textColor: '#fff' },
  { id: 'fire-gold', colors: ['#ef4444', '#f59e0b'], name: 'Fire Gold', textColor: '#fff' },
  { id: 'ocean-deep', colors: ['#3b82f6', '#6366f1'], name: 'Ocean Deep', textColor: '#fff' },
  { id: 'sunset', colors: ['#f97316', '#ec4899'], name: 'Sunset', textColor: '#fff' },
  { id: 'aurora', colors: ['#14b8a6', '#5bffb2'], name: 'Aurora', textColor: '#000' },
  { id: 'royal', colors: ['#8b5cf6', '#ec4899'], name: 'Royal', textColor: '#fff' },
  { id: 'cyber', colors: ['#06b6d4', '#84cc16'], name: 'Cyber', textColor: '#000' },
  { id: 'blood-moon', colors: ['#ef4444', '#a855f7'], name: 'Blood Moon', textColor: '#fff' },
];

const GUILD_EMBLEMS = [
  { id: 'swords', icon: 'swords', name: 'Crossed Swords' },
  { id: 'shield', icon: 'shield', name: 'Shield' },
  { id: 'crown', icon: 'crown', name: 'Crown' },
  { id: 'star', icon: 'star', name: 'Star' },
  { id: 'diamond', icon: 'diamond', name: 'Diamond' },
  { id: 'fire', icon: 'fire', name: 'Fire' },
  { id: 'bolt', icon: 'bolt', name: 'Lightning' },
  { id: 'skull', icon: 'skull', name: 'Skull' },
  { id: 'trophy', icon: 'trophy', name: 'Trophy' },
  { id: 'target', icon: 'target', name: 'Target' },
  { id: 'rocket', icon: 'rocket', name: 'Rocket' },
  { id: 'sparkles', icon: 'sparkles', name: 'Sparkles' },
];

const STARTER_PERKS = [
  { id: 'treasury_boost', name: 'Treasury Boost', desc: 'Start with 500 coins in treasury', icon: 'coins', selected: true },
  { id: 'recruitment_banner', name: 'Recruitment Banner', desc: 'Featured on guild listings for 24h', icon: 'megaphone', selected: false },
  { id: 'war_ready', name: 'War Ready', desc: 'Skip cooldown for first guild war', icon: 'swords', selected: false },
  { id: 'xp_boost', name: 'XP Boost', desc: '+25% guild XP for 7 days', icon: 'sparkles', selected: false },
];

const EVENT_TEMPLATES = [
  { id: 'war_night', name: 'War Night', desc: 'Coordinate guild wars together', icon: 'swords', time: 'Weekly' },
  { id: 'jackpot_party', name: 'Jackpot Party', desc: 'Group jackpot sessions', icon: 'trophy', time: 'Daily' },
  { id: 'trading_hour', name: 'Trading Hour', desc: 'Share tips & strategies', icon: 'coins', time: 'Weekly' },
  { id: 'custom', name: 'Custom Event', desc: 'Create your own event', icon: 'calendar', time: 'Custom' },
];

const WIZARD_STEPS = [
  { id: 'basics', title: 'Foundation', subtitle: 'Name your guild', icon: 'flag' },
  { id: 'identity', title: 'Identity', subtitle: 'Colors & emblem', icon: 'palette' },
  { id: 'category', title: 'Category', subtitle: 'Choose your focus', icon: 'target' },
  { id: 'story', title: 'Story', subtitle: 'Tell your tale', icon: 'scroll' },
  { id: 'rules', title: 'Laws', subtitle: 'Set the rules', icon: 'gavel' },
  { id: 'perks', title: 'Perks', subtitle: 'Starter bonuses', icon: 'gift' },
  { id: 'event', title: 'First Event', subtitle: 'Plan your launch', icon: 'calendar' },
  { id: 'review', title: 'Launch', subtitle: 'Create your guild', icon: 'rocket' },
];

const ACHIEVEMENTS_PREVIEW = [
  { name: 'Guild Founded', desc: 'Create your first guild', unlocked: true },
  { name: 'First Blood', desc: 'Win your first guild war', unlocked: false },
  { name: 'Full House', desc: 'Reach 10 members', unlocked: false },
  { name: 'War Machine', desc: 'Win 10 guild wars', unlocked: false },
  { name: 'Treasure Hoard', desc: 'Accumulate 10,000 in treasury', unlocked: false },
  { name: 'Legendary', desc: 'Reach guild level 10', unlocked: false },
];

// ============================================
// SVG ICONS
// ============================================
const Icons = {
  trophy: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg>,
  users: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>,
  coins: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="8" cy="8" r="6"/><path d="M18.09 10.37A6 6 0 1 1 10.34 18"/><path d="M7 6h1v4"/></svg>,
  star: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>,
  check: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="20 6 9 17 4 12"/></svg>,
  x: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  chevronLeft: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="15 18 9 12 15 6"/></svg>,
  chevronRight: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="9 18 15 12 9 6"/></svg>,
  shield: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>,
  crown: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m2 4 3 12h14l3-12-6 7-4-7-4 7-6-7zm3 16h14"/></svg>,
  diamond: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z"/></svg>,
  swords: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="14.5 17.5 3 6 3 3 6 3 17.5 14.5"/><line x1="13" y1="19" x2="19" y2="13"/><line x1="16" y1="16" x2="20" y2="20"/><line x1="19" y1="21" x2="21" y2="19"/><polyline points="14.5 6.5 18 3 21 3 21 6 17.5 9.5"/><line x1="5" y1="14" x2="9" y2="18"/><line x1="7" y1="17" x2="4" y2="20"/><line x1="3" y1="19" x2="5" y2="21"/></svg>,
  fire: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/></svg>,
  bolt: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>,
  skull: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="9" cy="12" r="1"/><circle cx="15" cy="12" r="1"/><path d="M8 20v2h8v-2"/><path d="m12.5 17-.5-1-.5 1h1z"/><path d="M16 20a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20"/></svg>,
  scroll: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M8 21h12a2 2 0 0 0 2-2v-2H10v2a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v3h4"/><path d="M19 17V5a2 2 0 0 0-2-2H4"/></svg>,
  target: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>,
  sparkles: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/><path d="M5 3v4"/><path d="M19 17v4"/><path d="M3 5h4"/><path d="M17 19h4"/></svg>,
  calendar: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>,
  flag: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/></svg>,
  palette: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="13.5" cy="6.5" r=".5"/><circle cx="17.5" cy="10.5" r=".5"/><circle cx="8.5" cy="7.5" r=".5"/><circle cx="6.5" cy="12.5" r=".5"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.555C21.965 6.012 17.461 2 12 2z"/></svg>,
  gavel: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m14 13-7.5 7.5c-.83.83-2.17.83-3 0 0 0 0 0 0 0a2.12 2.12 0 0 1 0-3L11 10"/><path d="m16 16 6-6"/><path d="m8 8 6-6"/><path d="m9 7 8 8"/><path d="m21 11-8-8"/></svg>,
  gift: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="20 12 20 22 4 22 4 12"/><rect x="2" y="7" width="20" height="5"/><line x1="12" y1="22" x2="12" y2="7"/><path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/><path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/></svg>,
  rocket: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>,
  megaphone: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m3 11 18-5v12L3 13v-2z"/><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6"/></svg>,
  lock: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>,
  globe: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>,
  info: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>,
};

const getIcon = (name) => Icons[name] || Icons.star;

// Format coins
const formatCoins = (cents) => ((cents || 0) / 100).toLocaleString('en-US', { minimumFractionDigits: 2 });

// ============================================
// MAIN WIZARD COMPONENT
// ============================================
function GuildCreateWizard({ user, onClose, onSuccess }) {
  const [step, setStep] = useState(0);
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState('');
  const [showConfetti, setShowConfetti] = useState(false);
  
  // Form data
  const [formData, setFormData] = useState({
    name: '',
    tag: '',
    category: '',
    primaryColor: '#5bffb2',
    secondaryColor: '#8b5cf6',
    useGradient: false,
    selectedGradient: null,
    emblem: 'shield',
    description: '',
    mission: '',
    slogan: '',
    rules: '',
    welcomeMessage: 'Welcome to the guild! Check out our rules and introduce yourself.',
    isPublic: true,
    minLevel: 1,
    requireApproval: false,
    selectedPerks: ['treasury_boost'],
    firstEvent: null,
    eventName: '',
    eventDesc: '',
  });

  // Helper to get the current emblem background (color or gradient)
  const getEmblemBackground = () => {
    if (formData.useGradient && formData.selectedGradient) {
      const gradient = GUILD_GRADIENTS.find(g => g.id === formData.selectedGradient);
      if (gradient) {
        return `linear-gradient(135deg, ${gradient.colors[0]}, ${gradient.colors[1]})`;
      }
    }
    return formData.primaryColor;
  };

  // Helper to get text color for current selection
  const getEmblemTextColor = () => {
    if (formData.useGradient && formData.selectedGradient) {
      const gradient = GUILD_GRADIENTS.find(g => g.id === formData.selectedGradient);
      return gradient ? gradient.textColor : '#fff';
    }
    const color = GUILD_COLORS.find(c => c.color === formData.primaryColor);
    return color ? color.textColor : '#000';
  };

  const userBalance = user.balance || user.coins || 0;
  const canCreate = userBalance >= GUILD_CREATION_COST;

  const updateField = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    setError('');
  };

  const togglePerk = (perkId) => {
    setFormData(prev => {
      const perks = prev.selectedPerks.includes(perkId)
        ? prev.selectedPerks.filter(p => p !== perkId)
        : [...prev.selectedPerks, perkId].slice(0, 2); // Max 2 perks
      return { ...prev, selectedPerks: perks };
    });
  };

  const validateStep = () => {
    switch (step) {
      case 0: // Basics
        if (formData.name.length < 3 || formData.name.length > 32) {
          setError('Guild name must be 3-32 characters');
          return false;
        }
        if (formData.tag && (formData.tag.length < 2 || formData.tag.length > 6)) {
          setError('Guild tag must be 2-6 characters');
          return false;
        }
        break;
      case 2: // Category
        if (!formData.category) {
          setError('Please select a guild category');
          return false;
        }
        break;
      case 3: // Story
        if (formData.description.length < 20) {
          setError('Tell us more about your guild (at least 20 characters)');
          return false;
        }
        if (formData.mission.length < 10) {
          setError('Add a mission statement (at least 10 characters)');
          return false;
        }
        break;
      case 4: // Rules
        if (formData.rules.length < 10) {
          setError('Add at least one rule (10+ characters)');
          return false;
        }
        break;
    }
    return true;
  };

  const nextStep = () => {
    if (validateStep()) {
      setStep(prev => Math.min(prev + 1, WIZARD_STEPS.length - 1));
      setError('');
    }
  };

  const prevStep = () => {
    setStep(prev => Math.max(prev - 1, 0));
    setError('');
  };

  const createGuild = async () => {
    if (!canCreate) {
      setError(`Not enough coins! You need 100 coins, you have ${formatCoins(userBalance)}`);
      return;
    }

    setCreating(true);
    setError('');

    try {
      // Determine the color to send (gradient or solid)
      let colorToSend = formData.primaryColor;
      if (formData.useGradient && formData.selectedGradient) {
        const gradient = GUILD_GRADIENTS.find(g => g.id === formData.selectedGradient);
        if (gradient) {
          // Send as special format: gradient:color1,color2
          colorToSend = `gradient:${gradient.colors.join(',')}`;
        }
      }

      const res = await fetch('/api/guilds/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          name: formData.name,
          tag: formData.tag.toUpperCase() || undefined,
          description: formData.description,
          is_public: formData.isPublic,
          mission: formData.mission,
          rules: formData.rules,
          welcome_message: formData.welcomeMessage,
          primary_color: colorToSend,
          emblem: formData.emblem,
          category: formData.category,
          min_level: formData.minLevel,
          slogan: formData.slogan,
          require_approval: formData.requireApproval,
          starter_perks: formData.selectedPerks,
          first_event: formData.firstEvent ? {
            type: formData.firstEvent,
            name: formData.eventName,
            description: formData.eventDesc
          } : null,
        })
      });

      // Check if response is JSON
      const contentType = res.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        if (res.status === 401) {
          setError('Session expired. Please refresh and log in again.');
        } else if (res.status >= 500) {
          setError('Server error. Please try again later.');
        } else {
          setError(`Error ${res.status}: Failed to create guild.`);
        }
        setCreating(false);
        return;
      }

      const data = await res.json();

      if (res.ok) {
        setShowConfetti(true);
        setTimeout(() => {
          onSuccess(data.guild);
        }, 2000);
      } else {
        setError(data.detail || data.message || 'Failed to create guild');
      }
    } catch (err) {
      console.error('Guild creation error:', err);
      setError('Network error. Please check your connection and try again.');
    }

    setCreating(false);
  };

  // ============================================
  // STEP RENDERS
  // ============================================
  
  const renderBasicsStep = () => (
    <div className="wizard-step-content">
      <div className="wizard-step-hero">
        <div className="step-icon-large">{Icons.flag}</div>
        <h3>Choose Your Guild Name</h3>
        <p>Pick a name that strikes fear into enemies and inspires allies!</p>
      </div>

      <div className="wizard-form-group">
        <label>Guild Name <span className="required">*</span></label>
        <input
          type="text"
          className="wizard-input wizard-input-large"
          placeholder="e.g., Shadow Warriors, Diamond Elite..."
          value={formData.name}
          onChange={(e) => updateField('name', e.target.value)}
          maxLength={32}
        />
        <div className="input-meta">
          <span className="char-count">{formData.name.length}/32</span>
          {formData.name.length >= 3 && <span className="input-valid">{Icons.check} Valid</span>}
        </div>
      </div>

      <div className="wizard-form-group">
        <label>Guild Tag <span className="optional">(Optional)</span></label>
        <div className="tag-preview-row">
          <input
            type="text"
            className="wizard-input wizard-input-tag"
            placeholder="e.g., SW"
            value={formData.tag}
            onChange={(e) => updateField('tag', e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, ''))}
            maxLength={6}
          />
          <div className="tag-preview">
            <span>[{formData.tag || 'TAG'}]</span> {formData.name || 'Guild Name'}
          </div>
        </div>
        <span className="wizard-hint">2-6 characters. Auto-generated if left blank.</span>
      </div>

      <div className="wizard-tip">
        <div className="tip-icon">{Icons.info}</div>
        <div className="tip-content">
          <strong>Pro Tip:</strong> Memorable guild names often reference strength, unity, or legendary themes. 
          Your tag will appear before member names in chat!
        </div>
      </div>
    </div>
  );

  const renderIdentityStep = () => (
    <div className="wizard-step-content">
      <div className="wizard-step-hero">
        <div className="step-icon-large" style={{ background: getEmblemBackground(), color: getEmblemTextColor() }}>{getIcon(formData.emblem)}</div>
        <h3>Design Your Identity</h3>
        <p>Choose colors and an emblem that represents your guild</p>
      </div>

      {/* Color Mode Toggle */}
      <div className="wizard-form-group">
        <div className="color-mode-toggle">
          <button
            className={`mode-btn ${!formData.useGradient ? 'active' : ''}`}
            onClick={() => updateField('useGradient', false)}
          >
            <span className="mode-icon">🎨</span>
            <span>Solid Color</span>
          </button>
          <button
            className={`mode-btn ${formData.useGradient ? 'active' : ''}`}
            onClick={() => updateField('useGradient', true)}
          >
            <span className="mode-icon">✨</span>
            <span>Gradient Mix</span>
          </button>
        </div>
      </div>

      {!formData.useGradient ? (
        <div className="wizard-form-group">
          <label>Guild Color</label>
          <div className="color-grid color-grid-large">
            {GUILD_COLORS.map(({ color, name, textColor }) => (
              <button
                key={color}
                className={`color-option ${formData.primaryColor === color ? 'active' : ''}`}
                style={{ '--color': color, '--text-color': textColor }}
                onClick={() => updateField('primaryColor', color)}
                title={name}
              >
                <span className="color-name" style={{ color: textColor }}>{name}</span>
                {formData.primaryColor === color && <span className="color-check" style={{ color: textColor }}>{Icons.check}</span>}
              </button>
            ))}
          </div>
        </div>
      ) : (
        <div className="wizard-form-group">
          <label>Choose Gradient</label>
          <div className="gradient-grid">
            {GUILD_GRADIENTS.map(({ id, colors, name, textColor }) => (
              <button
                key={id}
                className={`gradient-option ${formData.selectedGradient === id ? 'active' : ''}`}
                style={{ 
                  background: `linear-gradient(135deg, ${colors[0]}, ${colors[1]})`,
                  '--text-color': textColor 
                }}
                onClick={() => updateField('selectedGradient', id)}
                title={name}
              >
                <span className="gradient-name" style={{ color: textColor }}>{name}</span>
                {formData.selectedGradient === id && <span className="gradient-check" style={{ color: textColor }}>{Icons.check}</span>}
              </button>
            ))}
          </div>
        </div>
      )}

      <div className="wizard-form-group">
        <label>Guild Emblem</label>
        <div className="emblem-grid">
          {GUILD_EMBLEMS.map(({ id, icon, name }) => (
            <button
              key={id}
              className={`emblem-option ${formData.emblem === icon ? 'active' : ''}`}
              style={{ '--color': formData.primaryColor }}
              onClick={() => updateField('emblem', icon)}
              title={name}
            >
              {getIcon(icon)}
            </button>
          ))}
        </div>
      </div>

      <div className="guild-preview-card" style={{ '--accent': formData.primaryColor }}>
        <div className="preview-emblem" style={{ background: getEmblemBackground(), color: getEmblemTextColor() }}>
          {getIcon(formData.emblem)}
        </div>
        <div className="preview-info">
          <h4 style={{ color: formData.primaryColor }}>[{formData.tag || 'TAG'}] {formData.name || 'Your Guild'}</h4>
          <p>This is how your guild will appear</p>
        </div>
      </div>
    </div>
  );

  const renderCategoryStep = () => (
    <div className="wizard-step-content">
      <div className="wizard-step-hero">
        <div className="step-icon-large">{Icons.target}</div>
        <h3>Choose Your Path</h3>
        <p>What will your guild focus on? Each category provides unique bonuses!</p>
      </div>

      <div className="category-grid">
        {GUILD_CATEGORIES.map(cat => (
          <button
            key={cat.id}
            className={`category-card ${formData.category === cat.id ? 'active' : ''}`}
            onClick={() => updateField('category', cat.id)}
          >
            <div className="category-icon">{getIcon(cat.icon)}</div>
            <h4>{cat.name}</h4>
            <p>{cat.desc}</p>
            <div className="category-bonus">
              <span className="bonus-tag">{cat.bonus}</span>
            </div>
            {formData.category === cat.id && (
              <div className="category-selected">{Icons.check}</div>
            )}
          </button>
        ))}
      </div>
    </div>
  );

  const renderStoryStep = () => (
    <div className="wizard-step-content">
      <div className="wizard-step-hero">
        <div className="step-icon-large">{Icons.scroll}</div>
        <h3>Tell Your Story</h3>
        <p>What makes your guild special? What are you fighting for?</p>
      </div>

      <div className="wizard-form-group">
        <label>Guild Slogan <span className="optional">(Optional)</span></label>
        <input
          type="text"
          className="wizard-input"
          placeholder="e.g., Victory or Nothing!"
          value={formData.slogan}
          onChange={(e) => updateField('slogan', e.target.value)}
          maxLength={50}
        />
      </div>

      <div className="wizard-form-group">
        <label>Mission Statement <span className="required">*</span></label>
        <input
          type="text"
          className="wizard-input"
          placeholder="e.g., To become the #1 guild in CoinRush"
          value={formData.mission}
          onChange={(e) => updateField('mission', e.target.value)}
          maxLength={100}
        />
        <span className="wizard-hint">What is your guild's primary goal?</span>
      </div>

      <div className="wizard-form-group">
        <label>Guild Description <span className="required">*</span></label>
        <textarea
          className="wizard-textarea"
          placeholder="Tell potential members about your guild. What makes you different? What kind of members are you looking for? What activities do you enjoy?"
          value={formData.description}
          onChange={(e) => updateField('description', e.target.value)}
          rows={5}
          maxLength={500}
        />
        <div className="input-meta">
          <span className="char-count">{formData.description.length}/500</span>
          {formData.description.length >= 20 && <span className="input-valid">{Icons.check}</span>}
        </div>
      </div>
    </div>
  );

  const renderRulesStep = () => (
    <div className="wizard-step-content">
      <div className="wizard-step-hero">
        <div className="step-icon-large">{Icons.gavel}</div>
        <h3>Establish Your Laws</h3>
        <p>Set clear expectations for your members</p>
      </div>

      <div className="wizard-form-group">
        <label>Guild Rules <span className="required">*</span></label>
        <textarea
          className="wizard-textarea"
          placeholder="1. Be respectful to all members&#10;2. Participate in guild wars when possible&#10;3. Donate to treasury weekly&#10;4. No sharing guild strategies outside"
          value={formData.rules}
          onChange={(e) => updateField('rules', e.target.value)}
          rows={6}
          maxLength={1000}
        />
        <span className="wizard-hint">Use line breaks to separate rules. Be clear and fair.</span>
      </div>

      <div className="wizard-form-group">
        <label>Welcome Message</label>
        <textarea
          className="wizard-textarea"
          placeholder="This message is shown to new members when they join..."
          value={formData.welcomeMessage}
          onChange={(e) => updateField('welcomeMessage', e.target.value)}
          rows={3}
          maxLength={300}
        />
      </div>

      <div className="wizard-row">
        <div className="wizard-toggle-group">
          <label>Guild Visibility</label>
          <div className="toggle-options">
            <button 
              className={`toggle-btn ${formData.isPublic ? 'active' : ''}`}
              onClick={() => updateField('isPublic', true)}
            >
              {Icons.globe} Public
            </button>
            <button 
              className={`toggle-btn ${!formData.isPublic ? 'active' : ''}`}
              onClick={() => updateField('isPublic', false)}
            >
              {Icons.lock} Private
            </button>
          </div>
        </div>

        <div className="wizard-toggle-group">
          <label>Require Approval</label>
          <div className="toggle-options">
            <button 
              className={`toggle-btn ${!formData.requireApproval ? 'active' : ''}`}
              onClick={() => updateField('requireApproval', false)}
            >
              Open Join
            </button>
            <button 
              className={`toggle-btn ${formData.requireApproval ? 'active' : ''}`}
              onClick={() => updateField('requireApproval', true)}
            >
              Approval Needed
            </button>
          </div>
        </div>
      </div>

      <div className="wizard-form-group">
        <label>Minimum Level Required</label>
        <div className="level-slider">
          <input
            type="range"
            min="1"
            max="50"
            value={formData.minLevel}
            onChange={(e) => updateField('minLevel', parseInt(e.target.value))}
          />
          <span className="level-value">Level {formData.minLevel}</span>
        </div>
      </div>
    </div>
  );

  const renderPerksStep = () => (
    <div className="wizard-step-content">
      <div className="wizard-step-hero">
        <div className="step-icon-large">{Icons.gift}</div>
        <h3>Choose Starter Perks</h3>
        <p>Select up to 2 perks to give your guild a head start!</p>
      </div>

      <div className="perks-grid">
        {STARTER_PERKS.map(perk => (
          <button
            key={perk.id}
            className={`perk-card ${formData.selectedPerks.includes(perk.id) ? 'active' : ''}`}
            onClick={() => togglePerk(perk.id)}
          >
            <div className="perk-icon">{getIcon(perk.icon)}</div>
            <h4>{perk.name}</h4>
            <p>{perk.desc}</p>
            {formData.selectedPerks.includes(perk.id) && (
              <div className="perk-selected">{Icons.check}</div>
            )}
          </button>
        ))}
      </div>

      <div className="perks-selected-count">
        Selected: {formData.selectedPerks.length}/2 perks
      </div>
    </div>
  );

  const renderEventStep = () => (
    <div className="wizard-step-content">
      <div className="wizard-step-hero">
        <div className="step-icon-large">{Icons.calendar}</div>
        <h3>Plan Your First Event</h3>
        <p>Launch your guild with a bang! Schedule your first community event.</p>
      </div>

      <div className="event-templates">
        {EVENT_TEMPLATES.map(event => (
          <button
            key={event.id}
            className={`event-card ${formData.firstEvent === event.id ? 'active' : ''}`}
            onClick={() => updateField('firstEvent', formData.firstEvent === event.id ? null : event.id)}
          >
            <div className="event-icon">{getIcon(event.icon)}</div>
            <div className="event-info">
              <h4>{event.name}</h4>
              <p>{event.desc}</p>
              <span className="event-time">{event.time}</span>
            </div>
            {formData.firstEvent === event.id && (
              <div className="event-selected">{Icons.check}</div>
            )}
          </button>
        ))}
      </div>

      {formData.firstEvent === 'custom' && (
        <div className="custom-event-form">
          <div className="wizard-form-group">
            <label>Event Name</label>
            <input
              type="text"
              className="wizard-input"
              placeholder="e.g., Grand Opening Party"
              value={formData.eventName}
              onChange={(e) => updateField('eventName', e.target.value)}
            />
          </div>
          <div className="wizard-form-group">
            <label>Event Description</label>
            <textarea
              className="wizard-textarea"
              placeholder="What will happen at this event?"
              value={formData.eventDesc}
              onChange={(e) => updateField('eventDesc', e.target.value)}
              rows={3}
            />
          </div>
        </div>
      )}

      <div className="wizard-tip">
        <div className="tip-icon">{Icons.sparkles}</div>
        <div className="tip-content">
          Events are optional but highly recommended! They help attract members and build community spirit.
        </div>
      </div>
    </div>
  );

  const renderReviewStep = () => {
    const selectedCat = GUILD_CATEGORIES.find(c => c.id === formData.category);
    
    return (
      <div className="wizard-step-content">
        <div className="wizard-step-hero launch-hero">
          <div className="launch-emblem" style={{ background: formData.primaryColor }}>
            {getIcon(formData.emblem)}
          </div>
          <h3>Ready for Launch!</h3>
          <p>Review your guild and prepare for greatness</p>
        </div>

        <div className="review-preview">
          <div className="review-header" style={{ '--accent': formData.primaryColor }}>
            <div className="review-emblem" style={{ background: formData.primaryColor }}>
              {getIcon(formData.emblem)}
            </div>
            <div className="review-title">
              <h2>[{formData.tag || formData.name.substring(0, 4).toUpperCase()}] {formData.name}</h2>
              {formData.slogan && <p className="review-slogan">"{formData.slogan}"</p>}
            </div>
          </div>

          <div className="review-grid">
            <div className="review-item">
              <label>Category</label>
              <span>{selectedCat?.name || 'General'}</span>
              {selectedCat?.bonus && <span className="review-bonus">{selectedCat.bonus}</span>}
            </div>
            <div className="review-item">
              <label>Visibility</label>
              <span>{formData.isPublic ? 'Public' : 'Private'}</span>
            </div>
            <div className="review-item">
              <label>Min Level</label>
              <span>Level {formData.minLevel}</span>
            </div>
            <div className="review-item">
              <label>Starter Perks</label>
              <span>{formData.selectedPerks.length} selected</span>
            </div>
          </div>

          <div className="review-section">
            <label>Mission</label>
            <p>{formData.mission}</p>
          </div>

          {formData.firstEvent && (
            <div className="review-section">
              <label>First Event</label>
              <p>{EVENT_TEMPLATES.find(e => e.id === formData.firstEvent)?.name || formData.eventName}</p>
            </div>
          )}
        </div>

        {/* Achievements Preview */}
        <div className="achievements-preview">
          <h4>{Icons.trophy} Achievements You'll Unlock</h4>
          <div className="achievements-grid">
            {ACHIEVEMENTS_PREVIEW.map((ach, i) => (
              <div key={i} className={`achievement-item ${ach.unlocked ? 'unlocked' : ''}`}>
                <div className="ach-icon">{ach.unlocked ? Icons.check : Icons.lock}</div>
                <div className="ach-info">
                  <span className="ach-name">{ach.name}</span>
                  <span className="ach-desc">{ach.desc}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Cost Box */}
        <div className="cost-box">
          <div className="cost-row">
            <span>Guild Creation Cost</span>
            <span className="cost-amount">100.00 Coins</span>
          </div>
          <div className="cost-row balance">
            <span>Your Balance</span>
            <span className={canCreate ? 'balance-ok' : 'balance-low'}>
              {formatCoins(userBalance)} Coins
            </span>
          </div>
          {!canCreate && (
            <div className="cost-warning">
              {Icons.x} Not enough coins to create a guild
            </div>
          )}
          {canCreate && (
            <div className="cost-success">
              {Icons.check} Ready to create your guild!
            </div>
          )}
        </div>
      </div>
    );
  };

  const renderStep = () => {
    switch (step) {
      case 0: return renderBasicsStep();
      case 1: return renderIdentityStep();
      case 2: return renderCategoryStep();
      case 3: return renderStoryStep();
      case 4: return renderRulesStep();
      case 5: return renderPerksStep();
      case 6: return renderEventStep();
      case 7: return renderReviewStep();
      default: return null;
    }
  };

  const isLastStep = step === WIZARD_STEPS.length - 1;
  const progress = ((step + 1) / WIZARD_STEPS.length) * 100;

  // ============================================
  // RENDER
  // ============================================
  return (
    <div className="wizard-overlay" onClick={onClose}>
      <div className="wizard-modal" onClick={e => e.stopPropagation()}>
        {/* Success Confetti */}
        {showConfetti && (
          <div className="wizard-success">
            <div className="success-content">
              <div className="success-icon" style={{ background: formData.primaryColor }}>
                {getIcon(formData.emblem)}
              </div>
              <h2>Guild Created!</h2>
              <p>Welcome to [{formData.tag || formData.name.substring(0, 4).toUpperCase()}] {formData.name}</p>
              <div className="confetti-container">
                {[...Array(50)].map((_, i) => (
                  <div key={i} className="confetti" style={{
                    '--delay': `${Math.random() * 3}s`,
                    '--x': `${Math.random() * 100}%`,
                    '--color': GUILD_COLORS[i % GUILD_COLORS.length].color
                  }} />
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Header */}
        <div className="wizard-header">
          <div className="wizard-brand">
            <div className="brand-icon">{Icons.shield}</div>
            <div className="brand-text">
              <h2>Create Your Guild</h2>
              <p>Step {step + 1} of {WIZARD_STEPS.length}: {WIZARD_STEPS[step].title}</p>
            </div>
          </div>
          <button className="wizard-close" onClick={onClose}>{Icons.x}</button>
        </div>

        {/* Progress Bar */}
        <div className="wizard-progress-bar">
          <div className="progress-fill" style={{ width: `${progress}%` }} />
          <div className="progress-steps">
            {WIZARD_STEPS.map((s, i) => (
              <div 
                key={s.id}
                className={`progress-step ${i < step ? 'completed' : ''} ${i === step ? 'active' : ''}`}
                onClick={() => i <= step && setStep(i)}
              >
                <div className="step-dot">
                  {i < step ? Icons.check : getIcon(s.icon)}
                </div>
                <span className="step-label">{s.title}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Content */}
        <div className="wizard-body">
          {error && (
            <div className="wizard-error">
              {Icons.x} {error}
            </div>
          )}
          {renderStep()}
        </div>

        {/* Footer */}
        <div className="wizard-footer">
          <button 
            className="wizard-btn secondary"
            onClick={prevStep}
            disabled={step === 0}
          >
            {Icons.chevronLeft} Back
          </button>

          {isLastStep ? (
            <button 
              className="wizard-btn create"
              onClick={createGuild}
              disabled={creating || !canCreate}
            >
              {creating ? (
                <>Creating...</>
              ) : (
                <>{Icons.rocket} Launch Guild (100 Coins)</>
              )}
            </button>
          ) : (
            <button 
              className="wizard-btn primary"
              onClick={nextStep}
            >
              Continue {Icons.chevronRight}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// Export
window.GuildCreateWizard = GuildCreateWizard;
