// 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: 'var(--bg-card)', 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: 'var(--bg-card)', 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 ProfileTab = ({ active, onClick, children }) => (
  <button onClick={onClick} style={{
    padding: '8px 16px', borderRadius: 999,
    background: active ? 'var(--bg-soft)' : 'transparent',
    border: '1px solid', borderColor: active ? 'var(--line-2)' : 'transparent',
    fontSize: 13, fontWeight: active ? 600 : 500,
    color: active ? 'var(--ink)' : 'var(--mute)',
    cursor: 'pointer', fontFamily: 'inherit', transition: 'all 0.15s',
  }}>{children}</button>
);

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: 'var(--bg-card)',
      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: 'var(--bg-card)', 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: 'var(--bg-card)', 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>
  );
};

// ── Personalize Intelligence — its own module (opened from the sidebar) ──────
const ScreenPersonalize = ({ onBack }) => {
  const [prefs, setPrefs] = React.useState('');
  const [prefsSet, setPrefsSet] = React.useState(false);
  const [prefsLoading, setPrefsLoading] = React.useState(true);
  const [prefsSaving, setPrefsSaving] = React.useState(false);
  const [prefsMsg, setPrefsMsg] = React.useState(null);

  // Writing Style — five friendly fields the API composes into a SKILL.md the
  // report agent applies when drafting reports.
  const WS_FIELDS = [
    ['tone', 'Tone', 'e.g. Crisp and executive; confident, not salesy.'],
    ['structure', 'Structure', 'e.g. Lead with an executive summary, then detail.'],
    ['formatting', 'Formatting', 'e.g. Bullets for findings; tables for data.'],
    ['vocabulary', 'Vocabulary', 'e.g. Plain English; spell out acronyms once.'],
    ['avoid', 'Avoid', 'e.g. Hedging, filler, generic background.'],
  ];
  const [ws, setWs] = React.useState({ tone: '', structure: '', formatting: '', vocabulary: '', avoid: '' });
  const [wsLoading, setWsLoading] = React.useState(true);
  const [wsSaving, setWsSaving] = React.useState(false);
  const [wsMsg, setWsMsg] = React.useState(null);

  const [tab, setTab] = React.useState('instructions');

  React.useEffect(() => {
    PrimusAPI.getPreferences()
      .then(data => { setPrefs(data.content || ''); setPrefsSet(!!data.is_set); })
      .catch(() => {})
      .finally(() => setPrefsLoading(false));
  }, []);

  React.useEffect(() => {
    PrimusAPI.getWritingStyle()
      .then(data => { if (data && data.fields) setWs(data.fields); })
      .catch(() => {})
      .finally(() => setWsLoading(false));
  }, []);

  const handleSavePrefs = async () => {
    setPrefsSaving(true);
    setPrefsMsg(null);
    try {
      const updated = await PrimusAPI.updatePreferences(prefs);
      setPrefs(updated.content || '');
      setPrefsSet(true);
      setPrefsMsg({ type: 'ok', text: 'Instructions saved.' });
      setTimeout(() => setPrefsMsg(null), 2500);
    } catch (ex) {
      setPrefsMsg({ type: 'error', text: ex.message || 'Could not save your instructions.' });
    } finally { setPrefsSaving(false); }
  };

  const handleSaveWs = async () => {
    setWsSaving(true);
    setWsMsg(null);
    try {
      const updated = await PrimusAPI.updateWritingStyle(ws);
      if (updated && updated.fields) setWs(updated.fields);
      setWsMsg({ type: 'ok', text: 'Writing style saved.' });
      setTimeout(() => setWsMsg(null), 2500);
    } catch (ex) {
      setWsMsg({ type: 'error', text: ex.message || 'Could not save your writing style.' });
    } finally { setWsSaving(false); }
  };

  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>

        <h1 className="serif" style={{ fontSize: 28, fontWeight: 500, margin: '0 0 6px', letterSpacing: '-0.02em' }}>Personalize Intelligence</h1>
        <div style={{ fontSize: 13.5, color: 'var(--mute)', marginBottom: 18 }}>
          Tell Primus IQ how you want it to work.
        </div>

        <div style={{ display: 'flex', gap: 24, borderBottom: '1px solid var(--line)', marginBottom: 20 }}>
          {[['instructions', 'Custom Instructions'], ['style', 'Writing Style']].map(([key, label]) => (
            <button key={key} onClick={() => setTab(key)} style={{
              background: 'none', border: 'none', cursor: 'pointer', padding: '0 0 10px',
              fontSize: 14, fontFamily: 'inherit', fontWeight: tab === key ? 600 : 500,
              color: tab === key ? 'var(--ink)' : 'var(--mute)',
              borderBottom: tab === key ? '2px solid var(--maroon)' : '2px solid transparent',
              marginBottom: -1,
            }}>{label}</button>
          ))}
        </div>

        {tab === 'instructions' && (
        <div style={{ background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 14, padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-2)', textTransform: 'uppercase', letterSpacing: '0.07em' }}>Custom instructions</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
              {prefsMsg && (
                <span style={{ fontSize: 12, fontWeight: 600, color: prefsMsg.type === 'ok' ? '#2E6F40' : 'var(--maroon)' }}>
                  {prefsMsg.type === 'ok' ? '✓ ' : '⚠ '}{prefsMsg.text}
                </span>
              )}
              <button className="btn-primary" onClick={handleSavePrefs} disabled={prefsSaving || prefsLoading || prefs.length > 4000} style={{ height: 34 }}>{prefsSaving ? 'Saving…' : 'Save'}</button>
            </div>
          </div>
          {!prefsSet && !prefsLoading && (
            <div style={{ fontSize: 12, color: 'var(--maroon)', background: 'var(--maroon-06)', borderRadius: 8, padding: '6px 10px' }}>
              This is a starter template — edit it to fit how you work, then Save.
            </div>
          )}
          <textarea
            value={prefs}
            onChange={e => setPrefs(e.target.value)}
            placeholder={prefsLoading ? 'Loading…' : 'e.g. Always answer in tight bullets and cite sources.'}
            disabled={prefsLoading}
            style={{ width: '100%', padding: '12px 14px', borderRadius: 10, border: '1px solid var(--line-2)', background: 'var(--bg-card)', fontSize: 13, lineHeight: 1.6, fontFamily: 'inherit', color: 'var(--ink)', resize: 'vertical', minHeight: 220 }}
          />
          <div style={{ fontSize: 11, textAlign: 'right', color: prefs.length > 4000 ? 'var(--maroon)' : 'var(--mute)' }}>{prefs.length} / 4000</div>
        </div>
        )}

        {tab === 'style' && (
        <div style={{ background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 14, padding: 22, display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-2)', textTransform: 'uppercase', letterSpacing: '0.07em' }}>Writing style</div>
              <div style={{ fontSize: 12.5, color: 'var(--mute)', marginTop: 4 }}>How full reports are written for you. Applied when Primus IQ drafts a report.</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
              {wsMsg && (
                <span style={{ fontSize: 12, fontWeight: 600, color: wsMsg.type === 'ok' ? '#2E6F40' : 'var(--maroon)' }}>
                  {wsMsg.type === 'ok' ? '✓ ' : '⚠ '}{wsMsg.text}
                </span>
              )}
              <button className="btn-primary" onClick={handleSaveWs} disabled={wsSaving || wsLoading} style={{ height: 34 }}>{wsSaving ? 'Saving…' : 'Save'}</button>
            </div>
          </div>
          {WS_FIELDS.map(([name, label, placeholder]) => (
            <div key={name} style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
              <label style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{label}</label>
              <textarea
                value={ws[name] || ''}
                onChange={e => setWs(prev => ({ ...prev, [name]: e.target.value }))}
                placeholder={wsLoading ? 'Loading…' : placeholder}
                disabled={wsLoading}
                rows={2}
                style={{ width: '100%', padding: '10px 12px', borderRadius: 10, border: '1px solid var(--line-2)', background: 'var(--bg-card)', fontSize: 13, lineHeight: 1.55, fontFamily: 'inherit', color: 'var(--ink)', resize: 'vertical', minHeight: 56 }}
              />
            </div>
          ))}
        </div>
        )}
      </div>
    </div>
  );
};

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