const CharacterScreen = ({ state, onAddSkill, onAllocatePoint }) => {
  const [addModal, setAddModal] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', abbr: '', color: '#f59e0b', description: '' });
  const PALETTE = ['#f59e0b','#ef4444','#a78bfa','#34d399','#60a5fa','#f472b6','#fb923c','#e879f9'];

  const { character, skills } = state;

  const handleAdd = () => {
    if (!form.name.trim()) return;
    onAddSkill({
      ...form, id: 's' + Date.now(),
      abbr: form.abbr || form.name.slice(0,3).toUpperCase(),
      xp: 0, xpToNext: 200, level: 1
    });
    setForm({ name: '', abbr: '', color: '#f59e0b', description: '' });
    setAddModal(false);
  };

  return (
    <div style={{ padding: '28px 28px', maxWidth: 920, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ marginBottom: 26 }}>
        <div style={{ fontFamily: "'Exo 2',sans-serif", fontSize: 11, letterSpacing: 2.5, color: '#3a3a3a', textTransform: 'uppercase', marginBottom: 5 }}>キャラクター</div>
        <h1 style={{ margin: 0, fontFamily: "'Exo 2',sans-serif", fontSize: 26, fontWeight: 800, color: '#f0f0f0' }}>スキルツリー</h1>
      </div>

      {/* Character summary banner */}
      <div style={{
        background: 'linear-gradient(140deg, #0f0e0a 0%, #100e07 60%, #0a0909 100%)',
        border: '1px solid rgba(245,158,11,.2)', borderRadius: 10, padding: 24,
        display: 'flex', alignItems: 'center', gap: 24, marginBottom: 28,
        flexWrap: 'wrap'
      }}>
        {/* Avatar */}
        <div style={{
          width: 80, height: 80, borderRadius: 10, background: '#080808',
          border: '2px solid rgba(245,158,11,.3)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          fontFamily: "'Exo 2',sans-serif", fontSize: 34, color: 'rgba(245,158,11,.4)'
        }}>{character.name[0]}</div>

        {/* Info */}
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 6, flexWrap: 'wrap' }}>
            <span style={{ fontFamily: "'Exo 2',sans-serif", fontWeight: 800, fontSize: 20, color: '#f0f0f0' }}>{character.name}</span>
            <LevelBadge level={character.level} size="sm" />
          </div>
          <div style={{ fontSize: 11, color: 'rgba(245,158,11,.55)', marginBottom: 14, letterSpacing: .5 }}>{character.title}</div>
          <XPBar xp={character.xp} xpToNext={character.xpToNext} showLabel={true} height={7} />
        </div>

        {/* Skill points */}
        <div style={{ textAlign: 'center', flexShrink: 0, padding: '12px 20px', background: '#0a0a0a', borderRadius: 8, border: '1px solid #1a1a1a' }}>
          <div style={{ fontFamily: "'Exo 2',sans-serif", fontSize: 36, fontWeight: 900, color: '#a78bfa', lineHeight: 1 }}>{character.skillPoints}</div>
          <div style={{ fontSize: 11, color: '#555', marginTop: 5 }}>スキルポイント</div>
          <div style={{ fontSize: 10, color: '#333', marginTop: 2 }}>未割り当て</div>
        </div>
      </div>

      {/* Section header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
        <div style={{ fontFamily: "'Exo 2',sans-serif", fontSize: 11, letterSpacing: 2, color: '#444', textTransform: 'uppercase' }}>
          スキル一覧 — {skills.length}
        </div>
        <Btn onClick={() => setAddModal(true)} variant="secondary" style={{ fontSize: 11, padding: '6px 14px' }}>+ スキル追加</Btn>
      </div>

      {/* Skill grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(195px,1fr))', gap: 14 }}>
        {skills.map(skill => (
          <div key={skill.id} style={{
            background: '#0e0e0e', borderRadius: 10,
            border: `1px solid ${skill.color}2e`,
            padding: 20, position: 'relative',
            transition: 'border-color .2s, box-shadow .2s'
          }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = `${skill.color}66`; e.currentTarget.style.boxShadow = `0 0 20px ${skill.color}18`; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = `${skill.color}2e`; e.currentTarget.style.boxShadow = 'none'; }}
          >
            {/* Header row */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
              <div style={{
                width: 42, height: 42, borderRadius: 7, flexShrink: 0,
                background: `${skill.color}15`, border: `1px solid ${skill.color}40`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: "'Exo 2',sans-serif", fontWeight: 900, fontSize: 12,
                color: skill.color, letterSpacing: 1
              }}>{skill.abbr}</div>
              <div style={{
                background: `${skill.color}20`, border: `1px solid ${skill.color}50`,
                borderRadius: 4, padding: '3px 9px',
                fontFamily: "'Exo 2',sans-serif", fontSize: 11, color: skill.color, fontWeight: 800
              }}>Lv.{skill.level}</div>
            </div>

            {/* Name & desc */}
            <div style={{ fontFamily: "'Exo 2',sans-serif", fontWeight: 700, fontSize: 14, color: '#e8e8e8', marginBottom: skill.description ? 4 : 12 }}>
              {skill.name}
            </div>
            {skill.description && (
              <div style={{ fontSize: 11, color: '#3a3a3a', marginBottom: 12, lineHeight: 1.5 }}>{skill.description}</div>
            )}

            <XPBar xp={skill.xp} xpToNext={skill.xpToNext} color={skill.color} height={4} showLabel={true} />

            {/* Allocate button (only if points available) */}
            {character.skillPoints > 0 && (
              <button onClick={() => onAllocatePoint(skill.id)} style={{
                marginTop: 14, width: '100%', padding: '8px 0',
                background: `${skill.color}12`,
                border: `1px solid ${skill.color}38`,
                borderRadius: 5, cursor: 'pointer',
                color: skill.color, fontSize: 11,
                fontFamily: "'Exo 2',sans-serif", fontWeight: 700, letterSpacing: .5,
                transition: 'background .15s'
              }}
                onMouseEnter={e => e.currentTarget.style.background = `${skill.color}25`}
                onMouseLeave={e => e.currentTarget.style.background = `${skill.color}12`}
              >+ ポイントを割り当て</button>
            )}
          </div>
        ))}

        {/* Add new skill card */}
        <div onClick={() => setAddModal(true)} style={{
          background: 'transparent', borderRadius: 10, border: '1px dashed #1e1e1e',
          padding: 20, cursor: 'pointer', minHeight: 160,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          transition: 'border-color .2s, color .2s', color: '#252525'
        }}
          onMouseEnter={e => { e.currentTarget.style.borderColor = 'rgba(245,158,11,.3)'; e.currentTarget.style.color = 'rgba(245,158,11,.4)'; }}
          onMouseLeave={e => { e.currentTarget.style.borderColor = '#1e1e1e'; e.currentTarget.style.color = '#252525'; }}
        >
          <div style={{ fontSize: 32, lineHeight: 1, marginBottom: 10 }}>+</div>
          <div style={{ fontSize: 12, fontFamily: "'Exo 2',sans-serif", letterSpacing: .5 }}>新しいスキル</div>
        </div>
      </div>

      {/* Add Skill Modal */}
      <Modal open={addModal} onClose={() => setAddModal(false)} title="新しいスキルを追加">
        <Field label="スキル名" value={form.name} onChange={v => setForm(p => ({...p, name: v}))} placeholder="例：ライティング、3Dモデリング..." />
        <Field label="略称（最大3文字）" value={form.abbr} onChange={v => setForm(p => ({...p, abbr: v.toUpperCase().slice(0,3)}))} placeholder="例：WRI" />
        <Field label="説明（任意）" value={form.description} onChange={v => setForm(p => ({...p, description: v}))} placeholder="このスキルの概要..." />

        <div style={{ marginBottom: 22 }}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 10, fontFamily: "'Exo 2',sans-serif", letterSpacing: .8, textTransform: 'uppercase' }}>カラー</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {PALETTE.map(c => (
              <div key={c} onClick={() => setForm(p => ({...p, color: c}))} style={{
                width: 30, height: 30, borderRadius: 5, background: c, cursor: 'pointer',
                border: form.color === c ? '2px solid #fff' : '2px solid transparent',
                boxShadow: form.color === c ? `0 0 10px ${c}` : 'none',
                transition: 'all .15s'
              }} />
            ))}
          </div>
        </div>

        {/* Preview */}
        <div style={{
          background: '#080808', border: `1px solid ${form.color}30`,
          borderRadius: 7, padding: '12px 16px', marginBottom: 20,
          display: 'flex', alignItems: 'center', gap: 12
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: 6,
            background: `${form.color}18`, border: `1px solid ${form.color}40`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: "'Exo 2',sans-serif", fontWeight: 900, fontSize: 11,
            color: form.color, letterSpacing: 1
          }}>{form.abbr || (form.name.slice(0,3).toUpperCase() || '---')}</div>
          <div>
            <div style={{ fontFamily: "'Exo 2',sans-serif", fontWeight: 700, fontSize: 13, color: '#e0e0e0' }}>
              {form.name || 'スキル名'}
            </div>
            <div style={{ fontSize: 10, color: '#444', marginTop: 2 }}>{form.description || '—'}</div>
          </div>
          <div style={{ marginLeft: 'auto', fontFamily: "'Exo 2',sans-serif", fontSize: 11, color: form.color, fontWeight: 700 }}>Lv.1</div>
        </div>

        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <Btn variant="ghost" onClick={() => setAddModal(false)}>キャンセル</Btn>
          <Btn onClick={handleAdd} disabled={!form.name.trim()}>スキル作成</Btn>
        </div>
      </Modal>
    </div>
  );
};

Object.assign(window, { CharacterScreen });
