/* Rater Assignment screen — three-column layout with center network diagram */
const RaterScreen = () => {
  const employees = [
    { name: 'Aylin Demir', role: 'Sr. Product Designer', dept: 'Engineering', avatar: '#6B73F0', initials: 'AD', completion: 75, raterCount: 7, status: 'In progress' },
    { name: 'Mert Yılmaz', role: 'Engineering Manager', dept: 'Engineering', avatar: '#8B5CF6', initials: 'MY', completion: 62, raterCount: 9, status: 'In progress' },
    { name: 'Ceren Kaya', role: 'Backend Engineer', dept: 'Engineering', avatar: '#14B8A6', initials: 'CK', completion: 100, raterCount: 6, status: 'Complete' },
    { name: 'Burak Aslan', role: 'Data Scientist', dept: 'PMO / Digital Transformation', avatar: '#38BDF8', initials: 'BA', completion: 33, raterCount: 5, status: 'At risk' },
    { name: 'Selin Öztürk', role: 'Product Manager', dept: 'Engineering', avatar: '#F59E0B', initials: 'SÖ', completion: 88, raterCount: 8, status: 'In progress' },
    { name: 'Emre Şahin', role: 'Frontend Engineer', dept: 'Engineering', avatar: '#EF4444', initials: 'EŞ', completion: 50, raterCount: 6, status: 'In progress' },
    { name: 'Defne Aydın', role: 'HR Business Partner', dept: 'HR', avatar: '#6D28D9', initials: 'DA', completion: 100, raterCount: 7, status: 'Complete' },
    { name: 'Kerem Doğan', role: 'QA Lead', dept: 'Engineering', avatar: '#0D9488', initials: 'KD', completion: 14, raterCount: 3, status: 'At risk' },
  ];

  const [selected, setSelected] = React.useState(0);
  const emp = employees[selected];

  const raterGroups = [
    { name: 'Self',              icon: 'user', tint: 'tint-indigo', min: 1, assigned: 1, completed: 1, color: '#4F46E5' },
    { name: 'Manager',           icon: 'flag', tint: 'tint-violet', min: 1, assigned: 1, completed: 1, color: '#8B5CF6' },
    { name: 'Peer',              icon: 'users', tint: 'tint-sky', min: 4, assigned: emp.name === 'Burak Aslan' ? 3 : 5, completed: 3, color: '#38BDF8' },
    { name: 'Direct Report',     icon: 'team', tint: 'tint-mint', min: 3, assigned: emp.name === 'Kerem Doğan' ? 0 : 4, completed: 2, color: '#14B8A6' },
    { name: 'Internal Customer', icon: 'target', tint: 'tint-amber', min: 3, assigned: 4, completed: 1, color: '#F59E0B' },
    { name: 'External Customer', icon: 'globe', tint: 'tint-rose', min: 2, assigned: 0, completed: 0, color: '#EF4444' },
    { name: 'Matrix Manager',    icon: 'shield', tint: 'tint-slate', min: 0, assigned: 1, completed: 0, color: '#94A3B8' },
  ];

  const anonymityIssue = raterGroups.find(g => g.min > 0 && g.assigned > 0 && g.assigned < g.min);

  return (
    <div className="fade-in">
      <div className="page-header">
        <div>
          <h1>Rater Assignment</h1>
          <div className="subtitle">Define who evaluates whom — and keep every rater group above the anonymity threshold.</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-secondary"><Icon name="sparkle" size={15}/> Auto-suggest raters</button>
          <button className="btn btn-primary"><Icon name="check" size={15}/> Save Assignments</button>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '300px 1fr 360px', gap: 16, alignItems: 'start' }}>
        {/* Left: employee list */}
        <div className="card" style={{ overflow: 'hidden' }}>
          <div style={{ padding: 14, borderBottom: '1px solid var(--border)' }}>
            <div style={{ position: 'relative' }}>
              <Icon name="search" size={14} style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-400)' }}/>
              <input className="input" style={{ height: 34, padding: '0 12px 0 32px', fontSize: 12.5 }} placeholder="Search employees…"/>
            </div>
            <div style={{ fontSize: 11, color: 'var(--ink-500)', marginTop: 10, display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Evaluatees · {employees.length}</span>
              <button className="btn btn-ghost btn-sm" style={{ height: 22, padding: '0 6px', fontSize: 11 }}>Sort: Risk</button>
            </div>
          </div>
          <div style={{ maxHeight: 540, overflowY: 'auto' }}>
            {employees.map((e, i) => (
              <div key={i} onClick={() => setSelected(i)} style={{
                padding: '12px 14px',
                borderBottom: '1px solid var(--border)',
                background: selected === i ? 'var(--primary-50)' : 'transparent',
                borderLeft: selected === i ? '3px solid var(--primary-500)' : '3px solid transparent',
                display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer'
              }}>
                <Avatar name={e.name} color={e.avatar} initials={e.initials}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-900)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-500)' }}>{e.role}</div>
                  <div style={{ marginTop: 6 }}>
                    <Progress value={e.completion} tone="auto" height={4}/>
                  </div>
                </div>
                {e.status === 'At risk' && (
                  <div title="Anonymity risk" style={{ color: 'var(--warning-500)' }}>
                    <Icon name="warning" size={14}/>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Center: relationship visualization */}
        <div className="card" style={{ minHeight: 580 }}>
          <div className="card-header">
            <div>
              <h3>Rater network · {emp.name}</h3>
              <div className="desc">Live preview of who will be invited to evaluate this person.</div>
            </div>
            <Badge status={emp.status === 'Complete' ? 'Submitted' : emp.status === 'At risk' ? 'Overdue' : 'In progress'}/>
          </div>
          <div className="card-body" style={{ position: 'relative' }}>
            <RaterNetwork emp={emp} groups={raterGroups}/>

            {anonymityIssue && (
              <div className="alert alert-warning" style={{ marginTop: 16 }}>
                <Icon name="shield" size={16}/>
                <div>
                  <div className="alert-title">{anonymityIssue.name} group is below the anonymity threshold</div>
                  <div className="alert-body">
                    {anonymityIssue.assigned} of {anonymityIssue.min} required raters are assigned. Results for this rater group will be hidden in {emp.name.split(' ')[0]}'s individual report unless more raters are added.
                  </div>
                </div>
                <button className="btn btn-sm btn-primary">Add raters</button>
              </div>
            )}
          </div>
        </div>

        {/* Right: rater group details */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {raterGroups.map(g => {
            const ratio = g.min === 0 ? 1 : Math.min(1, g.assigned / g.min);
            const ok = g.min === 0 || g.assigned >= g.min;
            return (
              <div key={g.name} className="card" style={{ padding: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div className={`stat-icon ${g.tint}`} style={{ width: 34, height: 34, marginBottom: 0, flexShrink: 0 }}>
                    <Icon name={g.icon} size={15}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink-900)' }}>{g.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-500)' }}>
                      {g.assigned} / {g.min || '–'} raters {g.min > 0 ? `· min ${g.min}` : '· no minimum'}
                    </div>
                  </div>
                  <div className="btn btn-icon btn-sm btn-ghost" style={{ pointerEvents: 'none' }}>
                    {ok ? <Icon name="check" size={14} style={{ color: 'var(--success-500)' }}/> : <Icon name="warning" size={14} style={{ color: 'var(--warning-500)' }}/>}
                  </div>
                </div>
                <div style={{ marginTop: 10 }}>
                  <Progress value={g.completed / Math.max(g.assigned, 1) * 100} tone={ok ? 'success' : 'warning'} height={4}/>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 10.5, color: 'var(--ink-500)' }}>
                    <span>{g.completed} completed</span>
                    <span>Threshold: {g.min || '—'}</span>
                  </div>
                </div>
                {g.assigned > 0 && (
                  <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div className="avatar-stack">
                      {Array.from({ length: Math.min(g.assigned, 4) }).map((_, i) => (
                        <Avatar key={i} initials={['JL','RM','TK','SA','OP'][i]} color={['#6B73F0','#8B5CF6','#14B8A6','#F59E0B','#EF4444'][i]}/>
                      ))}
                    </div>
                    {g.assigned > 4 && <span style={{ fontSize: 11, color: 'var(--ink-500)', fontWeight: 600, marginLeft: 4 }}>+{g.assigned - 4}</span>}
                    <button className="btn btn-icon btn-sm btn-ghost" style={{ marginLeft: 'auto' }}><Icon name="plus" size={13}/></button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

/* Network diagram — radial arrangement */
const RaterNetwork = ({ emp, groups }) => {
  const W = 720, H = 440;
  const cx = W / 2, cy = H / 2;

  // Place groups in a circle around employee
  const positions = groups.map((g, i) => {
    const angle = (i / groups.length) * 2 * Math.PI - Math.PI / 2;
    const r = 165;
    return { x: cx + r * Math.cos(angle), y: cy + r * Math.sin(angle), g };
  });

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', maxHeight: 460 }}>
      <defs>
        <radialGradient id="centerGrad" cx="50%" cy="50%">
          <stop offset="0%" stopColor="#4F46E5" stopOpacity="0.18"/>
          <stop offset="100%" stopColor="#4F46E5" stopOpacity="0"/>
        </radialGradient>
      </defs>

      {/* glow */}
      <circle cx={cx} cy={cy} r={120} fill="url(#centerGrad)"/>

      {/* connections */}
      {positions.map((p, i) => {
        const ok = p.g.min === 0 || p.g.assigned >= p.g.min;
        return (
          <line key={i} x1={cx} y1={cy} x2={p.x} y2={p.y}
            stroke={ok ? p.g.color : '#F59E0B'}
            strokeWidth={p.g.assigned > 0 ? 1.6 : 1}
            strokeDasharray={p.g.assigned === 0 ? '4 4' : '0'}
            opacity={0.5}/>
        );
      })}

      {/* center */}
      <g transform={`translate(${cx},${cy})`}>
        <circle r="56" fill="white" stroke="#4F46E5" strokeWidth="2"/>
        <circle r="48" fill={emp.avatar}/>
        <text x="0" y="2" fontSize="20" fontWeight="700" fill="white" textAnchor="middle" dominantBaseline="middle">
          {emp.initials}
        </text>
        <text x="0" y="78" fontSize="13" fontWeight="700" fill="#0F1226" textAnchor="middle">{emp.name}</text>
        <text x="0" y="94" fontSize="11" fill="#6A6F8E" textAnchor="middle">{emp.role}</text>
      </g>

      {/* group nodes */}
      {positions.map((p, i) => {
        const ok = p.g.min === 0 || p.g.assigned >= p.g.min;
        const hasRaters = p.g.assigned > 0;
        return (
          <g key={i} transform={`translate(${p.x}, ${p.y})`}>
            <circle r="32" fill={hasRaters ? p.g.color : '#fff'} fillOpacity={hasRaters ? 0.12 : 1} stroke={hasRaters ? p.g.color : 'var(--border-strong)'} strokeWidth="1.5" strokeDasharray={hasRaters ? '0' : '3 3'}/>
            <text x="0" y="0" fontSize="11" fontWeight="700" fill={hasRaters ? p.g.color : '#9197B3'} textAnchor="middle" dominantBaseline="middle">
              {p.g.assigned}
            </text>
            <text x="0" y="14" fontSize="9" fill={hasRaters ? p.g.color : '#9197B3'} textAnchor="middle" dominantBaseline="middle" opacity="0.7">
              raters
            </text>
            {/* group label */}
            <text x="0" y="50" fontSize="11" fontWeight="700" fill="#0F1226" textAnchor="middle">{p.g.name}</text>
            {!ok && p.g.assigned > 0 && (
              <g transform="translate(22, -22)">
                <circle r="9" fill="#F59E0B"/>
                <text x="0" y="3" fontSize="10" fontWeight="700" fill="white" textAnchor="middle">!</text>
              </g>
            )}
          </g>
        );
      })}
    </svg>
  );
};

window.RaterScreen = RaterScreen;
