// hub-components.jsx — Shared constants, algorithms, SpiderChart, RevealAnimation

const ATTRS = [
  { key: 'hiz',      label: 'Hız',      icon: '⚡' },
  { key: 'sut',      label: 'Şut',      icon: '🎯' },
  { key: 'pas',      label: 'Pas',      icon: '🔀' },
  { key: 'dripling', label: 'Dripling', icon: '🌀' },
  { key: 'defans',   label: 'Defans',   icon: '🛡' },
  { key: 'fizik',    label: 'Fizik',    icon: '💪' },
];

const POSITIONS = ['KALECİ', 'DEFANS', 'ORTA SAHA', 'KANAT', 'FORVET'];

const POS_SHORT = { 'KALECİ':'GK', 'DEFANS':'DEF', 'ORTA SAHA':'MID', 'KANAT':'WNG', 'FORVET':'FWD' };

const DEFAULT_SCORES = { hiz:5, sut:5, pas:5, dripling:5, defans:5, fizik:5 };

function calcOverall(scores) {
  if (!scores) return 0;
  return parseFloat((ATTRS.reduce((s, a) => s + (scores[a.key] || 0), 0) / ATTRS.length).toFixed(1));
}

function getTitle(scores) {
  const { hiz, sut, pas, dripling, defans, fizik } = scores;
  const avg = calcOverall(scores);
  if (hiz >= 8.5 && dripling >= 8)  return { title:'FİŞEK',    sub:'Lightning Winger',   color:'#FFD700' };
  if (defans >= 8.5 && fizik >= 8)  return { title:'TANK',      sub:'Defensive Wall',      color:'#CC6600' };
  if (pas >= 8.5 && hiz >= 7)       return { title:'MAESTRO',   sub:'Playmaker',           color:'#9B59B6' };
  if (sut >= 8.5 && hiz >= 7)       return { title:'AVCI',      sub:'Clinical Finisher',   color:'#E74C3C' };
  if (avg >= 8)                      return { title:'EFSANE',    sub:'Complete Player',     color:'#39FF14' };
  if (fizik >= 8.5)                  return { title:'DUVAR',     sub:'Physical Beast',      color:'#7F8C8D' };
  if (hiz >= 8.5)                    return { title:'FIRTINA',   sub:'Speed Demon',         color:'#3498DB' };
  if (pas >= 8)                      return { title:'VİZYONER',  sub:'Vision Master',       color:'#1ABC9C' };
  if (avg >= 7)                      return { title:'KİLİT',     sub:'Key Player',          color:'#F39C12' };
  if (avg >= 5.5)                    return { title:'KAPTAN',    sub:'Solid Performer',     color:'#BDC3C7' };
  return                                    { title:'TOPAR',     sub:'Room to Grow',        color:'#555' };
}

// ─── SPIDER CHART ────────────────────────────────────────────────────
function SpiderChart({ scores, size = 200, animated = false, accentColor = '#39FF14' }) {
  const cx = size/2, cy = size/2, r = size*0.36, n = ATTRS.length;
  const polar = (val, i, rad) => {
    const a = (Math.PI*2*i/n) - Math.PI/2;
    const d = (val/10)*rad;
    return { x: cx + d*Math.cos(a), y: cy + d*Math.sin(a) };
  };
  const polyPts = (vals, rad) => ATTRS.map((a,i) => {
    const v = vals[a.key] ?? 5;
    const p = polar(v, i, rad);
    return `${p.x},${p.y}`;
  }).join(' ');

  return (
    <svg width={size} height={size} style={{ overflow:'visible' }}>
      {[2,4,6,8,10].map(lvl => (
        <polygon key={lvl} points={polyPts(Object.fromEntries(ATTRS.map(a=>[a.key,lvl])), r)}
          fill="none" stroke={lvl===10?'#333':'#1e1e1e'} strokeWidth={lvl===10?1:0.5} />
      ))}
      {ATTRS.map((a,i) => { const p=polar(10,i,r); return <line key={a.key} x1={cx} y1={cy} x2={p.x} y2={p.y} stroke="#252525" strokeWidth="1"/>; })}
      <polygon points={polyPts(scores, r)}
        fill={`${accentColor}20`} stroke={accentColor} strokeWidth="2"
        style={animated ? {filter:`drop-shadow(0 0 6px ${accentColor}80)`} : {}} />
      {ATTRS.map((a,i) => {
        const p = polar(scores[a.key]??5, i, r);
        return <circle key={a.key} cx={p.x} cy={p.y} r="4" fill={accentColor}
          style={{filter:`drop-shadow(0 0 4px ${accentColor})`}} />;
      })}
      {ATTRS.map((a,i) => {
        const p = polar(12, i, r);
        const dx = p.x-cx;
        return <text key={a.key} x={p.x} y={p.y}
          textAnchor={Math.abs(dx)<4?'middle':dx>0?'start':'end'} dominantBaseline="middle"
          fontSize="9" fontFamily="'Space Grotesk',sans-serif" fontWeight="600" fill="#666" letterSpacing="0.5">
          {a.label.toUpperCase()}
        </text>;
      })}
    </svg>
  );
}

// ─── MERGE REVEAL ────────────────────────────────────────────────────
function RevealAnimation({ player, votes, onDone }) {
  const [phase, setPhase] = React.useState('orbs');
  React.useEffect(() => {
    const t1 = setTimeout(() => setPhase('flash'), 2000);
    const t2 = setTimeout(() => setPhase('card'), 2700);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);

  const avg = ATTRS.reduce((acc,a) => ({
    ...acc, [a.key]: votes.reduce((s,v)=>s+(v[a.key]||0),0)/votes.length
  }), {});
  const titleData = getTitle(avg);
  const overall = calcOverall(avg);

  if (phase === 'orbs') {
    return (
      <div style={{display:'flex',alignItems:'center',justifyContent:'center',minHeight:'60vh',position:'relative'}}>
        <div style={{position:'relative',width:260,height:260,display:'flex',alignItems:'center',justifyContent:'center'}}>
          <div style={{position:'absolute',width:70,height:70,borderRadius:'50%',
            background:'radial-gradient(circle,rgba(57,255,20,0.4) 0%,transparent 70%)',
            animation:'pulse 0.8s infinite'}}/>
          {votes.map((v,i) => {
            const ang = (Math.PI*2*i/votes.length) - Math.PI/2;
            const rad = 90 + (i%3)*20;
            const ox = Math.cos(ang)*rad, oy = Math.sin(ang)*rad;
            return (
              <div key={i} style={{
                position:'absolute',width:40,height:40,borderRadius:'50%',
                background:'radial-gradient(circle,rgba(57,255,20,0.8),rgba(57,255,20,0.2))',
                border:'1px solid rgba(57,255,20,0.6)',
                display:'flex',alignItems:'center',justifyContent:'center',
                animation:`orbMerge 1.8s ease-in forwards`,
                animationDelay:`${i*0.1}s`,
              }}
              data-ox={`${ox}px`} data-oy={`${oy}px`}
              ref={el => { if(el){ el.style.setProperty('--ox',`${ox}px`); el.style.setProperty('--oy',`${oy}px`); }}}
              >
                <span style={{fontFamily:'var(--mono)',fontSize:10,fontWeight:700,color:'#000'}}>
                  {calcOverall(v).toFixed(1)}
                </span>
              </div>
            );
          })}
          <span style={{fontFamily:'var(--mono)',fontSize:11,color:'var(--green)',letterSpacing:2,zIndex:10,animation:'blink 0.5s infinite'}}>BİRLEŞİYOR</span>
        </div>
      </div>
    );
  }

  if (phase === 'flash') {
    return <div style={{position:'fixed',inset:0,background:'#39FF14',display:'flex',alignItems:'center',justifyContent:'center',zIndex:200}}>
      <span style={{fontFamily:'var(--mono)',fontSize:14,letterSpacing:4,color:'#000'}}>HESAPLANIYOR</span>
    </div>;
  }

  // Card
  return (
    <div style={{animation:'cardReveal 0.9s cubic-bezier(0.34,1.56,0.64,1) forwards'}}>
      <div style={{background:'var(--bg2)',border:`2px solid ${titleData.color}`,borderRadius:8,
        boxShadow:`0 0 50px ${titleData.color}40`,overflow:'hidden'}}>
        <div style={{background:`linear-gradient(135deg,${titleData.color}22,transparent)`,padding:'20px 20px 14px',borderBottom:'1px solid var(--border)'}}>
          <div style={{fontFamily:'var(--mono)',fontSize:9,letterSpacing:3,color:'var(--muted)',marginBottom:6}}>OYUNCU KARTI · HALIŞAHA HUB</div>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start'}}>
            <div>
              <div style={{fontSize:22,fontWeight:700}}>{player.name}</div>
              <div style={{color:'var(--muted)',fontSize:12,marginTop:2}}>{(player.positions||[player.position]).filter(Boolean).join(' · ')}</div>
            </div>
            <div style={{textAlign:'right'}}>
              <div style={{fontFamily:'var(--mono)',fontSize:36,fontWeight:700,color:overall>=8?'var(--green)':overall>=6?'#f0c040':'#ff6666',lineHeight:1}}>{overall}</div>
              <div style={{fontFamily:'var(--mono)',fontSize:9,color:'var(--muted)',letterSpacing:1}}>{votes.length} OY</div>
            </div>
          </div>
        </div>
        <div style={{padding:'12px 20px',background:`${titleData.color}15`,borderBottom:'1px solid var(--border)'}}>
          <div style={{fontFamily:'var(--mono)',fontSize:9,letterSpacing:3,color:'var(--muted)',marginBottom:3}}>UNVAN</div>
          <div style={{fontFamily:'var(--mono)',fontSize:24,fontWeight:700,letterSpacing:4,color:titleData.color}}>{titleData.title}</div>
          <div style={{fontSize:11,color:'var(--muted)'}}>{titleData.sub}</div>
        </div>
        <div style={{display:'flex',justifyContent:'center',padding:'16px 0 4px'}}>
          <SpiderChart scores={avg} size={200} animated accentColor={titleData.color}/>
        </div>
        <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:1,background:'var(--border)',margin:'0 0 1px'}}>
          {ATTRS.map(a => (
            <div key={a.key} style={{background:'var(--bg2)',padding:'10px 14px'}}>
              <div style={{fontFamily:'var(--mono)',fontSize:8,color:'var(--muted)',letterSpacing:1,marginBottom:3}}>{a.label.toUpperCase()}</div>
              <div style={{fontFamily:'var(--mono)',fontSize:20,fontWeight:700,color:avg[a.key]>=8?titleData.color:'var(--text)'}}>{avg[a.key].toFixed(1)}</div>
            </div>
          ))}
        </div>
        <div style={{padding:'10px 20px',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
          <span style={{fontFamily:'var(--mono)',fontSize:9,color:'var(--muted)',letterSpacing:1}}>{new Date().toLocaleDateString('tr-TR')} · {votes.length} KATILIMCI</span>
        </div>
      </div>
      <button onClick={onDone} style={{width:'100%',marginTop:12,padding:12,background:'transparent',
        border:'1px solid var(--border2)',color:'var(--muted)',borderRadius:4,cursor:'pointer',
        fontFamily:'var(--mono)',fontSize:11,letterSpacing:3}}>
        KARTA KAYDET ✓
      </button>
    </div>
  );
}

// ─── VOTER SCREEN ────────────────────────────────────────────────────
function VoterScreen({ player, onSubmit, votingOpen }) {
  const [scores, setScores] = React.useState({...DEFAULT_SCORES});
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

  const handleSubmit = async () => {
    if (submitting||submitted) return;
    setSubmitting(true);
    await new Promise(r=>setTimeout(r,700));
    onSubmit(scores);
    setSubmitted(true); setSubmitting(false);
  };

  if (!votingOpen) return (
    <div style={{display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',minHeight:'60vh',gap:12}}>
      <div style={{fontFamily:'var(--mono)',color:'var(--red)',fontSize:16,letterSpacing:2}}>OYLAMA KAPALI</div>
      <div style={{color:'var(--muted)',fontSize:13}}>Bu link geçersiz veya sona erdi.</div>
    </div>
  );

  if (submitted) return (
    <div style={{display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',minHeight:'60vh',gap:16,animation:'fadeIn 0.5s ease'}}>
      <div style={{fontSize:48}}>✅</div>
      <div style={{fontFamily:'var(--mono)',color:'var(--green)',fontSize:16,letterSpacing:2}}>OY KAYDEDİLDİ</div>
      <div style={{color:'var(--muted)',fontSize:13,textAlign:'center'}}>Admin sonuçları açıkladığında<br/>oyuncu kartı oluşturulacak.</div>
      <div style={{display:'flex',gap:8,alignItems:'center'}}>
        <div style={{width:7,height:7,borderRadius:'50%',background:'var(--green)',animation:'blink 1.5s infinite'}}/>
        <span style={{fontFamily:'var(--mono)',color:'var(--muted)',fontSize:11,letterSpacing:1}}>BEKLE...</span>
      </div>
    </div>
  );

  const avg = Object.values(scores).reduce((a,b)=>a+b,0)/6;

  return (
    <div>
      <div style={{display:'flex',alignItems:'center',gap:12,padding:'16px 0 20px',borderBottom:'1px solid var(--border)'}}>
        <div style={{width:44,height:44,borderRadius:8,background:'var(--green-dim)',border:'1px solid rgba(57,255,20,0.3)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:20}}>⚽</div>
        <div>
          <div style={{fontFamily:'var(--mono)',color:'var(--green)',fontSize:9,letterSpacing:3,marginBottom:2}}>OYUNCU DEĞERLENDİRMESİ</div>
          <div style={{fontSize:18,fontWeight:700}}>{player.name}</div>
          <div style={{color:'var(--muted)',fontSize:11}}>{(player.positions||[player.position]).filter(Boolean).join(' · ')}</div>
        </div>
      </div>
      <div style={{display:'flex',flexDirection:'column',alignItems:'center',padding:'20px 0 8px'}}>
        <SpiderChart scores={scores} size={200} animated/>
        <div style={{fontFamily:'var(--mono)',color:'var(--muted)',fontSize:10,marginTop:6,letterSpacing:1}}>
          ORT: <span style={{color:'var(--green)'}}>{avg.toFixed(1)}</span>
        </div>
      </div>
      <div style={{display:'flex',flexDirection:'column',gap:18,padding:'12px 0'}}>
        {ATTRS.map(attr => {
          const val = scores[attr.key];
          const pct = ((val-1)/9)*100;
          return (
            <div key={attr.key}>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:8}}>
                <span style={{fontSize:12,fontWeight:600,letterSpacing:0.5}}>{attr.icon} {attr.label.toUpperCase()}</span>
                <span style={{fontFamily:'var(--mono)',color:'var(--green)',fontSize:18,fontWeight:700}}>{val}</span>
              </div>
              <div style={{position:'relative',height:4,background:'var(--border2)',borderRadius:2}}>
                <div style={{position:'absolute',inset:0,right:`${100-pct}%`,background:'var(--green)',borderRadius:2,boxShadow:'0 0 6px rgba(57,255,20,0.5)',transition:'right 0.05s'}}/>
              </div>
              <input type="range" min={1} max={10} step={1} value={val}
                onChange={e=>setScores(s=>({...s,[attr.key]:parseInt(e.target.value)}))}
                style={{width:'100%',marginTop:-4,opacity:0,cursor:'pointer',height:20}}/>
            </div>
          );
        })}
      </div>
      <button onClick={handleSubmit} disabled={submitting} style={{
        width:'100%',padding:14,marginTop:8,
        background:submitting?'var(--border2)':'var(--green)',
        color:'#000',border:'none',borderRadius:4,cursor:'pointer',
        fontFamily:'var(--mono)',fontWeight:700,fontSize:13,letterSpacing:3,
        boxShadow:submitting?'none':'0 0 20px rgba(57,255,20,0.3)',
      }}>
        {submitting?'KAYDEDİLİYOR...':'ONAYLA VE GÖNDER'}
      </button>
    </div>
  );
}

Object.assign(window, { ATTRS, POSITIONS, POS_SHORT, DEFAULT_SCORES, calcOverall, getTitle, SpiderChart, RevealAnimation, VoterScreen });
