// Primus IQ — Profile Screen

const ProfileTagList = ({ items, editing, onChange, placeholder }) => {
  const [input, setInput] = React.useState('');
  const add = () => {
    const v = input.trim();
    if (v && !items.includes(v)) onChange([...items, v]);
    setInput('');
  };
  if (!editing) return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
      {items.length === 0
        ? <span style={{ fontSize: 13, color: 'var(--mute)' }}>—</span>
        : items.map(item => (
          <span key={item} style={{ padding: '3px 10px', borderRadius: 20, background: 'var(--maroon-06)', color: 'var(--maroon)', fontSize: 12, fontWeight: 500 }}>{item}</span>
        ))}
    </div>
  );
  return (
    <div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: items.length ? 6 : 0 }}>
        {items.map(item => (
          <span key={item} style={{ padding: '3px 10px', borderRadius: 20, background: 'var(--maroon-06)', color: 'var(--maroon)', fontSize: 12, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4 }}>
            {item}
            <button onClick={() => onChange(items.filter(i => i !== item))} style={{ width: 14, height: 14, border: 'none', background: 'none', cursor: 'pointer', color: 'var(--maroon)', fontSize: 14, padding: 0, lineHeight: 1 }}>×</button>
          </span>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 6 }}>
        <input value={input} onChange={e => setInput(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); add(); } }}
          placeholder={placeholder}
          style={{ flex: 1, height: 34, padding: '0 12px', borderRadius: 8, border: '1px solid var(--line-2)', background: 'white', fontSize: 13, fontFamily: 'inherit', color: 'var(--ink)' }}
        />
        <button onClick={add} className="btn-secondary" style={{ height: 34, padding: '0 12px', fontSize: 13 }}>Add</button>
      </div>
    </div>
  );
};

const ProfileInfoCard = ({ title, children }) => (
  <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 14, padding: 22, display: 'flex', flexDirection: 'column', gap: 16 }}>
    <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-2)', textTransform: 'uppercase', letterSpacing: '0.07em' }}>{title}</div>
    {children}
  </div>
);

const ProfileInfoField = ({ label, children }) => (
  <div>
    <div style={{ fontSize: 11, color: 'var(--mute)', fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', marginBottom: 5 }}>{label}</div>
    {children}
  </div>
);

const ScreenProfile = ({ currentUser, onBack }) => {
  const [profile, setProfile] = React.useState(null);
  const [editing, setEditing] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [fullName, setFullName] = React.useState('');
  const [yoe, setYoe] = React.useState('');
  const [primaryDomain, setPrimaryDomain] = React.useState('');
  const [secondaryDomain, setSecondaryDomain] = React.useState('');
  const [skills, setSkills] = React.useState([]);
  const [tools, setTools] = React.useState([]);
  const [methodologies, setMethodologies] = React.useState([]);
  const [industries, setIndustries] = React.useState([]);
  const [regions, setRegions] = React.useState([]);
  const [languages, setLanguages] = React.useState([]);

  React.useEffect(() => {
    PrimusAPI.getMe().then(data => {
      setProfile(data);
      setFullName(data.full_name || '');
      setYoe(String(data.yoe ?? ''));
      setPrimaryDomain(data.primary_domain || '');
      setSecondaryDomain(data.secondary_domain || '');
      setSkills(data.skills || []);
      setTools(data.tools || []);
      setMethodologies(data.methodologies || []);
      setIndustries(data.industries || []);
      setRegions(data.regions || []);
      setLanguages(data.languages || []);
    }).catch(() => {});
  }, []);

  const handleSave = async () => {
    setSaving(true);
    try {
      const updated = await PrimusAPI.updateMe({
        full_name: fullName,
        yoe: parseInt(yoe) || 0,
        primary_domain: primaryDomain,
        secondary_domain: secondaryDomain,
        skills, tools, methodologies, industries, regions, languages,
      });
      setProfile(updated);
      setEditing(false);
    } catch (ex) { console.error('Save profile failed:', ex); }
    finally { setSaving(false); }
  };

  const cancelEdit = () => {
    if (!profile) return;
    setFullName(profile.full_name || '');
    setYoe(String(profile.yoe ?? ''));
    setPrimaryDomain(profile.primary_domain || '');
    setSecondaryDomain(profile.secondary_domain || '');
    setSkills(profile.skills || []);
    setTools(profile.tools || []);
    setMethodologies(profile.methodologies || []);
    setIndustries(profile.industries || []);
    setRegions(profile.regions || []);
    setLanguages(profile.languages || []);
    setEditing(false);
  };

  if (!profile) return (
    <div style={contentArea}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
        <span style={{ fontSize: 13, color: 'var(--mute)' }}>Loading profile…</span>
      </div>
    </div>
  );

  const initials = profile.full_name
    ? profile.full_name.split(' ').filter(Boolean).map(w => w[0].toUpperCase()).slice(0, 2).join('')
    : '?';
  const designation = profile.designation
    ? profile.designation.split(/[\s_]/).map(w => w[0].toUpperCase() + w.slice(1)).join(' ')
    : '';
  const textInput = (value, setValue, placeholder = '') => ({
    value, onChange: e => setValue(e.target.value), placeholder,
    style: {
      width: '100%', height: 36, padding: '0 12px', borderRadius: 8,
      border: '1px solid var(--line-2)', background: 'white',
      fontSize: 13, fontFamily: 'inherit', color: 'var(--ink)',
    },
  });

  return (
    <div style={contentArea}>
      <div className="mobile-p-16" style={{ padding: '32px 48px 48px', maxWidth: 900, margin: '0 auto' }}>
        <button onClick={onBack} style={{ ...crumbBtn, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 22 }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M10 3L5 8l5 5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
          Back
        </button>

        {/* Header */}
        <div className="mobile-stack" style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 16, padding: '24px 28px', display: 'flex', alignItems: 'flex-start', gap: 20, marginBottom: 20 }}>
          <div style={{ width: 68, height: 68, borderRadius: 18, flexShrink: 0, background: 'var(--maroon)', color: 'white', display: 'grid', placeItems: 'center', fontSize: 24, fontWeight: 700 }}>{initials}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            {editing
              ? <input {...textInput(fullName, setFullName, 'Full name')} style={{ ...textInput(fullName, setFullName).style, fontSize: 20, fontWeight: 600, marginBottom: 8, height: 40 }}/>
              : <h1 className="serif" style={{ fontSize: 28, fontWeight: 500, margin: '0 0 6px', letterSpacing: '-0.02em' }}>{profile.full_name}</h1>
            }
            <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 14, color: 'var(--ink-2)' }}>{designation}</span>
              <span style={{ color: 'var(--mute)' }}>·</span>
              <span style={{ fontSize: 13, color: 'var(--mute)' }}>{profile.primus_email}</span>
              <span className={`role-badge`} style={{ background: 'var(--bg-soft)', color: 'var(--ink-2)', border: '1px solid var(--line-2)', borderRadius: 6, padding: '2px 8px', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{profile.tier}</span>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
            {editing ? (
              <>
                <button className="btn-secondary" onClick={cancelEdit} style={{ height: 36 }}>Cancel</button>
                <button className="btn-primary" onClick={handleSave} disabled={saving} style={{ height: 36 }}>{saving ? 'Saving…' : 'Save changes'}</button>
              </>
            ) : (
              <button className="btn-secondary" onClick={() => setEditing(true)} style={{ height: 36, display: 'flex', alignItems: 'center', gap: 6 }}>
                <svg width="13" height="13" viewBox="0 0 16 16" fill="none"><path d="M11 2l3 3L5 14H2v-3L11 2z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                Edit profile
              </button>
            )}
          </div>
        </div>

        {/* Info grid */}
        <div className="pi-grid-2" style={{ gap: 18 }}>
          <ProfileInfoCard title="Basic info">
            <ProfileInfoField label="Employee code">
              <span style={{ fontSize: 14, color: 'var(--ink)' }}>{profile.emp_code || '—'}</span>
            </ProfileInfoField>
            <ProfileInfoField label="Years of experience">
              {editing
                ? <input type="number" value={yoe} onChange={e => setYoe(e.target.value)} style={{ width: 100, height: 34, padding: '0 10px', borderRadius: 8, border: '1px solid var(--line-2)', background: 'white', fontSize: 13, fontFamily: 'inherit' }}/>
                : <span style={{ fontSize: 14, color: 'var(--ink)' }}>{profile.yoe ?? '—'} yrs</span>
              }
            </ProfileInfoField>
            <ProfileInfoField label="Tier">
              <span style={{ fontSize: 14, color: 'var(--ink)', textTransform: 'capitalize' }}>{profile.tier || '—'}</span>
            </ProfileInfoField>
          </ProfileInfoCard>

          <ProfileInfoCard title="Domain & expertise">
            <ProfileInfoField label="Primary domain">
              {editing
                ? <input {...textInput(primaryDomain, setPrimaryDomain, 'e.g. Financial Services')}/>
                : <span style={{ fontSize: 14, color: 'var(--ink)' }}>{profile.primary_domain || '—'}</span>
              }
            </ProfileInfoField>
            <ProfileInfoField label="Secondary domain">
              {editing
                ? <input {...textInput(secondaryDomain, setSecondaryDomain, 'e.g. Public Policy')}/>
                : <span style={{ fontSize: 14, color: 'var(--ink)' }}>{profile.secondary_domain || '—'}</span>
              }
            </ProfileInfoField>
            <ProfileInfoField label="Skills">
              <ProfileTagList items={skills} editing={editing} onChange={setSkills} placeholder="Add a skill, press Enter"/>
            </ProfileInfoField>
            <ProfileInfoField label="Tools">
              <ProfileTagList items={tools} editing={editing} onChange={setTools} placeholder="Add a tool, press Enter"/>
            </ProfileInfoField>
            <ProfileInfoField label="Methodologies">
              <ProfileTagList items={methodologies} editing={editing} onChange={setMethodologies} placeholder="Add a methodology, press Enter"/>
            </ProfileInfoField>
          </ProfileInfoCard>

          <ProfileInfoCard title="Industry & geography">
            <ProfileInfoField label="Industries">
              <ProfileTagList items={industries} editing={editing} onChange={setIndustries} placeholder="Add an industry, press Enter"/>
            </ProfileInfoField>
            <ProfileInfoField label="Regions">
              <ProfileTagList items={regions} editing={editing} onChange={setRegions} placeholder="Add a region, press Enter"/>
            </ProfileInfoField>
            <ProfileInfoField label="Languages">
              <ProfileTagList items={languages} editing={editing} onChange={setLanguages} placeholder="Add a language, press Enter"/>
            </ProfileInfoField>
          </ProfileInfoCard>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, {
  ProfileTagList,
  ProfileInfoCard,
  ProfileInfoField,
  ScreenProfile,
});
