/* My Evaluations + Survey filling flow + Confirmation screen */

const MyEvaluationsScreen = ({ onStartSurvey }) => {
  const [filter, setFilter] = React.useState('All');
  const tabs = ['All', 'Not started', 'In progress', 'Submitted', 'Overdue'];
  const filtered = MY_EVALS.filter(e => filter === 'All' || e.status === filter);

  const counts = {
    'All': MY_EVALS.length,
    'Not started': MY_EVALS.filter(e => e.status === 'Not started').length,
    'In progress': MY_EVALS.filter(e => e.status === 'In progress').length,
    'Submitted':   MY_EVALS.filter(e => e.status === 'Submitted').length,
    'Overdue':     MY_EVALS.filter(e => e.status === 'Overdue').length,
  };

  return (
    <div className="fade-in">
      <div className="page-header">
        <div>
          <h1>My Evaluations</h1>
          <div className="subtitle">Surveys assigned to you. Your responses are anonymized before reaching managers and HR.</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-secondary"><Icon name="calendar" size={15}/> Calendar view</button>
        </div>
      </div>

      <div className="alert alert-info" style={{ marginBottom: 20 }}>
        <Icon name="shield" size={16}/>
        <div style={{ flex: 1 }}>
          <div className="alert-title">Your responses are confidential.</div>
          <div className="alert-body">Pulse360 separates your identity from your answers. Managers see <b>aggregated</b> rater group results only, never individual responses.</div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 20 }}>
        {tabs.map(t => (
          <button key={t} className={`chip ${filter === t ? 'active' : ''}`} onClick={() => setFilter(t)}>
            {t} <span style={{ color: 'var(--ink-400)', fontWeight: 500 }}>{counts[t]}</span>
          </button>
        ))}
      </div>

      <div className="grid grid-2">
        {filtered.map((e, i) => {
          const overdue = e.status === 'Overdue';
          const submitted = e.status === 'Submitted';
          return (
            <div key={i} className="card" style={{ padding: 18 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
                <Avatar name={e.person} color={e.avatar} initials={e.initials} size="md"/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                    <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink-900)' }}>{e.person}</div>
                    <Badge kind="info">{e.relationship}</Badge>
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 2 }}>{e.role}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-600)', marginTop: 8, padding: '4px 8px', background: 'var(--surface-alt)', border: '1px solid var(--border)', borderRadius: 6, display: 'inline-block' }}>
                    <Icon name="cycles" size={11} style={{ verticalAlign: -1 }}/> {e.cycle}
                  </div>
                </div>
                <Badge status={e.status}/>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginTop: 16, padding: 12, background: 'var(--surface-alt)', borderRadius: 10 }}>
                <div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Due</div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: overdue ? 'var(--danger-700)' : 'var(--ink-900)', marginTop: 2 }}>{e.due}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Time</div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-900)', marginTop: 2 }}>{e.estTime}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Questions</div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-900)', marginTop: 2 }}>{e.questionsTotal}</div>
                </div>
              </div>

              <div style={{ marginTop: 14 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontSize: 11.5, color: 'var(--ink-500)', fontWeight: 600 }}>Progress</span>
                  <span style={{ fontSize: 11.5, color: 'var(--ink-700)', fontWeight: 700 }}>{e.progress}%</span>
                </div>
                <Progress value={e.progress} tone={submitted ? 'success' : overdue ? 'danger' : 'default'}/>
              </div>

              <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
                {submitted ? (
                  <button className="btn btn-secondary" style={{ flex: 1 }}><Icon name="eye" size={13}/> View submission</button>
                ) : (
                  <button className="btn btn-primary" style={{ flex: 1 }} onClick={() => onStartSurvey(e)}>
                    {e.progress > 0 ? 'Continue' : 'Start'} evaluation <Icon name="chevright" size={13}/>
                  </button>
                )}
                <button className="btn btn-icon btn-secondary"><Icon name="more" size={14}/></button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

/* === Survey filling flow === */
const SURVEY_QUESTIONS = [
  { competency: 'Communication', text: 'Bu kişi ekipler arası iş birliği gerektiren konularda açık ve zamanında iletişim kurar.', type: 'likert', helper: 'Consider both written and verbal communication across teams.' },
  { competency: 'Teamwork', text: 'Actively supports teammates by sharing knowledge and offering help without being asked.', type: 'likert' },
  { competency: 'Accountability', text: 'Demonstrates ownership of commitments and follows through on deliverables, even when challenges arise.', type: 'likert' },
  { competency: 'Problem Solving', text: 'Breaks complex problems into clear, actionable steps and considers multiple options before deciding.', type: 'likert' },
  { competency: 'Customer Focus', text: 'Understands internal customer needs and adapts their approach to deliver meaningful outcomes.', type: 'likert' },
  { competency: 'Change Adaptability', text: 'Responds constructively to shifting priorities, ambiguity and new ways of working.', type: 'likert' },
  { competency: 'Leadership', text: 'Provides clear direction and creates space for the team to do their best work.', type: 'likert' },
  { competency: 'Open Feedback', text: 'In your own words: what should this person start, stop, or continue doing to grow over the next 6 months?', type: 'open' },
];

const LIKERT_OPTIONS = [
  { val: 1, label: 'Never Demonstrates' },
  { val: 2, label: 'Rarely Demonstrates' },
  { val: 3, label: 'Sometimes Demonstrates' },
  { val: 4, label: 'Usually Demonstrates' },
  { val: 5, label: 'Consistently Demonstrates' },
];

const SurveyScreen = ({ evaluation, onExit, onSubmitted }) => {
  const [idx, setIdx] = React.useState(0);
  const [answers, setAnswers] = React.useState({});

  const q = SURVEY_QUESTIONS[idx];
  const isLast = idx === SURVEY_QUESTIONS.length - 1;
  const isFirst = idx === 0;
  const progress = Math.round(((idx + (answers[idx] !== undefined ? 1 : 0)) / SURVEY_QUESTIONS.length) * 100);

  const setAnswer = (v) => setAnswers(a => ({ ...a, [idx]: v }));

  return (
    <div style={{ minHeight: '100vh', background: 'linear-gradient(180deg, #F7F8FC 0%, #EEF0FF 100%)', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 32px', borderBottom: '1px solid var(--border)', background: 'rgba(255,255,255,0.7)', backdropFilter: 'blur(12px)', position: 'sticky', top: 0, zIndex: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <button className="btn btn-icon btn-sm btn-ghost" onClick={onExit}><Icon name="chevleft" size={16}/></button>
          <div>
            <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink-900)' }}>{evaluation?.cycle || 'Q2 2026 Leadership 360'}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 1 }}>
              Evaluating <b style={{ color: 'var(--ink-700)' }}>{evaluation?.person || 'Aylin Demir'}</b> · {evaluation?.relationship || 'Peer'}
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ fontSize: 12, color: 'var(--ink-600)' }}>
            <Icon name="lock" size={12} style={{ verticalAlign: -2, marginRight: 4 }}/>
            Anonymous response
          </div>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-700)' }}>
            Question {idx + 1} of {SURVEY_QUESTIONS.length}
          </div>
          <button className="btn btn-sm btn-secondary"><Icon name="x" size={13}/> Exit</button>
        </div>
      </div>

      {/* Progress bar */}
      <div style={{ height: 4, background: 'var(--ink-100)' }}>
        <div style={{ height: '100%', width: `${progress}%`, background: 'linear-gradient(90deg, #4F46E5, #8B5CF6)', transition: 'width 0.35s ease' }}></div>
      </div>

      {/* Body */}
      <div style={{ flex: 1, display: 'flex', justifyContent: 'center', padding: '36px 24px 24px' }}>
        <div style={{ width: '100%', maxWidth: 760 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <Badge kind="info"><Icon name="competency" size={11}/> {q.competency}</Badge>
            <div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>{q.type === 'open' ? 'Open-ended · Optional' : 'Likert 1–5 · Required'}</div>
          </div>

          <div className="card" style={{ padding: 32 }}>
            <div style={{ fontSize: 11, color: 'var(--primary-600)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 14 }}>
              Question {idx + 1}
            </div>
            <div style={{ fontSize: 22, fontWeight: 600, color: 'var(--ink-900)', lineHeight: 1.4, letterSpacing: '-0.01em' }}>
              {q.text}
            </div>
            {q.helper && <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: 10 }}>{q.helper}</div>}

            <div style={{ marginTop: 28 }}>
              {q.type === 'likert' ? (
                <div className="likert">
                  {LIKERT_OPTIONS.map(o => (
                    <button key={o.val} className={`likert-btn ${answers[idx] === o.val ? 'selected' : ''}`} onClick={() => setAnswer(o.val)}>
                      <div className="num">{o.val}</div>
                      <div className="lbl">{o.label}</div>
                    </button>
                  ))}
                  <button className={`likert-btn na ${answers[idx] === 'NA' ? 'selected' : ''}`} onClick={() => setAnswer('NA')} style={{ borderStyle: 'dashed' }}>
                    <div className="num">N/A</div>
                    <div className="lbl">Not observed</div>
                  </button>
                </div>
              ) : (
                <div>
                  <textarea className="textarea" rows="6" placeholder="Share specific behaviors and examples. Your name will not be attached to this comment."
                    value={answers[idx] || ''} onChange={e => setAnswer(e.target.value)}/>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 11, color: 'var(--ink-500)' }}>
                    <span><Icon name="info" size={11} style={{ verticalAlign: -1 }}/> HR may mask comments that could reveal your identity.</span>
                    <span>{(answers[idx] || '').length} / 1000</span>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Nav */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 20 }}>
            <button className="btn btn-ghost"><Icon name="download" size={13}/> Save Draft</button>
            <div style={{ display: 'flex', gap: 8 }}>
              {!isFirst && (
                <button className="btn btn-secondary" onClick={() => setIdx(idx - 1)}>
                  <Icon name="chevleft" size={14}/> Previous
                </button>
              )}
              {!isLast ? (
                <button className="btn btn-primary" onClick={() => setIdx(idx + 1)} disabled={q.type === 'likert' && answers[idx] === undefined}>
                  Next question <Icon name="chevright" size={14}/>
                </button>
              ) : (
                <button className="btn btn-primary" onClick={onSubmitted}>
                  <Icon name="check" size={14}/> Submit Evaluation
                </button>
              )}
            </div>
          </div>

          {/* Mini dots */}
          <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginTop: 28 }}>
            {SURVEY_QUESTIONS.map((_, i) => (
              <button key={i} onClick={() => setIdx(i)} style={{
                width: i === idx ? 24 : 8, height: 8,
                borderRadius: 999,
                background: i === idx ? 'var(--primary-500)' : answers[i] !== undefined ? 'var(--primary-300)' : 'var(--ink-200)',
                transition: 'all 0.2s',
                cursor: 'pointer'
              }}></button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

const SurveyConfirmation = ({ onDone }) => (
  <div style={{ minHeight: '100vh', background: 'linear-gradient(180deg, #F7F8FC 0%, #EEF0FF 100%)', display: 'grid', placeItems: 'center', padding: 24 }}>
    <div className="card" style={{ maxWidth: 560, padding: 40, textAlign: 'center' }}>
      <div style={{ width: 76, height: 76, margin: '0 auto 20px', borderRadius: '50%', background: 'linear-gradient(135deg, #ECFDF5, #A7F3D0)', display: 'grid', placeItems: 'center', position: 'relative' }}>
        <div style={{ width: 52, height: 52, borderRadius: '50%', background: 'linear-gradient(135deg, #10B981, #047857)', display: 'grid', placeItems: 'center', color: 'white' }}>
          <Icon name="check" size={26}/>
        </div>
      </div>
      <h2 style={{ fontSize: 24, fontWeight: 700, color: 'var(--ink-900)', margin: 0, letterSpacing: '-0.01em' }}>Thank you for your feedback</h2>
      <p style={{ fontSize: 14, color: 'var(--ink-600)', marginTop: 12, lineHeight: 1.55 }}>
        Your feedback has been submitted securely.
      </p>
      <div className="alert alert-info" style={{ marginTop: 20, textAlign: 'left' }}>
        <Icon name="shield" size={16}/>
        <div>
          <div className="alert-title">Your individual response will not be shown directly in reports.</div>
          <div className="alert-body">Pulse360 aggregates responses by rater group. The person you evaluated will only see the group's combined results — never your individual ratings or comments.</div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'center', marginTop: 28 }}>
        <button className="btn btn-secondary" onClick={onDone}><Icon name="chevleft" size={14}/> Back to my evaluations</button>
        <button className="btn btn-primary" onClick={onDone}>Go to Dashboard <Icon name="chevright" size={14}/></button>
      </div>
    </div>
  </div>
);

Object.assign(window, { MyEvaluationsScreen, SurveyScreen, SurveyConfirmation });
