// WeWire applicant — Welcome + Status Tracker (home).

const STAGE_ICON = {
  application: 'user', aptitude: 'brain', critical: 'spark', analytical: 'chart',
  sjt: 'chat', written: 'edit', case: 'brief', interview: 'star',
};

// ── Welcome / entry ──────────────────────────────────────────
function ScreenWelcome({ onBegin, onResume, applyClose, daysLeft }) {
  const closingSoon = daysLeft != null && daysLeft >= 0 && daysLeft <= 7;
  return (
    <div style={{ minHeight: '100%', height: '100%', background: WW.ink, display: 'flex', flexDirection: 'column',
      padding: '64px 24px 36px', boxSizing: 'border-box', color: WW.cream, position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: -80, right: -90, width: 320, height: 320, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(255,77,7,0.55), transparent 65%)', filter: 'blur(8px)' }} />
      <img src="../assets/wewire-logo-cream.svg" alt="WeWire" style={{ height: 26, position: 'relative', display: 'block' }} />

      {closingSoon && (
        <Card pad={14} style={{ marginTop: 24, background: 'rgba(255,77,7,0.2)', border: '1px solid rgba(255,113,57,0.4)', color: WW.cream }}>
          <div style={{ fontSize: 13, lineHeight: 1.5 }}>
            <b>{daysLeft === 0 ? 'Last day' : `${daysLeft} day${daysLeft === 1 ? '' : 's'} left`}</b> — applications close {applyClose || '24 July 2026'}.
          </div>
        </Card>
      )}

      <div style={{ flex: 1 }} />
      <Eyebrow color="rgba(251,247,240,0.6)">Graduate Program · Class of 2026</Eyebrow>
      <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 46, lineHeight: 1.0, letterSpacing: '-0.03em',
        margin: '18px 0 0', color: WW.cream }}>Welcome.<br/>Let's begin<br/>your story.</h1>
      <p style={{ marginTop: 18, fontSize: 16, lineHeight: 1.55, color: 'rgba(251,247,240,0.72)', maxWidth: 320 }}>
        Milestone 1 is automatic (70% on each assessment). Milestone 2 is reviewed by our team before anyone is invited to interview.
      </p>
      <div style={{ flex: 1 }} />

      <Btn variant="primary" full onClick={onBegin} icon="arrow" style={{ marginBottom: 14 }}>Begin your application</Btn>
      <div style={{ textAlign: 'center', fontSize: 13, color: 'rgba(251,247,240,0.6)' }}>
        Already started?{' '}
        <u style={{ cursor: 'pointer', color: WW.cream }} onClick={onResume}>Sign in to continue</u>
      </div>
    </div>
  );
}

// ── Stage row ────────────────────────────────────────────────
function StageRow({ stage, state, score, onClick, editable }) {
  const done = state === 'done', current = state === 'current', invited = state === 'invited';
  const locked = state === 'locked', failed = state === 'failed';
  const active = current || invited;
  const clickable = current || invited || (done && !!editable);
  const bg = failed ? WW.redSoft : active ? WW.orangeSoft : WW.white;
  const showScore = score != null && stage.kind !== 'form' && stage.kind !== 'written' && stage.kind !== 'case' && stage.kind !== 'interview';

  return (
    <div onClick={clickable ? onClick : undefined} style={{
      display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px', borderRadius: 18,
      background: bg, border: `1px solid ${active ? 'transparent' : failed ? WW.red : WW.line}`,
      boxShadow: active ? `inset 0 0 0 1.5px ${WW.orange}` : '0 2px 8px rgba(27,24,19,0.03)',
      cursor: clickable ? 'pointer' : 'default', opacity: locked ? 0.55 : 1,
      transition: 'transform 160ms ease', position: 'relative',
    }}>
      <div style={{ width: 44, height: 44, borderRadius: 13, flex: 'none', display: 'grid', placeItems: 'center',
        background: failed ? WW.red : done ? WW.green : active ? WW.orange : WW.sand,
        color: (done || active || failed) ? '#fff' : WW.subtle }}>
        {done ? <Icon name="check" size={22} /> : failed ? <Icon name="x" size={20} /> : invited ? <Icon name="star" size={20} /> : locked ? <Icon name="lock" size={18} /> : <Icon name={STAGE_ICON[stage.key]} size={20} />}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontFamily: DISP, fontWeight: 600, fontSize: 11, color: WW.subtle, letterSpacing: '0.08em' }}>{stage.n}</span>
          {current && <Chip tone="warm" style={{ padding: '2px 8px', fontSize: 10 }}>In progress</Chip>}
          {invited && <Chip tone="warm" style={{ padding: '2px 8px', fontSize: 10 }}>Invited</Chip>}
          {done && !editable && <Chip tone="green" style={{ padding: '2px 8px', fontSize: 10 }}>Complete</Chip>}
          {done && editable && <Chip tone="neutral" style={{ padding: '2px 8px', fontSize: 10 }}>Edit</Chip>}
          {failed && <Chip tone="neutral" style={{ padding: '2px 8px', fontSize: 10, background: WW.redSoft, color: WW.red }}>Below 70%</Chip>}
          {locked && stage.invite && <Chip tone="neutral" style={{ padding: '2px 8px', fontSize: 10 }}>By invitation</Chip>}
        </div>
        <div style={{ fontFamily: DISP, fontWeight: 600, fontSize: 16, letterSpacing: '-0.01em', marginTop: 2,
          color: locked || failed ? WW.muted : WW.ink }}>{stage.name}</div>
      </div>
      {showScore && (
        <span style={{ fontSize: 14, fontWeight: 700, color: score >= 70 ? WW.green : WW.red, flex: 'none' }}>{score}%</span>
      )}
      {clickable && <Icon name="next" size={18} color={WW.subtle} />}
    </div>
  );
}

function MilestoneSection({ milestone, stageIndices, stages, done, scores, status, onOpenStage, locked, failed, editableStageIndices = new Set() }) {
  const m1Count = WWFunnel.FUNNEL.milestone1Count;
  const m2Count = WWFunnel.FUNNEL.milestone2Count;
  let complete = false;
  let active = false;

  if (milestone.id === 1) {
    complete = done >= m1Count && WWFunnel.passedMilestone1(scores);
    active = done < m1Count || (done >= m1Count && !WWFunnel.passedMilestone1(scores) && !failed);
  } else if (milestone.id === 2) {
    complete = done >= m1Count + m2Count;
    active = WWFunnel.passedMilestone1(scores) && done >= m1Count && done < m1Count + m2Count;
  } else {
    complete = done >= stages.length;
    active = WWFunnel.interviewInvited(status) && done >= m1Count + m2Count && !complete;
  }

  const sectionLocked = locked || (milestone.id === 2 && !WWFunnel.passedMilestone1(scores) && done >= m1Count);

  return (
    <div style={{ marginBottom: 18, opacity: sectionLocked && milestone.id > 1 ? 0.72 : 1 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 10, padding: '0 4px' }}>
        <div style={{ width: 28, height: 28, borderRadius: 8, flex: 'none', display: 'grid', placeItems: 'center',
          background: failed ? WW.redSoft : complete ? WW.greenSoft : active ? WW.orangeSoft : WW.sand,
          color: failed ? WW.red : complete ? WW.green : active ? WW.orangeDeep : WW.muted,
          fontFamily: DISP, fontWeight: 700, fontSize: 13 }}>
          {complete ? <Icon name="check" size={14} /> : milestone.id}
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: DISP, fontWeight: 600, fontSize: 17, letterSpacing: '-0.02em', color: WW.ink }}>
            Milestone {milestone.id} · {milestone.name}
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 6 }}>
            {milestone.gate === 'automatic' && (
              <Chip tone="warm" style={{ padding: '2px 8px', fontSize: 10 }}>Automatic gate</Chip>
            )}
            {milestone.gate === 'manual' && (
              <Chip tone="neutral" style={{ padding: '2px 8px', fontSize: 10 }}>Manual team review</Chip>
            )}
            {milestone.invite && (
              <Chip tone="neutral" style={{ padding: '2px 8px', fontSize: 10 }}>Invitation only</Chip>
            )}
          </div>
          <div style={{ fontSize: 12.5, color: WW.muted, lineHeight: 1.45, marginTop: 6 }}>{milestone.blurb}</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, paddingLeft: 4 }}>
        {stageIndices.map((i) => {
          const s = stages[i];
          let state;
          const breakdown = WWFunnel.milestone1Breakdown(scores);
          const timedEntry = breakdown.find((b) => b.key === s.key);
          const stageFailed = timedEntry && timedEntry.score != null && !timedEntry.passed && i < done;

          if (s.invite) {
            if (i < done) state = 'done';
            else if (WWFunnel.interviewInvited(status) && done === i) state = 'invited';
            else state = 'locked';
          } else if (sectionLocked && i >= WWFunnel.FUNNEL.milestone1Count) {
            state = 'locked';
          } else if (stageFailed && WWFunnel.milestone1Complete(done)) {
            state = 'failed';
          } else if (i < done) {
            state = 'done';
          } else if (i === done) {
            state = 'current';
          } else {
            state = 'locked';
          }

          return (
            <StageRow
              key={s.key}
              stage={s}
              state={state}
              score={scores[s.key]}
              onClick={() => onOpenStage(i)}
              editable={editableStageIndices.has(i)}
            />
          );
        })}
      </div>
    </div>
  );
}

// ── Home / status tracker ────────────────────────────────────
function ScreenHome({ name, email, done, scores, status, onOpenStage, onSignOut, applicationsOpen }) {
  const { STAGES, PROGRAM, MILESTONES } = window.WWData;
  const funnel = WWFunnel.funnelState({ done, scores, status: status || 'in_progress' });
  const total = STAGES.length;
  const editableStageIndices = React.useMemo(() => {
    const set = new Set();
    if (done > 0 && done < total) set.add(0);
    return set;
  }, [done, total]);
  const m1 = WWFunnel.FUNNEL.milestone1Count;
  const m2 = WWFunnel.FUNNEL.milestone2Count;

  let heroTitle, heroBody, heroPct, ctaLabel, ctaIdx, showCta = true;

  if (funnel.phase === 'complete') {
    heroTitle = 'All milestones complete';
    heroBody = 'You\'ve done everything we asked. We look forward to meeting you in Accra.';
    heroPct = 1;
    showCta = false;
  } else if (funnel.phase === 'milestone1_failed') {
    heroTitle = 'Milestone 1 · Automatic rejection';
    heroBody = 'You needed at least 70% on each timed assessment. This gate is scored automatically — your application will not advance to Milestone 2.';
    heroPct = m1 / total;
    showCta = false;
  } else if (funnel.phase === 'milestone2_rejected') {
    heroTitle = 'Application not advancing';
    heroBody = 'Our team reviewed your Written Response and Take-home Case. You have not been shortlisted for a final interview at this time.';
    heroPct = (m1 + m2) / total;
    showCta = false;
  } else if (funnel.phase === 'under_review') {
    heroTitle = 'Awaiting team review';
    heroBody = 'Milestone 2 is complete. Unlike the assessments, this stage is reviewed manually — we\'ll be in touch if you\'re shortlisted to book your final interview in Accra.';
    heroPct = (m1 + m2) / total;
    showCta = false;
  } else if (funnel.phase === 'interview_invited') {
    heroTitle = 'You\'re shortlisted';
    heroBody = 'Congratulations — you\'re through to the final round. Book your in-person interview at WeWire HQ, Accra.';
    heroPct = (m1 + m2) / total;
    ctaLabel = 'Schedule interview';
    ctaIdx = total - 1;
  } else if (funnel.phase === 'milestone2') {
    const stepInM2 = done - m1 + 1;
    heroTitle = `Milestone 2 · Step ${stepInM2} of ${m2}`;
    heroBody = <>Next up: <b style={{ color: WW.cream }}>{STAGES[done].name}</b>. Submit both parts — our team will review manually before anyone moves to interview.</>;
    heroPct = (done) / total;
    ctaLabel = done === m1 ? 'Continue' : 'Continue';
    ctaIdx = done;
  } else {
    heroTitle = `Milestone 1 · Step ${Math.min(done + 1, m1)} of ${m1}`;
    heroBody = <>Next up: <b style={{ color: WW.cream }}>{STAGES[Math.min(done, total - 1)].name}</b>. {STAGES[Math.min(done, total - 1)].blurb}</>;
    heroPct = done / total;
    ctaLabel = done === 0 ? 'Start' : 'Continue';
    ctaIdx = done;
  }

  const milestoneStageMap = MILESTONES.map((m) =>
    m.stageKeys.map((key) => STAGES.findIndex((s) => s.key === key)).filter((i) => i >= 0)
  );

  return (
    <Screen>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <Eyebrow>Your application</Eyebrow>
          <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 28, letterSpacing: '-0.02em', marginTop: 6 }}>
            Hi {name || 'there'}.
          </h1>
          {email && (
            <div style={{ fontSize: 12, color: WW.subtle, marginTop: 4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              Signed in as {email}
            </div>
          )}
        </div>
        <div style={{ width: 44, height: 44, borderRadius: '50%', background: WW.ink, color: WW.cream,
          display: 'grid', placeItems: 'center', fontFamily: DISP, fontWeight: 600, fontSize: 16, flex: 'none' }}>
          {(name || email || 'A')[0].toUpperCase()}
        </div>
      </div>

      {!applicationsOpen && (
        <Card pad={14} style={{ background: WW.orangeSoft, border: 'none', marginBottom: 14 }}>
          <div style={{ fontSize: 13, color: WW.orangeDeep, lineHeight: 1.5 }}>
            Applications are closed. You can still complete outstanding stages or view your progress.
          </div>
        </Card>
      )}

      <Card pad={20} style={{ marginBottom: 18, background: WW.ink, border: 'none', color: WW.cream }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span style={{ fontFamily: DISP, fontWeight: 600, fontSize: 15, whiteSpace: 'nowrap' }}>{heroTitle}</span>
          <span style={{ fontSize: 13, color: 'rgba(251,247,240,0.7)' }}>{Math.round(heroPct * 100)}%</span>
        </div>
        <div style={{ marginTop: 12 }}>
          <ProgressBar value={heroPct} track="rgba(251,247,240,0.16)" fill={WW.orange} />
        </div>
        <div style={{ marginTop: 16, fontSize: 14, color: 'rgba(251,247,240,0.72)', lineHeight: 1.5 }}>
          {heroBody}
        </div>
        {showCta && (
          <Btn variant="primary" full style={{ marginTop: 16, height: 48 }} icon={funnel.phase === 'interview_invited' ? 'star' : 'arrow'}
            onClick={() => onOpenStage(ctaIdx)}>
            {ctaLabel}
          </Btn>
        )}
      </Card>

      <Eyebrow style={{ margin: '4px 4px 12px' }}>Your milestones</Eyebrow>
      {MILESTONES.map((m, idx) => (
        <MilestoneSection
          key={m.id}
          milestone={m}
          stageIndices={milestoneStageMap[idx]}
          stages={STAGES}
          done={done}
          scores={scores}
          status={status}
          onOpenStage={onOpenStage}
          failed={funnel.phase === 'milestone1_failed'}
          locked={funnel.phase === 'milestone1_failed' && m.id > 1}
          editableStageIndices={editableStageIndices}
        />
      ))}

      <div style={{ textAlign: 'center', marginTop: 22, fontSize: 12, color: WW.subtle, lineHeight: 1.5 }}>
        15 graduates · In person at WeWire HQ, Accra<br/>Applications close {PROGRAM.applyClose}
        {onSignOut && (
          <>
            <br/>
            <button type="button" onClick={onSignOut} style={{ background: 'none', border: 'none', color: WW.muted,
              fontWeight: 600, cursor: 'pointer', fontSize: 12, marginTop: 8, fontFamily: FONT }}>
              Sign out
            </button>
          </>
        )}
      </div>
    </Screen>
  );
}

Object.assign(window, { ScreenWelcome, ScreenHome, StageRow, STAGE_ICON });
