/* Evaluation Cycles screen + Create Cycle wizard */
const CYCLE_TYPES = [
  { name: '360 Feedback',       icon: 'cycles',  tint: 'tint-indigo',  desc: 'Multi-rater: self + manager + peers + direct reports' },
  { name: '180 Evaluation',     icon: 'users',   tint: 'tint-violet',  desc: 'Manager + self, supplemented with optional peer set' },
  { name: 'Peer Review',        icon: 'team',    tint: 'tint-sky',     desc: 'Colleagues evaluate colleagues at the same level' },
  { name: 'Manager Review',     icon: 'user',    tint: 'tint-mint',    desc: 'Manager-led performance evaluation' },
  { name: 'Upward Feedback',    icon: 'arrow_up',tint: 'tint-amber',   desc: 'Direct reports provide feedback to leaders' },
  { name: 'Pulse Survey',       icon: 'pulse',   tint: 'tint-rose',    desc: 'Short, recurring temperature checks (5–10 questions)' },
  { name: 'Engagement Survey',  icon: 'sparkle', tint: 'tint-violet',  desc: 'Annual or biannual engagement & climate measurement' },
  { name: 'Department Survey',  icon: 'dept',    tint: 'tint-emerald', desc: 'Tailored questions for a single department or BU' },
];

const CyclesScreen = () => {
  const [filter, setFilter] = React.useState('All');
  const [showWizard, setShowWizard] = React.useState(false);
  const [query, setQuery] = React.useState('');

  const tabs = ['All', 'Active', 'Draft', 'Reporting', 'Closed', 'Archived'];
  const filtered = CYCLES.filter(c =>
    (filter === 'All' || c.status === filter) &&
    (query === '' || c.name.toLowerCase().includes(query.toLowerCase()) || c.type.toLowerCase().includes(query.toLowerCase()))
  );

  return (
    <div className="fade-in">
      <div className="page-header">
        <div>
          <h1>Evaluation Cycles</h1>
          <div className="subtitle">Plan, launch and monitor every survey-based evaluation across the organization.</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-secondary"><Icon name="download" size={15}/> Export</button>
          <button className="btn btn-primary" onClick={() => setShowWizard(true)}>
            <Icon name="plus" size={15}/> Create Cycle
          </button>
        </div>
      </div>

      <div className="grid grid-4" style={{ marginBottom: 20 }}>
        <StatCard icon="cycles"  tint="tint-indigo" label="Active cycles"       value="6" foot="3 closing this week"/>
        <StatCard icon="myeval"  tint="tint-violet" label="In-flight responses" value="952" delta="+248" deltaDir="up" foot="last 24h"/>
        <StatCard icon="warning" tint="tint-amber"  label="Anonymity flags"     value="3" foot="below min. threshold"/>
        <StatCard icon="check"   tint="tint-emerald"label="Closed this quarter" value="11" delta="+4" deltaDir="up"/>
      </div>

      <div className="table-wrap">
        <div className="table-toolbar">
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {tabs.map(t => (
              <button key={t} className={`chip ${filter === t ? 'active' : ''}`} onClick={() => setFilter(t)}>
                {t}
                <span style={{ color: 'var(--ink-400)', fontWeight: 500 }}>
                  {t === 'All' ? CYCLES.length : CYCLES.filter(c => c.status === t).length}
                </span>
              </button>
            ))}
          </div>
          <div style={{ flex: 1 }}></div>
          <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: 32, padding: '0 12px 0 32px', width: 220, fontSize: 12.5 }}
              placeholder="Search cycles…" value={query} onChange={e => setQuery(e.target.value)}/>
          </div>
          <button className="btn btn-sm btn-secondary"><Icon name="filter" size={14}/> Filters</button>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 32 }}><div className="checkbox"></div></th>
              <th>Cycle Name</th>
              <th>Type</th>
              <th>Target Population</th>
              <th>Start</th>
              <th>End</th>
              <th>Status</th>
              <th style={{ minWidth: 180 }}>Completion</th>
              <th style={{ width: 100 }}></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(c => (
              <tr key={c.id}>
                <td><div className="checkbox"></div></td>
                <td>
                  <div className="cell-emph">{c.name}</div>
                  <div className="cell-sub">{c.id} · Owner: {c.owner}</div>
                </td>
                <td>
                  <Badge kind="info">{c.type}</Badge>
                </td>
                <td style={{ color: 'var(--ink-700)' }}>{c.target}</td>
                <td style={{ color: 'var(--ink-600)' }}>{c.start}</td>
                <td style={{ color: 'var(--ink-600)' }}>{c.end}</td>
                <td><Badge status={c.status}/></td>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Progress value={c.completion} tone="auto"/>
                    <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-800)', minWidth: 36, textAlign: 'right' }}>{c.completion}%</span>
                  </div>
                </td>
                <td>
                  <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
                    <button className="btn btn-icon btn-sm btn-ghost" title="View"><Icon name="eye" size={14}/></button>
                    <button className="btn btn-icon btn-sm btn-ghost" title="Edit"><Icon name="edit" size={14}/></button>
                    <button className="btn btn-icon btn-sm btn-ghost" title="More"><Icon name="more" size={14}/></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showWizard && <CycleWizard onClose={() => setShowWizard(false)}/>}
    </div>
  );
};

/* === Multi-step wizard === */
const WIZARD_STEPS = [
  'Basic Information',
  'Evaluation Type',
  'Target Employees',
  'Rater Groups',
  'Survey Template',
  'Privacy Rules',
  'Review & Launch'
];

const CycleWizard = ({ onClose }) => {
  const [step, setStep] = React.useState(0);
  const [state, setState] = React.useState({
    name: 'Q3 2026 Engineering 360',
    objective: 'Establish baseline competency scores for engineering managers ahead of mid-year talent review.',
    cycleType: '360 Feedback',
    targetMode: 'Department',
    departments: ['Engineering'],
    raters: { Self: true, Manager: true, Peer: true, 'Direct Report': true, 'Internal Customer': false, 'External Customer': false, 'Matrix Manager': false },
    minPeers: 4,
    minReports: 3,
    template: 'Engineering Team Review',
    anonymity: true,
    threshold: 4,
    hideComments: false,
    maskIdentity: true,
    separateData: true,
    retention: '24 months',
    start: '2026-06-02',
    end: '2026-06-23',
  });

  const update = (k, v) => setState(s => ({ ...s, [k]: v }));
  const goNext = () => setStep(s => Math.min(WIZARD_STEPS.length - 1, s + 1));
  const goPrev = () => setStep(s => Math.max(0, s - 1));

  return (
    <div className="modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" style={{ maxWidth: 1080, padding: 0, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr', minHeight: 620, maxHeight: '92vh' }}>
          {/* Side */}
          <div className="wizard-side">
            <div className="wizard-brand">Pulse360 · Cycle Builder</div>
            <h2>Create a new<br/>evaluation cycle</h2>
            <div className="wizard-sub">Seven guided steps. You can save and return at any time — nothing goes live until you press <em>Launch</em>.</div>
            <div>
              {WIZARD_STEPS.map((s, i) => (
                <div key={s} className={`wizard-step ${i === step ? 'active' : ''} ${i < step ? 'done' : ''}`} onClick={() => setStep(i)}>
                  <div className="ws-num">{i < step ? <Icon name="check" size={13}/> : i + 1}</div>
                  <div>
                    <div className="ws-name">{s}</div>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 'auto', paddingTop: 24, fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>
              <Icon name="lock" size={12} style={{ verticalAlign: -2 }}/>{' '}
              All identity ↔ response data flows are encrypted at rest. Anonymity rules apply automatically.
            </div>
          </div>
          {/* Body */}
          <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
            <div className="modal-header">
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--primary-600)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Step {step + 1} of {WIZARD_STEPS.length}</div>
                <div className="modal-title" style={{ marginTop: 2 }}>{WIZARD_STEPS[step]}</div>
              </div>
              <button className="btn btn-icon btn-sm btn-ghost" onClick={onClose}><Icon name="x" size={16}/></button>
            </div>
            <div className="modal-body" style={{ flex: 1 }}>
              <WizardBody step={step} state={state} update={update}/>
            </div>
            <div className="modal-footer">
              <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
              <div style={{ display: 'flex', gap: 8 }}>
                <button className="btn btn-secondary">Save as draft</button>
                {step > 0 && <button className="btn btn-secondary" onClick={goPrev}><Icon name="chevleft" size={14}/> Back</button>}
                {step < WIZARD_STEPS.length - 1
                  ? <button className="btn btn-primary" onClick={goNext}>Continue <Icon name="chevright" size={14}/></button>
                  : <button className="btn btn-primary" onClick={onClose}><Icon name="check" size={14}/> Launch cycle</button>
                }
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const WizardBody = ({ step, state, update }) => {
  if (step === 0) return (
    <div style={{ maxWidth: 620 }}>
      <div className="field">
        <label>Cycle name</label>
        <input className="input" value={state.name} onChange={e => update('name', e.target.value)}/>
        <span className="hint">Visible to participants. Use a clear, dated label.</span>
      </div>
      <div className="field">
        <label>Objective</label>
        <textarea className="textarea" rows="3" value={state.objective} onChange={e => update('objective', e.target.value)}/>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <div className="field">
          <label>Start date</label>
          <input type="date" className="input" value={state.start} onChange={e => update('start', e.target.value)}/>
        </div>
        <div className="field">
          <label>End date</label>
          <input type="date" className="input" value={state.end} onChange={e => update('end', e.target.value)}/>
        </div>
      </div>
      <div className="field">
        <label>Cycle owner</label>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: 8, border: '1px solid var(--border)', borderRadius: 10, background: 'var(--surface-alt)' }}>
          <Avatar name="Defne Aydın" color="#6B73F0"/>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Defne Aydın</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>HR Business Partner · People Analytics</div>
          </div>
        </div>
      </div>
    </div>
  );

  if (step === 1) return (
    <div>
      <p style={{ fontSize: 13, color: 'var(--ink-600)', marginTop: 0, marginBottom: 20 }}>
        Pick the evaluation pattern. Rater groups, anonymity defaults and reporting templates adapt automatically.
      </p>
      <div className="grid grid-2" style={{ gap: 12 }}>
        {CYCLE_TYPES.map(t => (
          <div key={t.name}
            onClick={() => update('cycleType', t.name)}
            style={{
              padding: 14, borderRadius: 14, border: '1.5px solid',
              borderColor: state.cycleType === t.name ? 'var(--primary-500)' : 'var(--border)',
              background: state.cycleType === t.name ? 'linear-gradient(180deg, var(--primary-50), white)' : 'var(--surface)',
              cursor: 'pointer', display: 'flex', gap: 12, alignItems: 'flex-start',
              boxShadow: state.cycleType === t.name ? '0 0 0 4px rgba(79, 70, 229, 0.1)' : 'none'
            }}>
            <div className={`stat-icon ${t.tint}`} style={{ width: 38, height: 38, marginBottom: 0, flexShrink: 0 }}>
              <Icon name={t.icon} size={18}/>
            </div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink-900)' }}>{t.name}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 3, lineHeight: 1.45 }}>{t.desc}</div>
            </div>
            {state.cycleType === t.name && (
              <div style={{ marginLeft: 'auto' }}>
                <div className="checkbox on"></div>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );

  if (step === 2) return (
    <div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
        {['Department', 'Role family', 'Manual selection', 'Saved segment'].map(m => (
          <button key={m} className={`chip ${state.targetMode === m ? 'active' : ''}`} onClick={() => update('targetMode', m)}>{m}</button>
        ))}
      </div>
      <div className="field">
        <label>Departments included</label>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {DEPARTMENTS.map(d => {
            const on = state.departments.includes(d);
            return (
              <button key={d} className={`chip ${on ? 'active' : ''}`} onClick={() => {
                update('departments', on ? state.departments.filter(x => x !== d) : [...state.departments, d]);
              }}>
                {on ? <Icon name="check" size={12}/> : <Icon name="plus" size={12}/>} {d}
              </button>
            );
          })}
        </div>
      </div>
      <div className="card" style={{ marginTop: 16, background: 'var(--surface-alt)' }}>
        <div className="card-body" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }}>
          <div><div style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Selected</div><div style={{ fontSize: 22, fontWeight: 700, marginTop: 4 }}>186</div><div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>employees</div></div>
          <div><div style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Managers</div><div style={{ fontSize: 22, fontWeight: 700, marginTop: 4 }}>28</div><div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>~ 15%</div></div>
          <div><div style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Avg. tenure</div><div style={{ fontSize: 22, fontWeight: 700, marginTop: 4 }}>3.2 yr</div></div>
          <div><div style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Languages</div><div style={{ fontSize: 22, fontWeight: 700, marginTop: 4 }}>EN · TR</div></div>
        </div>
      </div>
    </div>
  );

  if (step === 3) return (
    <div>
      <p style={{ fontSize: 13, color: 'var(--ink-600)', marginTop: 0, marginBottom: 16 }}>
        Which rater perspectives will be invited? Anonymity thresholds protect identities when groups are too small.
      </p>
      <div className="grid grid-2" style={{ gap: 10 }}>
        {Object.keys(state.raters).map(g => (
          <div key={g} style={{
            padding: 14, borderRadius: 12, border: '1px solid var(--border)',
            display: 'flex', alignItems: 'center', gap: 12,
            background: state.raters[g] ? 'linear-gradient(180deg, var(--primary-50), white)' : 'var(--surface)'
          }}>
            <div className={`stat-icon ${g === 'Self' ? 'tint-indigo' : g === 'Manager' ? 'tint-violet' : g === 'Peer' ? 'tint-sky' : g === 'Direct Report' ? 'tint-mint' : 'tint-amber'}`} style={{ width: 34, height: 34, marginBottom: 0 }}>
              <Icon name={g === 'Self' ? 'user' : g === 'Manager' ? 'flag' : 'users'} size={16}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 13.5 }}>{g}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>
                {g === 'Peer' ? `Min ${state.minPeers} raters required` : g === 'Direct Report' ? `Min ${state.minReports} raters required` : 'No minimum'}
              </div>
            </div>
            <div className={`switch ${state.raters[g] ? 'on' : ''}`} onClick={() => update('raters', { ...state.raters, [g]: !state.raters[g] })}></div>
          </div>
        ))}
      </div>
    </div>
  );

  if (step === 4) return (
    <div>
      <div className="field">
        <label>Choose template</label>
        <span className="hint">Templates can be cloned and customized in the Survey Templates section.</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {TEMPLATES.slice(0, 5).map(t => (
          <div key={t.name} onClick={() => update('template', t.name)} style={{
            padding: 14, borderRadius: 12,
            border: '1.5px solid', borderColor: state.template === t.name ? 'var(--primary-500)' : 'var(--border)',
            background: state.template === t.name ? 'var(--primary-50)' : 'var(--surface)',
            cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14
          }}>
            <div className={`stat-icon ${t.tint}`} style={{ width: 38, height: 38, marginBottom: 0 }}>
              <Icon name="template" size={17}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 13.5 }}>{t.name}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>{t.questions} questions · {t.coverage} competencies · {t.type}</div>
            </div>
            <Badge status={t.status}/>
          </div>
        ))}
      </div>
    </div>
  );

  if (step === 5) return (
    <div style={{ maxWidth: 640 }}>
      <div className="alert alert-info" style={{ marginBottom: 18 }}>
        <Icon name="shield" size={16}/>
        <div>
          <div className="alert-title">Anonymity is treated as a contract with raters.</div>
          <div className="alert-body">When a rater group has fewer responses than the threshold, scores and comments for that group are hidden from the report — they are not just blurred.</div>
        </div>
      </div>
      {[
        ['Enable anonymous feedback',          'anonymity'],
        ['Hide individual comments in reports','hideComments'],
        ['Mask identity-revealing comments',   'maskIdentity'],
        ['Separate identity from response data','separateData'],
      ].map(([label, key]) => (
        <div key={key} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{label}</div>
          </div>
          <div className={`switch ${state[key] ? 'on' : ''}`} onClick={() => update(key, !state[key])}></div>
        </div>
      ))}
      <div className="field" style={{ marginTop: 18 }}>
        <label>Minimum rater threshold per group</label>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <input type="range" min="2" max="10" value={state.threshold} onChange={e => update('threshold', +e.target.value)} style={{ flex: 1 }}/>
          <span style={{ fontSize: 18, fontWeight: 700, color: 'var(--primary-600)', minWidth: 32, textAlign: 'center' }}>{state.threshold}</span>
        </div>
        <span className="hint">Groups with fewer responses than this number will be excluded from individual reports.</span>
      </div>
      <div className="field">
        <label>Data retention period</label>
        <select className="select" value={state.retention} onChange={e => update('retention', e.target.value)}>
          <option>12 months</option><option>24 months</option><option>36 months</option><option>60 months</option>
        </select>
      </div>
    </div>
  );

  if (step === 6) return (
    <div style={{ maxWidth: 720 }}>
      <div className="alert alert-success" style={{ marginBottom: 18 }}>
        <Icon name="check" size={16}/>
        <div>
          <div className="alert-title">Ready to launch</div>
          <div className="alert-body">186 participants will be invited via email & Teams. Reminders will be sent on day 7 and day 14. You'll get a daily completion digest.</div>
        </div>
      </div>
      {[
        ['Cycle name', state.name],
        ['Type', state.cycleType],
        ['Target', `${state.targetMode} · ${state.departments.join(', ')} · 186 employees`],
        ['Rater groups', Object.entries(state.raters).filter(([_, v]) => v).map(([k]) => k).join(', ')],
        ['Template', state.template],
        ['Anonymity threshold', `${state.threshold} raters minimum`],
        ['Window', `${state.start} → ${state.end}`],
      ].map(([k, v], i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '180px 1fr', padding: '12px 0', borderBottom: '1px solid var(--border)', fontSize: 13 }}>
          <div style={{ color: 'var(--ink-500)', fontWeight: 500 }}>{k}</div>
          <div style={{ fontWeight: 600, color: 'var(--ink-900)' }}>{v}</div>
        </div>
      ))}
    </div>
  );

  return null;
};

Object.assign(window, { CyclesScreen, CycleWizard });
