// Editor screen — WYSIWYG resume with highlighted issues

function HighlightedText({ text, issues, onIssueClick, activeId }) {
  if (!issues || issues.length === 0) return <>{text}</>;
  // Build spans. Find each issue word in order.
  const parts = [];
  let cursor = 0;
  const sorted = [...issues].map(iss => ({ ...iss, idx: text.indexOf(iss.word, 0) })).filter(i => i.idx >= 0).sort((a,b) => a.idx - b.idx);
  sorted.forEach((iss, n) => {
    if (iss.idx > cursor) parts.push(<span key={`t${n}`}>{text.slice(cursor, iss.idx)}</span>);
    parts.push(
      <span key={iss.id}
        onClick={() => onIssueClick(iss)}
        className={ISSUE_META[iss.type]?.cls}
        style={{
          cursor: 'pointer', borderRadius: 3, padding: '0 2px',
          outline: activeId === iss.id ? `2px solid ${ISSUE_META[iss.type].color}` : 'none',
          outlineOffset: 1,
        }}>{iss.word}</span>
    );
    cursor = iss.idx + iss.word.length;
  });
  if (cursor < text.length) parts.push(<span key="tail">{text.slice(cursor)}</span>);
  return <>{parts}</>;
}

function EditorScreen({ platform, onBack, onFix, onIssueTap, onExport, fixedIds = new Set(), activeIssue }) {
  const [view, setView] = React.useState('resume'); // resume | list
  const issues = allIssues();
  const remaining = issues.filter(i => !fixedIds.has(i.id));

  const applyIfFixed = (text, issueList) => {
    // When the fix-all is applied, swap in the fixed copy.
    let out = text;
    issueList.forEach(iss => {
      if (fixedIds.has(iss.id) && FIXES[iss.id]) {
        out = out.replace(FIXES[iss.id].from, FIXES[iss.id].to);
      }
    });
    return out;
  };
  const liveIssues = (issueList) => issueList.filter(i => !fixedIds.has(i.id));

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fef9f0' }}>
      <PhoneHeader platform={platform} title="Jordan_Resume_v4" sub={`${remaining.length} issue${remaining.length === 1 ? '' : 's'}`} onBack={onBack}
        right={
          <div style={{ display: 'flex', gap: 6 }}>
            <button onClick={onExport} style={{ width: 36, height: 36, borderRadius: '50%', border: 'none', background: 'rgba(26,13,46,0.06)', color: '#1a0d2e', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }} title="download">
              <svg width="14" height="14" viewBox="0 0 20 20"><path d="M10 2v10m0 0l-4-4m4 4l4-4M3 17h14" stroke="#1a0d2e" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            <button style={{ width: 36, height: 36, borderRadius: '50%', border: 'none', background: 'rgba(26,13,46,0.06)', color: '#1a0d2e', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }} title="chat">
              <svg width="14" height="14" viewBox="0 0 20 20"><path d="M3 5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-4 4v-4H5a2 2 0 0 1-2-2V5z" stroke="#1a0d2e" strokeWidth="1.6" fill="none" strokeLinejoin="round"/></svg>
            </button>
            <button style={{ width: 36, height: 36, borderRadius: '50%', border: 'none', background: 'rgba(26,13,46,0.06)', color: '#1a0d2e', cursor: 'pointer', fontSize: 18 }}>⋯</button>
          </div>
        }
      />

      {/* view toggle */}
      <div style={{ padding: '0 20px 10px' }}>
        <div style={{ display: 'flex', background: '#f0ebe0', borderRadius: 100, padding: 4 }}>
          {['resume','issues'].map(v => (
            <button key={v} onClick={() => setView(v === 'resume' ? 'resume' : 'list')} style={{
              flex: 1, padding: '8px 12px', borderRadius: 100, border: 'none',
              background: (view === 'resume' && v === 'resume') || (view === 'list' && v === 'issues') ? '#1a0d2e' : 'transparent',
              color: (view === 'resume' && v === 'resume') || (view === 'list' && v === 'issues') ? '#fae14b' : '#6b5e88',
              fontFamily: 'Plus Jakarta Sans', fontWeight: 700, fontSize: 13, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>
              {v === 'resume' ? 'resume' : 'issues'}
              {v === 'issues' && <span style={{ background: '#ff8a7a', color: '#1a0d2e', fontSize: 11, padding: '1px 6px', borderRadius: 10 }}>{remaining.length}</span>}
            </button>
          ))}
        </div>
      </div>

      {view === 'resume' && (
        <div style={{ flex: 1, overflowY: 'auto', padding: '0 16px 8px' }} className="device-scroll">
          {/* resume paper */}
          <div style={{
            background: '#fff', borderRadius: 14, padding: '28px 24px',
            boxShadow: '0 4px 24px rgba(26,13,46,0.08)', color: '#1a0d2e',
            fontFamily: 'Plus Jakarta Sans, sans-serif', fontSize: 13, lineHeight: 1.55,
            marginBottom: 8,
          }}>
            {/* name */}
            <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 28, lineHeight: 1.1, letterSpacing: '-0.01em' }}>{RESUME.name}</div>
            <div style={{ fontSize: 13, color: '#6b5e88', marginTop: 2 }}>{RESUME.title}</div>
            <div style={{ fontSize: 10, color: '#6b5e88', marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 8, fontFamily: 'JetBrains Mono, monospace' }}>
              {RESUME.contact.map((c,i) => <span key={i}>{c}</span>)}
            </div>
            <hr style={{ border: 'none', borderTop: '1px solid #eee6d4', margin: '14px 0' }}/>

            {/* summary */}
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.15em', color: '#6b5e88', marginBottom: 4 }}>summary</div>
            <p style={{ margin: 0 }}>
              <HighlightedText text={applyIfFixed(RESUME.summary.text, RESUME.summary.issues)}
                issues={liveIssues(RESUME.summary.issues)}
                activeId={activeIssue?.id}
                onIssueClick={onIssueTap}/>
            </p>

            {/* experience */}
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.15em', color: '#6b5e88', margin: '16px 0 6px' }}>experience</div>
            {RESUME.experience.map((exp, ei) => (
              <div key={ei} style={{ marginBottom: 12 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <div style={{ fontWeight: 700, fontSize: 13 }}>{exp.role}, <span style={{ fontWeight: 500 }}>{exp.company}</span></div>
                  <div style={{ fontSize: 10, color: '#6b5e88', fontFamily: 'JetBrains Mono, monospace' }}>{exp.dates}</div>
                </div>
                <ul style={{ paddingLeft: 18, margin: '4px 0 0' }}>
                  {exp.bullets.map((b, bi) => (
                    <li key={bi} style={{ marginBottom: 4 }}>
                      <HighlightedText text={applyIfFixed(b.text, b.issues)}
                        issues={liveIssues(b.issues)}
                        activeId={activeIssue?.id}
                        onIssueClick={onIssueTap}/>
                    </li>
                  ))}
                </ul>
              </div>
            ))}

            {/* education */}
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.15em', color: '#6b5e88', margin: '8px 0 4px' }}>education</div>
            <div style={{ fontSize: 13 }}><strong>{RESUME.education.school}</strong> · {RESUME.education.degree}</div>

            {/* missing section prompt */}
            {liveIssues(RESUME.missingSections.map((s,i) => ({ id: `m${i}`, type: 'missing', word: s }))).length > 0 && (
              <div style={{
                marginTop: 14, padding: '10px 12px', borderRadius: 10,
                background: 'linear-gradient(90deg, rgba(255,77,184,0.1), rgba(138,92,246,0.1))',
                border: '1.5px dashed #ff4db8',
                fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: '#1a0d2e',
                cursor: 'pointer',
              }} onClick={() => onIssueTap({ id: 'm0', type: 'missing', word: 'Skills' })}>
                + missing: <strong>skills</strong> section — tap to add
              </div>
            )}
          </div>
        </div>
      )}

      {view === 'list' && (
        <div style={{ flex: 1, overflowY: 'auto', padding: '0 16px 8px' }} className="device-scroll">
          {remaining.length === 0 ? (
            <div style={{ textAlign: 'center', padding: 40 }}>
              <Auri score={95} size={120}/>
              <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 32, fontStyle: 'italic', color: '#1a0d2e', marginTop: 16 }}>all fixed ✨</div>
              <div style={{ fontFamily: 'Plus Jakarta Sans', fontSize: 14, color: '#6b5e88', marginTop: 8 }}>your aura is glowing.</div>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {remaining.map(iss => (
                <div key={iss.id} onClick={() => onIssueTap(iss)} style={{
                  background: '#fffdf7', borderRadius: 14, padding: '12px 14px',
                  border: '1px solid rgba(26,13,46,0.08)', display: 'flex', gap: 12, alignItems: 'flex-start',
                  cursor: 'pointer',
                }}>
                  <div style={{ width: 28, height: 28, borderRadius: 8, background: ISSUE_META[iss.type].color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Plus Jakarta Sans', fontWeight: 700, fontSize: 12, color: '#1a0d2e', flexShrink: 0 }}>
                    {ISSUE_META[iss.type].icon}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#6b5e88' }}>{ISSUE_META[iss.type].label} · {iss.section}</div>
                    <div style={{ fontFamily: 'Plus Jakarta Sans', fontSize: 14, fontWeight: 600, color: '#1a0d2e', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>"{iss.word}"</div>
                  </div>
                  <Chevron dir="right" color="#6b5e88"/>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* sticky fix-all + export bar */}
      <div style={{ padding: '10px 16px', paddingBottom: platform === 'ios' ? 34 : 20, background: 'linear-gradient(180deg, transparent, #fef9f0 30%)', display: 'flex', gap: 8 }}>
        {remaining.length > 0 ? (
          <>
            <PillButton variant="aura" onClick={onFix} style={{ flex: 1 }}>
              <Sparkle color="#fff"/> fix all {remaining.length}
            </PillButton>
            <PillButton variant="primary" onClick={onExport} style={{ flex: 1 }}>
              <svg width="14" height="14" viewBox="0 0 20 20"><path d="M10 2v10m0 0l-4-4m4 4l4-4M3 17h14" stroke="#fae14b" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
              download
            </PillButton>
          </>
        ) : (
          <PillButton variant="lemon" onClick={onExport} style={{ width: '100%' }}>
            <svg width="16" height="16" viewBox="0 0 20 20"><path d="M10 2v10m0 0l-4-4m4 4l4-4M3 17h14" stroke="#1a0d2e" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
            download resume
          </PillButton>
        )}
      </div>
    </div>
  );
}

window.EditorScreen = EditorScreen;
window.HighlightedText = HighlightedText;
